问题描述:

i have this so when page loads gets value and if true to show a msg which worked but when i used change the change did not so i then used live change function which worked when you changed but now the default check on load does not? any ideas around this?

$(document).ready(function() {

var target = $('.product-options select').find(":selected").val();

if(target == "2" || target == "4"){

$(".beans-msg").html("would you like beans?").show();

} else {

$(".beans-msg").hide();

}

console.log(target);

$('.product-options select').live('change',function(){

var changedVal = $(this).find(":selected").val();

if(changedVal == "2" || changedVal == "4"){

$(".beans-msg").html("would you like beans?").show();

} else {

$(".beans-msg").hide();

}

console.log(changedVal);

});

});

网友答案:

If it's jQuery 1.5.2, on() is not supported, but try something like this :

$(document).ready(function () {
    $('.product-options select').live('change', function() {
        var beans = $.trim( this.value );
        if (beans == "2" || beans == "4") {
            $(this).closest('tr')
                   .find(".beans-msg")
                   .html("would you like beans?").show();
        } else {
            $(this).closest('tr')
                   .find(".beans-msg")
                   .hide();
        }
        console.log(beans);
    }).trigger('change');
});

If the change function works, just trigger it on pageload ?

网友答案:
$(document).ready(function() {   
var x = $('.product-options').find(':selected').val();        
        if (x == "2" || x == "4")
            $('.beans-msg').html("would you like beans?").show();
        $('.product-options').live('change',function(){                
            var changedVal = $(this).find(':selected').val();                
                if(changedVal == "2" || changedVal == "4"){
                    $('.beans-msg').html("would you like beans?").show();
                } else {
                    $('.beans-msg').hide();
                }
            });
        });

fiddle here

相关阅读:
Top