Reset Select Menu to default in the on change event

问题: hello i'm trying to reset the select menu to the defaul option immediatly after new item is selected. I never want the select menu to show the selected item. I have this se...

问题:

hello i'm trying to reset the select menu to the defaul option immediatly after new item is selected. I never want the select menu to show the selected item. I have this select menu:

<select name="new-effect" id="new-effect">
    <option selected value="add">Add New Effect</option>
    <option value="waves">Waves</option>
    <option value="spiral">Spiral</option>
</select>

which is handled by

$( function() {
    $( "#new-effect" ).selectmenu({
        change: function( event, data ){            
            add_new_effect(data.item.value);
        }
    });
});

It gets the value, but i can't get it to reset. I've tried the following:

$("#new-effect").val("");
$("#new-effect").val("add");
$("#new-effect").prop('selectedIndex',0);

None of them work and they all result in selected item being shown


回答1:

If you're just trying to reset the select element back to a default value, there's a couple ways to do it. Here's is one way that will work:

https://jsfiddle.net/mswilson4040/gnLkyexa/5/

<select placeholder="Select a value..." id="new-effect">
  <option selected value="add" class="default-selection">Add New Effect</option>
  <option value="waves">Waves</option>
  <option value="spiral">Spiral</option>
</select>

const defaultOption = $('#new-effect').find('.default-selection');
$('#new-effect').change(e => {
  const value = $('#new-effect').val();
  console.log(value);
  $('#new-effect').val(defaultOption.val());
});

Basically, you need to capture the default value that you want to reset everytime. Once you have that, in your change event, obtain the selected value and do what you need to with it. After that is done, you can then just set the select dropdown back to the value you need it to.

The selected attribute in the HTML is fine to have for the initial render, but that will go away once someone changes the value (which is why you can't rely on it for everything).


回答2:

Add this to your CSS

option:checked {
  display:none;
}

If you only need this to happen for a specific list, then change the selector to #new-effect option:checked.

Now for your JS, do this

$("#new-effect").change(function(e) {
  e.target.value = 'add';
});

If you have more than one list, you'll want to programatically select the default option instead of hardcoding it like I did here.

  • 发表于 2019-01-12 05:47
  • 阅读 ( 18 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除