Reputation: 63
Please I need help on disabling a checkbox from being checked again after being checked first.
This is what I have done so far.
<label class="checkbox-inline"><input type="checkbox" id="checked" onclick="check();"></label>
<script type="text/javascript">
function check() {
if($("#checked").is(":checked")){
alert("Thanks for Attending");
$(this).attr('disabled','disabled');
}
}
}
</script>
Upvotes: 3
Views: 7203
Reputation: 1
<html>
<head>
<title>JqueryCheckboxChekedDisableCheckbox</title>
<style>
input[type=text] {
width: 100%;
height:10%;
padding: 6px;
border: 1px solid #ccc;
border-radius: 4px;
}
label {
padding: 12px 12px 12px 0;
display: inline-block;
font-family:sans-serif;
}
input[type=submit] {
background-color: #4CAF50;
border: none;
color: white;
padding: 6px 20px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
.error{
color:red;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<fieldset style="margin-left:20%;margin-right:20%;font-family:sans-serif;padding:15px;border-radius:5px;background:#f2f2f2;border:5px solid #1F497D">
<legend style="background:#1F497D;color:#fff;padding:5px 10px;font-size:22px;border-radius:5px;margin-left:20px;box-shadow:0 0 0 5px #ddd">JqueryCheckboxChekedDisableCheckbox</legend>
<table>
<tr><td>Subjects:</td><td><input type="checkbox" name="subject" value="java"/>Java<input type="checkbox" name="subject" value="hibernate"/>Hibernate<input type="checkbox" name="subject" value="spring"/>Spring</td></tr>
<tr><td></td><td><input type="submit" value="Submit" id="send"/></td></tr>
</table>
</fieldset>
</html>
<script>
$('#send').on('click',function(){
$("input[name='subject']").each(function(){
if ($(this).is(":checked")) {
$(this).prop("disabled",true);
}
});
});
</script>
Upvotes: 0
Reputation: 1545
An alternative with vanilla js since you are trying to combine it with jQuery while you could not do so:
function check() {
var el = document.getElementById("checked");
if (el.checked) {
el.disabled = true;
}
}
If you still need jQuery version stick to .prop()
usage:
function check() {
var $el = $("#checked");
if ($el.is(":checked")) {
$el.prop("disabled", true);
}
}
Upvotes: 0
Reputation: 5246
Please check this snippet.
function check() {
if($("#checked").is(":checked")){
alert("Thanks for Attending");
//Code to disable checkbox after checked
$('#checked').attr('disabled', true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox-inline"><input type="checkbox" id="checked" onclick="check();"></label>
Upvotes: 2
Reputation: 26258
Change
$(this).attr('disabled','disabled');
to
$('#checked').attr('disabled', true);
As $(this) not refers to checkbox because you are inside the function body.
Upvotes: 0