开发者

Is there a better way of getting the selected option than string concatenation?

开发者 https://www.devze.com 2023-03-14 17:06 出处:网络
I have this: function addSelectOnChange(select_id,selected_cb) { $(select_id).live(\"change\",function() {

I have this:

function addSelectOnChange(select_id,selected_cb) {
    $(select_id).live("change",function() {
         var value = $(select_id + " option:selected").val();
         if(value) {
             selected_cb(value);
         }
    });
}
开发者_开发技巧

Is there another way of telling jQuery that I want to get the selected option, than by concatenating the selector?


Have a look at the examples of .val(). You can do:

var value = $(select_id).val();

Better in this case:

var value = $(this).val();

or even (see HTMLSelectElement):

var value = this.value;


You don't need to add the filter.

Just do $(selector).val() on a dropdown and jquery will give you the selected value.

0

精彩评论

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