Reputation: 313
Table Tag
<tr>
<td>
<input id="chkbox" name="chkbox" type="checkbox" class="Checkbox" value = <%: item.field1 %> />
</td>
<td>
<%: item.field1 %>
</td>
<td>
<%: item.field2 %>
</td>
</tr>
My Jquery
$("#Free").click(function fn() {
if ($('#chkbox').is(':checked')) {
return true;
}
else {
alert("Please Select option");
return false;
}
});
my check box are clicked but it always showing else part that alert message "Please Select Option"
Upvotes: 0
Views: 65
Reputation: 1039418
It looks like you have multiple input fields in your DOM with id="chkbox"
. This results in invalid markup and your $('#chkbox')
selector is always returning the first element.
You could use the class name instead:
<input name="chkbox" type="checkbox" class="Checkbox" value = <%: item.field1 %> />
and then:
$("#Free").click(function() {
if ($('.Checkbox:checked').length > 0) {
return true;
}
else {
alert("Please Select option");
return false;
}
});
Also from your question it is not quite clear what this #Free
is, whether it is a single button or you have such buttons on each table row.
If it is a single button then the previous code should be alright -> it ensures that there is at least one checkbox that is checked.
If you have many such buttons then you should use a class selector for them (after assigning each button the same class
) and then:
$(".Free").click(function() {
var checkbox = $(this).closest('tr').find('.Checkbox');
if (checkbox.is(':checked')) {
return true;
}
else {
alert("Please Select option");
return false;
}
});
Also notice that you had some invalid javascript in the .click event:
.click(function fn() {
which I fixed to using an anonymous function:
.click(function() {
Upvotes: 1