简体   繁体   中英

jquery .val() not returning correct value

In the below function I want to show and hide an element based on other options selected on the page (radio buttons). The problem is, the var complianceMember always returns the first value for the set of radio buttons it's part of and not the selected value, why is this? The other two variables return the correct values.

$(document).ready(function() {
    $('input[name="waste-management-plan"]').change(function () {

        var producerType = $('input[name="producertype"]').val();
        var complianceMember = $('input[name="compliance-member"]').val();

        if ($(this).val() == 'Y' && complianceMember == 'Y' && producerType == 'both' ) {
            $('.producerOp3').show();
        } else {
            $('.producerOp3').hide();
            console.log( $(this).val(),complianceMember,producerType );
        }
    });
});

You need to use a filter to find the checked radio button and then get its value. You can use the :checked selector

var complianceMember = $('input[name="compliance-member"]:checked').val();

因为您提到了单选组,所以必须获取选中的单选按钮的值

var complianceMember = $('input[name="compliance-member"]:checked').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM