Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

onchange - Jquery select change not firing

I need to capture when a select box changes, should be simple!

    $('#multiid').change(function(){
    alert('Change Happened');
});

But it does not work, I suspected the problem is that the select box does not exist on document ready it is created only if needed, so I created it empty in HTML, populated it with code as a test but that didn't work either.

function buildmulti(id,name,price) {
    // build action items for action bar
    var optlist = $('<select></select>').attr('id', 'multiid').attr('name', 'multiid');
    optlist.append('<option value="0">Select Size</option>');
    $.each(option, function(index, val) {
        if(val.prodID *1  == id * 1) {
            v = val.ID;
            fprice = price * 1 + val.pricechange * 1;
            t = name + ' - ' + val.variation +  ' - ' + currency + (fprice).toFixed(2);
            optlist.append('<option value="' + v + '">' + t + '</option>');
        }
    })
    $('#addbasket').append(optlist);
};

it's probably another bracket out of place, but I can't find it!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try

 $(document).on('change','#multiid',function(){
    alert('Change Happened');
});

As your select-box is generated from the code, so you have to use event delegation, where in place of $(document) you can have closest parent element.

Or

$(document.body).on('change','#multiid',function(){
    alert('Change Happened');
});

Update:

Second one works fine, there is another change of selector to make it work.

$('#addbasket').on('change','#multiid',function(){
    alert('Change Happened');
});

Ideally we should use $("#addbasket") as it's the closest parent element [As i have mentioned above].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...