checkbox always returning false

2019-07-30 13:43发布

问题:

I've read a few articles talking about checkboxes always returning a false state, but haven't found anything about my own problem.

So, here is the script:

<script type="text/javascript">
    function update_contact(id, name) {
        alert("idCont : " + id + "\n nameCKB : " + name + "\n state : "
                + $(this).attr('checked'));
        var a = location.pathname.substring(1).split('/')
        $.ajax({
            url : '@Url.Action("update_contact")',
            type : 'POST',
            data : {
                name : name,
                isChecked : $(this).is(':checked'),
                idOpp : a[2],
                idCont : id
            },
            success : function(result) {
            }
        });
    };
</script>

And here is the checkbox's code :

@If mail = False Then
    @<input type="checkbox" name="mailed" id="mailed" class="mailed" onclick="update_contact(@item.idContact.toString() , 'mailed')" />
Else
    @<input type="checkbox" name="mailed" id="mailed" class="mailed" onclick="update_contact(@item.idContact.toString() , 'mailed')" checked="checked" />
End If

And here is the code generated by the server :

<input name="mailed" id="mailed" class="mailed" onclick="update_contact(1 , 'mailed')" type="checkbox">

In the beginning, I used a Html helper. It was returning smth like that:

<input id="mailed" name="mailed" onclick="update_contact(1 ,'mailed')" value="true" type="checkbox">
<input name="mailed" value="false" type="hidden">

I though it was due to the second input that it was always returning a false state.

回答1:

The problem is likely that this is not what you think it is. Try explicitly passing a reference to the clicked checkbox to your function:

@If mail = False Then
      @<input type="checkbox" name="mailed" id="mailed" class="mailed" onclick="update_contact(@item.idContact.toString() , 'mailed', this)" />
Else
      @<input type="checkbox" name="mailed" id="mailed" class="mailed" onclick="update_contact(@item.idContact.toString() , 'mailed', this)" checked="checked" />
End If

And then:

    function update_contact(id, name, cb) {
        alert("idCont: " + id + "\n nameCKB: " + name + "\n state: " + cb.checked);
        // you could say $(cb).attr("checked"), but cb.checked is more efficient
        // and easier to read
        var a = location.pathname.substring(1).split('/')
        $.ajax({
            url: '@Url.Action("update_contact")',
            type: 'POST',
            data: { 
                    name: name, 
                    isChecked: cb.checked, 
                    idOpp: a[2], 
                    idCont: id
            },
            success: function (result) {}
        });
    };

Alternatively use jQuery to assign the click handler and it will set this for you correctly. You could put the @item.idContact.toString() in the value attribute and then access it using this.value in your handler:

@If mail = False Then
      @<input type="checkbox" name="mailed" id="mailed" class="mailed" value="@item.idContact.toString()" />
Else
      @<input type="checkbox" name="mailed" id="mailed" class="mailed" value="@item.idContact.toString()" checked="checked" />
End If

And then:

 $(document).ready(function() {
    $("#mailed").click(function() {
        alert("idCont: " + this.value + "\n nameCKB: " + this.name + "\n state: " + this.checked);
        // you could say $(this).attr("checked"), but this.checked is more efficient
        // and easier to read
        var a = location.pathname.substring(1).split('/')
        $.ajax({
            url: '@Url.Action("update_contact")',
            type: 'POST',
            data: { 
                    name: this.name, 
                    isChecked: this.checked, 
                    idOpp: a[2], 
                    idCont: this.value
            },
            success: function (result) {}
        });
    });
});

(Note: I don't actually know the VB/razor syntax, I'm just guessing on that part.)



回答2:

Try this (working fiddle here: http://jsfiddle.net/Ac3kd/):

<script type="text/javascript">
    function update_contact(id, name) {
        var source = $('#'+name);
        alert("idCont : " + id + "\n nameCKB : " + name + "\n state : " + source.attr('checked'));
        var a = location.pathname.substring(1).split('/')
        $.ajax({
            url: '@Url.Action("update_contact")',
            type: 'POST',
            data: { 
                    name: name, 
                    isChecked: source.is(':checked'), 
                    idOpp: a[2], 
                    idCont: id
            },
            success: function (result) {}
        });
    };
</script>


回答3:

Mamoo is correct: $.ajax is a jQuery object, so $(this) won't point to the element that called the update_contact function. Instead of creating two variables (source ans a) as mamoo does, I'd create the var data just before the $.ajax bit:

function update_contact(id,name)
{
    var data = {name: name, 
                isChecked: $(this).is(':checked'), 
                idOpp: location.pathname.substring(1).split('/')[2], 
                idCont: id};
    $.ajax({
            url: '@Url.Action("update_contact")',
            type: 'POST',
            data: data,
            success: function (result) {}
        });
}

EDIT

for $(this) to work, instead of passing name and id parameters -which implies you have the checkbox element selected somewhere, and you're calling the function in a way similar to this:

update_contact($(elem).attr('id'),$(elem).attr('name'));

just use the shorter, cleaner and more powerful:

update_contact.call($(elem));

Or change the inline onclick="update_contact()" to onclick="update_contact.call(this)". just this, without the $ sign or brackets...