简体   繁体   中英

How to empty a value from the first option of a select box option using javascript or jquery?

Here's my code. Is it possible to empty the value of the first option using jquery/javascript ?

<select id="select_1" name="select_1" class="category-select required">
<option value="0">Select category</option>
<option value="1">Phones</option>
<option value="2">Computers</option>
<option value="3">Tablets</option>
</select>

so it will become like that:

<option value="">Select category</option>

I already know that i can remove the whole first option by targeting its value

$("#select_1 option[value='0']").remove();

您可以使用纯JavaScript来使用.options这样的方法来获取select元素的第一个选项,这样会返回索引集合,因此您可以使用基于零的索引来获取第一个选项并设置其value属性:

document.getElementById("select_1").options[0].value = '';

To target the first element of a collection use :first . Then you can use val('') to remove the value from it:

 $('#select_1 option:first').val(''); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="select_1" name="select_1" class="category-select required"> <option value="0">Select category</option> <option value="1">Phones</option> <option value="2">Computers</option> <option value="3">Tablets</option> </select> 

<script>
$(document).ready(function (){

 $('#btnremoveoption').click(function (){
   $('#select_1 option:first').remove();
 });

});

</script>
<body>
    <select id="select_1" name="select_1" class="category-select required">
      <option value="0">Select category</option>
      <option value="1">Phones</option>
      <option value="2">Computers</option>
      <option value="3">Tablets</option>
    </select>
<input type="button" id="btnremoveoption" value="Click to Remove all Options" onclick="Remove_options()"/>
</body>

This Program will keep Removing first option when ever button will be click.

$(document).ready(function (){


   $('#select_1 option:first').remove();


});

this will remove it onload of the page. without leaving the option blank it will be filled with the next option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM