开发者

How to 'narrow' onchange for specific id?

开发者 https://www.devze.com 2023-03-29 01:33 出处:网络
I found this cod on jquery web $(\"select\").change(function () { var str = \"\"; $(\"select option:selected\").each(function () {

I found this cod on jquery web

$("select").change(function () {
      var str = "";
      $("select option:selected").each(function () {
            str += $(this).text() + " ";
          });
      $("div").text(str);
    })
    .change();

I can use it for I want but I want this function to be fired only for #my_id. I tried to insert #my_id after both selects but then the function does nothing.

I though I could bind this func开发者_开发技巧tion to only select with specific id.


That works fine for select#my_id:

http://jsfiddle.net/ambiguous/wAU5w/

Did you use select #my_id (note the space) my mistake?

The select#my_id selector matches the <select id="my_id"> element, the select #my_id matches anything with and id="my_id" that is a child of a <select>.


as in?

$("#my_id").change(function () {
  var str = "";
  $("#my_id :selected").each(function () {
        str += $(this).text() + " ";
      });
  $("div").text(str);
})
.change();


This will only work for < select > elements. You shouldn't need it but try this:

$("select#my_id").change...

also make sure it's wrapped in

$(document).ready(function(){

});

To make sure the DOM is ready


If your select is labeled my_id than just swap

select

for

#my_id

in the two places where it occurs in the script.


Maybe this:

$("select#my_id").change(function() {
    var selOpts = jQuery.map($(":selected", $(this)), function(opt, index) {
        return $(opt).text();
    });
    $("div").text(selOpts.join(" "));
}).change();
0

精彩评论

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