开发者

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'开发者_如何学JAVA).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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜