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.

user207421
  • 305,947
  • 44
  • 307
  • 483
maloney
  • 1,633
  • 3
  • 26
  • 49
  • `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")`. – Frédéric Hamidi Mar 07 '13 at 10:21

1 Answers1

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/

Ruslan
  • 9,927
  • 15
  • 55
  • 89