Click here to Skip to main content
15,887,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I want to add options with value and text to select using JQuery, I have no problem doing this but I want the new option to be selected for this I added the selected attribute but in html it insert the selected attribute to all options.
is it possible to add selected attribute to new option only.

HTML
<select name="theFee" id="theFee">
<option selected="selected" value="3">2021-01</option>
<option selected="selected" value="3">2021-02</option>
<option selected="selected" value="3">2021-03</option>
</select>


Hope I explained my problem.
Please help.

What I have tried:

JavaScript
$("#addFee").click(function(){
      var ft = $("#feetypeid").val();
      var fm = $("#formonth").val();
      $("#theFee").append($('<option selected="selected"></option>').val(ft).html(fm));
    });
Posted
Updated 7-Jan-21 0:17am
Comments
F-ES Sitecore 6-Jan-21 13:03pm    
They're all selected because....they're all selected? :) You have selected="selected" in all of your options in the html.
nyt1972 6-Jan-21 13:16pm    
yes in html they are all selected bcoz from JQuery it add selected to each option, and thats I want to ask that how can I add to the new option only.

1 solution

Use jQuery's val method to set the value of the list after adding the new option.
JavaScript
$("#addFee").click(function(){
    var ft = $("#feetypeid").val();
    var fm = $("#formonth").val();
    $("#theFee").append($("<option/>").val(ft).html(fm)).val(ft);
});
Demo[^]

NB: Since the <select> will only submit the value of the selected item, it doesn't make sense to have multiple options with the same value. If you do, val will select the first option with the specified value.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900