开发者

Dynamically set default selection in html with jQuery

I am using the following line of code to dynamically set the default selection of a selection box in html with jQuery

   var y=...a value from the DB;
   this.$(".status option[value=y]").attr("selected", "selected");

However, this only work if I replace it manually by saying option[value=3], I can't use a variable here.

I have already made sure what's from the DB is one of the o开发者_Python百科ption. Thanks


The simplest way to do this is to use the jQuery val method:

$(".status").val(y);

If you want to continue selecting the correct option and setting the selected attribute, then @redsquare's answer should do the trick, but note that you can also use prop instead of attr if you're using a later version of jQuery.


In your scenario you need the following

$(".status option[value=" + y + "]").attr("selected", true);

However a better way is to do what James Allardice suggests in his answer by using .val().

The best way would be to set this in your server side scripts and avoid any script whatsoever!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜