jquery - Check if options exist, append them if they don't exist and set one option to "selected" -


1) following code append options on selected value

  $('#product').on('change',function(){    if($(this).val()!=='free'){     $("#license option:selected").remove();    $("#license").append("<option value=''> -- select --</option>").attr('selected','selected');    $("#license").append("<option value='1'>1</option>").val('licenza');    $("#license").append("<option value='2'>2</option>").val('2');    $("#license").append(" <option value='3'>3</option>").val('3');     }else{    $("#license").find('option').remove().end().append("<option value='free'>    free</option>").val('free');     }                  }); 

the problem on each change in select id= "#product" 4 options appended. in place need insert .length check if options existing?

2) also, if options not existing , appended select id="#license", cannot set first option value ( "--select--" option) selected one.

i have tried

   .attr('selected','selected'); 

but won't work;

hope explanation clear enough. appreciated.

edit

here's link unterstand situation

$("#license").append("<option value=''> -- select --</option>").attr('selected','selected'); $("#license").append("<option value='1'>1</option>").val('licenza'); $("#license").append("<option value='2'>2</option>").val('2'); $("#license").append(" <option value='3'>3</option>").val('3'); 

.val(), attr('selected','selected') method here use add attributes license select... adding attribute value , selected license select...

you can remove .val() , .attr() , place on append string... this:

$("#license").append("<option value='' selected> -- select --</option>"); $("#license").append("<option value='licenza'>licenza</option>"); $("#license").append("<option value='2'>2</option>"); $("#license").append(" <option value='3'>3</option>"); 

fiddle sample


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -