Reputation: 11
I need to check the checkbox status for my web in ASP.Net but I can't get the javascript work:
<li>
<a id="link" href="/ControlHoras">Control Horas</a>
<input onchange="favButton()" name="checkbox" type="checkbox" id="ControlHoras"/>
</li>
function favButton() {
if ($(this).is(":checked")) {
var id = this.id;
alert('checked');
} else {
alert('unchecked');
}
};
Upvotes: 1
Views: 126
Reputation: 348
<li>
<a id="link" href="/ControlHoras">Control Horas</a>
<input onclick="favButton()" name="checkbox" type="checkbox" id="ControlHoras"/>
</li>
Upvotes: 1
Reputation: 21695
The proper way to get the caller/sender is through the event
argument. In fact Firefox ignores events if they don't have the event
argument.
function favButton(event) {
if ($(event.currentTarget).is(":checked")) {
var id = event.currentTarget.id;
alert('checked');
} else {
alert('unchecked');
}
};
Upvotes: 0
Reputation: 337700
this
in favButton
will be the window, not the clicked checkbox, as you're using an outdated onchange
event attribute.
You can improve your code and avoid the issue by attaching your event handler using an unobtrusive event handler, like this:
$('#ControlHoras').change(function() {
if ($(this).is(":checked")) {
var id = this.id;
alert('checked');
} else {
alert('unchecked');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a id="link" href="/ControlHoras">Control Horas</a>
<input name="checkbox" type="checkbox" id="ControlHoras" />
</li>
</ul>
Upvotes: 2