Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  152] [ 1]  / answers: 1 / hits: 21157  / 9 Years ago, sat, november 28, 2015, 12:00:00

I have try a few examples of enable the submit button when checkbox is selected but i'm getting nowhere. Below is one of my attempts, where the submit button is disabled until the checkbox is selected. Please let me know what am i missing.





function checked(sub1) {
var myLayer = document.getElementById(sub1);
var input = myLayer.childNodes[0];
if (input.checked == true) {
myLayer.disabled = ;
} else {
myLayer.disabled = disabled;
}
}

<p style=color: #FF0000; font-weight: bold;>I have read and agree to the terms and conditions
<input type=checkbox id=termsChkbx onchange=checked('sub1') />
</p>

<p>
<input type=submit name=submit value=Order now! id=sub1 disabled=disabled />
</p>




More From » javascript

 Answers
15

Nobody has explained why your code isn't working.



For one, you aren't selecting the input checkbox element properly. It is not a child node of the button element. You could either get a reference to the checkbox by passing this in the onchange event, or you could pass the event object and access the checkbox element through the event.target property:



For example:



<input type=checkbox id=termsChkbx  onchange=isChecked(this, 'sub1') />


Then you can access a reference to the checkbox element that fired on the change event:



function isChecked(checkbox, sub1) {
// checkbox
}


After changing a couple things, it would work as expected:



function isChecked(checkbox, sub1) {
var button = document.getElementById(sub1);

if (checkbox.checked === true) {
button.disabled = ;
} else {
button.disabled = disabled;
}
}


However, you can simplify the code and rewrite it to:



Example Here



<input type=checkbox id=termsChkbx  onchange=isChecked(this, 'sub1') />




function isChecked(checkbox, sub1) {
document.getElementById(sub1).disabled = !checkbox.checked;
}


As a side note, I would highly suggest using unobtrusive JavaScript and add an event listener to the element in order to avoid inline onchange events:



Example Here



document.getElementById('termsChkbx').addEventListener('click', function (e) {
document.getElementById('sub1').disabled = !e.target.checked;
});

[#64241] Wednesday, November 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
colby

Total Points: 311
Total Questions: 102
Total Answers: 102

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;