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.
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:And then:
Alternatively use jQuery to assign the click handler and it will set
this
for you correctly. You could put the@item.idContact.toString()
in thevalue
attribute and then access it usingthis.value
in your handler:And then:
(Note: I don't actually know the VB/razor syntax, I'm just guessing on that part.)
Try this (working fiddle here: http://jsfiddle.net/Ac3kd/):
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
ansa
) as mamoo does, I'd create thevar data
just before the$.ajax
bit: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:just use the shorter, cleaner and more powerful:
Or change the inline
onclick="update_contact()"
toonclick="update_contact.call(this)"
. just this, without the $ sign or brackets...