0

Im trying to dynamically check a checkbox using JQuery 1.5, based on something the user selects from a dropdown list. When the list changes it returns to this function:

function displaySystemResults(html){
    var v = html.split(",");
    document.getElementById('fUpdateSystemName').value = v[0];
        if (v[1] == "true"){
            alert("true");
            $('#fUpdateActiveFlag').setAttribute('checked','checked');
        }
    }

Here is the dropdown list:

<td valign="top"><form:checkbox path="fUpdateActiveFlag"
name='fUpdateActiveFlag' value="checked" />&nbsp;</td>

I can't get the checkbox to put a tick in the box. Can anyone spot what im doing wrong? I know its hitting the setAttribute method as the alert box is displaying when it should be set to true.

1
  • setAttribute() is a method exposed by DOM elements, not jQuery objects. You're probably looking for attr("checked", "checked") or prop("checked", true) or $("#fUpdateActiveFlag")[0].setAttribute("checked", "checked"). Commented Mar 7, 2013 at 10:21

1 Answer 1

2

$('#fUpdateActiveFlag') is the ID selector.

add it to your checkbox

<td valign="top"><form:checkbox ID="fUpdateActiveFlag" path="fUpdateActiveFlag"
name='fUpdateActiveFlag' value="checked" />&nbsp;</td>

Also, jQuery function is incorrect. setAttribute is the JavaScript function, while it looks like you're using jQuery selector, hence the object you select is jQuery object, which does not have a method called setAttribute, instead, use .attr():

$('#fUpdateActiveFlag').attr('checked','checked')

see working example http://jsfiddle.net/ruslans/8xp9g/

Edit: as per @Dementic 's comment below, you can keep using the name attribute, but then you'll have to change your selector to:

$('[name="fUpdateActiveFlag"]').attr('checked','checked');

see working example: http://jsfiddle.net/ruslans/A4D8f/

Sign up to request clarification or add additional context in comments.

5 Comments

or, if you do not want to change the markup $('[name="fUpdateActiveFlag"]').attr('checked', true);
name attribute isn't unique, so I reckon it's best to set an ID here.
@Tsar and Dementic - thank you both for your responses. Tsar, I couldnt get my code working with your suggestion but Dementic, your code works perfectly so thanks for that! I will accept this as the answer
use prop() over attr() in newer versions of jquery
@Johan - not exactly, have a good read stackoverflow.com/questions/5874652/prop-vs-attr

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.