Tutorial :jQuery: Updating an option's text inside a select after the option has already been added?


I've searched all around for a solution and have found nothing. Here is some sample code:

$('#myselect').append(     '<option id=\'myoption\'></option>'    );  $('#mytextfield').change(function() {   $('#myoption').html($(this).val);  });  

so, i want to change the select option's html whenever my text field is changed. any ideas? thanks!


Apart from the missing () on val, writing innerHTML of an <option> is generally unreliable due to how browsers implement form fields, and writing the innerHTML of anything from user input is highly inadvisableâ€"what if the user typed something with < or & symbols in?

Use the standard DOM text property to change the label text instead, eg.:

var myoption= new Option();  $('#myselect').append(myoption);  $('#mytextfield').change(function() {      myoption.text= this.value;  });  

(or $(this).val() if you must, but I think the plain-DOM version is more readable.)


val is a function. I'm not sure if this is the reason for youyr problem as you didn't say what result or error you are getting...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »