Reputation: 12856
I have a form:
<form name="registration_form" action="<?php echo base_url();?>user/register" method="post" onsubmit="return verify()">
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<tr>
<td class="login_user_td">Click If Want To Edit :</td>
<td><input type="checkbox" name="edit" id="edit" onclick="enable_edit()"/>
</td>
</tr>
<tr>
<td class="login_user_td"> First Name :</td>
<td><input type="text" name="f_name" readonly="true" id="f_name" value="<?php echo $my_info[0]['first_name'];?>">
</td>
</tr>
<tr>
<td colspan="2" align="center" class="login_user_button"><input type="image" style="display: none;"src="<?php echo base_url();?>assets/front_assets/image/edit.gif" /></td>
</tr>
</table>
</form>
Now the checkbox edit have a onclick event which calls the function
enable_edit()
{
if($('#edit').prop("checked", true))
{
alert('true');
}
else
alert('false');
}
The problem is that, whenever I am clicking on the checkbox, it's always displaying true.
Suppose if I click first time, the property gets checked, then it will alert true, next time when I am again clicking, this time the check should get unchecked, and hence should alert false.
But every time it's alerting true, moreover the checkbox isn't getting unchecked.
Upvotes: 0
Views: 238
Reputation: 22339
You are always setting the checked state rather than querying it.
Use prop("checked")
instead of prop("checked", true)
in your conditional check as the latter will always set the checked
state property to true
.
See .prop() documentation for more details on getting and setting a property value.
Change your code to the following:
function enable_edit() {
if ($('#edit').prop("checked")) {
alert('true');
} else alert('false');
}
DEMO - Working checkbox
Upvotes: 2
Reputation: 2260
You are setting the value of the checked attribute to true in that if statement.
What you need is just $('#edit').prop("checked");
Upvotes: 2