0

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.

<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>

$("#boxes").contents().find(":checkbox").bind('change', function(){        
val = this.checked;
var $obj = $(this);    
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
    //Do stuff
}
else
{
    $obj.attr('checked', false);
}
}

This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".

var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");

I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?

1 Answer 1

1

Those are variables, and they need to be concentenated into the string in the selector, like so:

$('input[name="' + group + '"][value="Basic"]').prop("checked");

A simplified version:

$("#boxes input[type='checkbox']").on('change', function(){        
   var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");

    if( this.value == "Advanced" && bT) {
        //Do stuff
    } else {
        $(this).prop('checked', false);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, caught it after writing the question that a variable didn't belong in a string. The added quotes for it aren't needed, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.