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

36
August 24, 2019, at 09:40 AM

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();
Answer 1

You can use plain javascript to get the first option of a select element using .options like so, which returns an indexed collection, so you can just use zero based index to grab the first option and set it's value property:

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

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>

Answer 3
<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.

Answer 4
$(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.

READ ALSO
How can I disable button and change the button text on this code?

How can I disable button and change the button text on this code?

I dont know very well jquery/javascript and I am having problems with the code below

26
Getting values from data attribute into an array [duplicate]

Getting values from data attribute into an array [duplicate]

This question already has an answer here:

22
Add mouse pan on left mouse button on 2D graph created with D3.js fork 3D Force-Directed Graph

Add mouse pan on left mouse button on 2D graph created with D3.js fork 3D Force-Directed Graph

I try to make a 2D graph by using 3D Force Directed Graph (that is using D3js, https://github

18