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>
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;
});
Here is the complete code
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx " onclick="change_button(this,'sub1')"/>
</p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
<script type = "text/javascript">
function change_button(checkbx,button_id) {
var btn = document.getElementById(button_id);
if (checkbx.checked == true) {
btn.disabled = "";
} else {
btn.disabled = "disabled";
}
}
</script>
Try like this
<input type="checkbox" id="termsChkbx " onchange="isChecked(this,'sub1')"/></p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
JS
function isChecked(chk,sub1) {
var myLayer = document.getElementById(sub1);
if (chk.checked == true) {
myLayer.disabled = false;
} else {
myLayer.disabled = true;
};
}
PLUNKR
The major problem can be easily checked by using the browser's debug console. There you can immediately see an exception.
Try this:
Html:
<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', this.checked);" />
</p>
<p>
<input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled" />
</p>
JavaScript:
function checked(sub1, checkedState) {
document.getElementById(sub1, this).disabled = !checkedState;
}
But be aware, that this code snippet is not best practice. It just solves your current problem without using libraries like jQuery.
Try using this JQuery function
$(function() {
$('#termsChkbx').click(function() {
if ($(this).is(':checked')) {
$('#sub1').removeAttr('disabled');
} else {
$('#sub1').attr('disabled', 'disabled');
}
});
});
Example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="color: #FF0000; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" /></p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
<script>
$(function() {
$('#termsChkbx').click(function() {
if ($(this).is(':checked')) {
$('#sub1').removeAttr('disabled');
} else {
$('#sub1').attr('disabled', 'disabled');
}
});
});
</script>
While your problem has been solved, there is no need for JavaScript here.
This can be done with pure CSS/HTML:
input[type="checkbox"]:not(:checked) ~ input[type="submit"]{
pointer-events: none;
tab-index: -1;
color: graytext;
}
<input type="checkbox"/>
<input type="submit" id="submit" value="submit" onclick="this.value='clicked';"/>
I've used the :not() pseudo-class to detect when a check-box isn't ticked as this is w3c's recommended approach. I wasn't sure where (in HTML) the check box is in relevance to the button, so I used the tilde (~ general sibling selector) to find the button. If the check-box is immediately before the button I would recommend using the adjacent sibling selector + instead.
However if you have multiple check-boxes and you only want one check-box to toggle the button's state then using the :nth-of-type pseudo class or an id may be more appropriate:
input[type="checkbox"]:nth-of-type(2):not(:checked) ~ input[type="submit"]{
pointer-events: none;
tab-index: -1;
color: graytext;
}
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="submit" id="submit" value="submit" onclick="this.value='clicked';"/>
Otherwise all the check-boxes will be 'required' for the button to become click-able:
input[type="checkbox"]:not(:checked) ~ input[type="submit"]{
pointer-events: none;
tab-index: -1;
color: graytext;
}
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="submit" id="submit" value="submit" onclick="this.value='clicked';"/>
Related
The form’s submit button should be disabled until the user has checked the checkbox to say that they have read and agree to the terms and conditions
Here is code html code for checkbox and submit button.I've tried this but failed
var submit = document.getElementsByName('termsChkbx')[0];
input.onchange=function() {
if(input.checked) {
document.getElementsByName('submit').disabled = false;
} else {
document.getElementsByName('submit').disabled = true;
}
}
<p style="color: #FF0000; font-weight: bold;" id='termsText'>I have read and agree to the terms and conditions <input type="checkbox" name="termsChkbx"></p>
<input type="submit" name="submit" value="Book now!" disabled>
Here where you got it wrong :
You put your checkbox reference to variable "submit". Then you used another variable named "input" where there is no value in it.
Updated Answer :
<p style="color: #FF0000; font-weight: bold;" id='termsText'>I have read and agree to the terms and conditions <input type="checkbox" name="termsChkbx"></p>
<input type="submit" name="submit" value="Book now!" disabled>
<script>
var input = document.getElementsByName('termsChkbx')[0];
var submit = document.getElementsByName('submit')[0];
input.onchange=function() {
if(input.checked) {
submit.disabled = false;
} else {
submit.disabled = true;
}
}
</script>
I recently start to learn JavaScript and have a question about checkbox Attribute.
I want to put Nickname feature that is if someone want to put his/her nickname, he/she can check the checkbox and it appears the text box for Nickname.
However, when the page is loaded, the text box is there even though the checkbox is not checked.
Can anyone please help me with the problem...?
<fieldset>
<form>
<div>
<label for = "yesNick"> Nickname?:</label>
<input id="yesNick" name="yesNick" type="checkbox" value="yes" onchange="nicknameFunction()"/><br/>
</div>
<div id= "nick">
<label for = "nickname">Nickname:</label>
<input type="text" name="nickname" id="nickname"><br/>
</div>
<input type="submit" value="Vertify"/>
<script type="text/javascript">
function nicknameFunction() {
if (document.getElementById('yesNick').checked){
document.getElementById('nick').style.display="inline";
document.getElementById('nickname').setAttribute('required',true);
}
else{
document.getElementById('nickname').removeAttribute('required');
document.getElementById('nick').style.display="none";
}
}
</script>
</form>
</fieldset>
</p>
Set your initial display for the #nick div to 'none'. Your function only runs on change of the checkbox so you will need to ensure initial state on your own.
function nicknameFunction() {
if (document.getElementById('yesNick').checked){
document.getElementById('nick').style.display="inline";
document.getElementById('nickname').setAttribute('required',true);
}
else{
document.getElementById('nickname').removeAttribute('required');
document.getElementById('nick').style.display="none";
}
}
#nick {
display:none;
}
<fieldset>
<form>
<div>
<label for = "yesNick"> Nickname?:</label>
<input id="yesNick" name="yesNick" type="checkbox" value="yes" onchange="nicknameFunction()"/><br/>
</div>
<div id= "nick">
<label for = "nickname">Nickname:</label>
<input type="text" name="nickname" id="nickname"><br/>
</div>
<input type="submit" value="Vertify"/>
</form>
</fieldset>
You don't need JavaScript for this; in fact, you shouldn't use JS for this because accessing the dom is quite slow. CSS is more than sufficient. You can also make it animated by using width instead of display property, but for my example I only used the display property.
#yesNick:checked ~ #nickname {
display: block;
}
#nickname {
display: none;
}
<div>
<label for = "yesNick"> Nickname?:</label>
<input id="yesNick" name="yesNick" type="checkbox" value="yes"/><br/>
<label for = "nickname">Nickname:</label>
<input type="text" name="nickname" id="nickname"><br/>
</div>
<input type="submit" value="Vertify"/>
try hiding the textbox for the first time :
var nickName = document.getElementById('nick');
nickName.style.display="none";
function nicknameFunction() {
if (document.getElementById('yesNick').checked){
nickName.style.display="inline";
document.getElementById('nickname').setAttribute('required',true);
}
else{
document.getElementById('nickname').removeAttribute('required');
nickName.style.display="none";
}
}
There is a form containing two buttons. And then I suppose that when I click different buttons, a relevant message box will be popped up. Once the button is clicked, it will trigger a further action called "Approval".
However, at the current situation, the alert box only shows one status. I know the current status are getting the same ID and it is a wrong operation. But I don't know the solution now. Could anyone help me?
I looked into this ref: Form onSubmit determine which submit button was pressed, but could not quite understand the concept the solution provided.
<script type="text/javascript" language="javascript">
function ConfirmOnDelete() {
var a = document.getElementById('a_action').value; //I want to change this
if (a == "Approve")
{
if (confirm("Are you sure to approve?") == true)
return true;
else
return false;
}
else
{
if (confirm("Are you sure to delete?") == true)
return true;
else
return false;
}
}
</script>
<form id="Batch" action="Approval" method="post" onsubmit="return ConfirmOnDelete();">
#<text>
#If ViewBag.unapprovedCount > 0 Then
#<div style="float: left;">
<br />
<input type="hidden" name="batch_action" value="Delete" />
<input type="hidden" id="a_action" name="additional_action" value="Delete" />
<input type="submit" id="submit4" name="submit" class="button" value="Delete" style="width:100px;">
</div>
End If
#If ViewBag.unapprovedCount > 0 Then
#<div style="float: right;">
<br />
<input type="hidden" name="batch_action" value="Approve" />
<input type="hidden" id="a_action2" name="additional_action" value="Approve" />
<input type="submit" id="submit3" name="submit" class="button" value="#ViewBag.batch_action" style="width:100px;">
</div>
End If
</text>
</form>
On your #a_action element, you can add a data-* attribute and do some magic.
<input type="hidden" id="a_action" name="additional_action" value="Delete" data-value="Approve" />
Notice at the end it says data-value="Approve". Now you can grab that value like this:
var a = document.getElementById('a_action').getAttribute('data-value');
And check if the value is equal to something, just like in your example.
if (a == "Approve") {
//This would be true in this example, as data-value == "Approve"
}
Was this was you were looking for?
The reason you are only getting one status is because
var a = document.getElementById('a_action').value; //get by Button click
retrieves the value based on ID. ID should be unique, but both of your inputs have the id a_action. So the getElementById only returns the first value, in this case that is Delete.
What you can do is the following
Instead of binding `ConfirmOnDelete' on the form, you can bind in on the buttons and pass the action as an argument.
See this fiddle https://jsfiddle.net/j3rvter5/1/
notice the addition of { and }in your code. that's the correct syntax for javascript if statement.
UPDATE
you want to call the ConfirmOnDelete()depending on which button the from was submitted with, either the approve or delete. forgive me for using jquery
$("#Batch").on("submit", function() {
// Does the element have focus:
var hasApproveFocus = $("input[id='submit3']").is(':focus');
var hasDeleteFocus = $("input[id='submit4']").is(':focus');
//checking which of the submit button has focus to determine which was click on submit
if (hasApproveFocus == true) {
if (confirm("Are you sure to approve?") == true) {
return true;
} else {
return false;
}
} else if (hasDeleteFocus == true){
if (confirm("Are you sure to delete?") == true) {
return true;
} else {
return false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="Batch" action="Approval" method="post">
<div style="float: left;">
<input type="submit" id="submit4" name="submit" class="button" value="Delete" style="width:100px;">
</div>
<div style="float: right;">
<br />
<input type="submit" id="submit3" name="submit" class="button" value="Approve" style="width:100px;">
</div>
</form>
This is the solution I achieved.
<script type="text/javascript">
function question_submit(input) {
if (input == 1)
{
if (confirm('Are you sure you want to delete?')) {
document.getElementById("action").value = "Delete";
$('#Batch').submit();
}
else {
alert('You have not submitted this form');
}
}
else {
if (confirm('Are you sure you want to approve?')) {
document.getElementById("action").value = "Approve";
$('#Batch').submit();
}
else {
alert('You have not submitted this form');
}
}
}
</script>
<form id="Batch" name="myform" action="BatchApproval" method="post" >
<input id="action" type="hidden" name="batch_action" />
<div style="float: left;">
<br />
<input type="button" id="submit4" name="submit4" class="button" value="Delete" style="width:100px;" onclick="question_submit(1)">
</div>
<div style="float: right;">
<br />
<input type="button" id="submit3" name="submit3" class="button" value="Approve" style="width:100px;" onclick="question_submit(2)">
</div>
</form>
Hello and thanks in advance for any help
In my store page, I have a checkbox that is checked when user agrees with the terms. When he checks the checkbox, submit button is disabled (false). My problem is that this solution doesn't work on iPhone and other mobile devices.
Here's the code:
function terms() {
if (document.getElementById("cbTerms").checked)
document.getElementById("submit").disabled = false;
else
document.getElementById("submit").disabled = true;
}
function cbc() {
if (document.getElementById("cbc").checked)
document.getElementById("cbc") = ("הריני מאשר קבלת מבצעים והטבות אל הדואר האלקטרוני מפראיה");
else
document.getElementById("cbc").value = ".";
}
<input class="btn btn-toranj alt" name="submit" type="submit" id="submit" value="לרכישה" disabled="true">
<br>
<br>
<input type="checkbox-0" id="cbTerms" name="cbTerms" onclick="terms();" style="width:15px; height:15px;">
<p style="margin-bottom:0px; font-size:14px; display: -webkit-inline-box;">הריני מאשר כי קראתי את התקנון
</p>
<br>
<input type="checkbox" id="cbc" name="os3" oninput="cbc()" style="width:15px; height:15px;">
<p style="margin-bottom:0px; font-size:14px; display: -webkit-inline-box;">הריני מאשר קבלת מבצעים והטבות אל דואר האלקטרוני</p>
<input type="hidden" value="הטבות ומבצעים" id="on3" name="on3">
At first sight your first checkbox is not really a checkbox.
<input type="checkbox-0" ...> should be more like: <input type="checkbox" ...>
With this change it will work.
P.S.:
Consider using braces for your if() {} else {} statements as you will propably run into some logic error if you change something in the future (e.g. add a line of code) and forget to add them.
The change event is preferred over click. And in addition, you'd pass the currently clicked checkbox on the fly as following
<input class="btn btn-toranj alt" name="submit" type="submit" id="submit" value="לרכישה" disabled="true">
<br><br>
<input type="checkbox" id="cbTerms" name="cbTerms" onchange="terms(this);" style="...">
<p style="...">הריני מאשר כי קראתי את
התקנון
</p>
<br>
<input type="checkbox" id="cbc" name="os3" onchange="cbc(this)" style="...">
<p style="...">הריני מאשר קבלת מבצעים והטבות אל דואר האלקטרוני</p>
<input type="hidden" value="הטבות ומבצעים" id="on3" name="on3">
<script type="text/javascript">
function terms(me)
{
document.getElementById("submit").disabled = !me.checked;
}
function cbc(me){
var val=document.getElementById("cbc").checked?
"הריני מאשר קבלת מבצעים והטבות אל הדואר האלקטרוני מפראיה":".";
document.getElementById("cbc").value = val;
}
</script>
I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.
Here is my form:
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="----??----" />
The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.
Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.
You could use:
if(!this.form.checkbox.checked)
{
alert('You must agree to the terms first.');
return false;
}
(demo page).
<input type="checkbox" name="checkbox" value="check" />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
! is the Boolean NOT operator.
this is the submit button because it is the element the event handler is attached to.
.form is the form the submit button is in.
.checkbox is the control named "checkbox" in that form.
.checked is true if the checkbox is checked and false if the checkbox is unchecked.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept SOMETHING Terms and Conditions</p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
You can do something like this:
<form action="../" onsubmit="return checkCheckBoxes(this);">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.MyCheckbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
http://lab.artlung.com/validate-checkbox/
Although less legible imho, this can be done without a separate function definition like this:
<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
<p><input type="SUBMIT" value="Submit!"></p>
</form>
You can do the following:
<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
<input type="checkbox" name="checkbox" value="check" id="agree" />
<input type="submit" name="email_submit" value="submit" />
</form>
Here is a working demo - http://jsfiddle.net/Ccr2x/
If your checkbox has an ID of 'checkbox':
if(document.getElementById('checkbox').checked == true){ // code here }
HTH
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:
html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">
script:
<script type="text/Javascript">
function deleteData() {
if(!document.getElementById('Delete').checked){
alert('Checkbox not checked');
return false;
}
</script>
Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.
HTML:
<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />
JavaScript:
var alterDisabledState = function () {
var isMyCheckboxChecked = $('#myCheckbox').is(':checked');
if (isMyCheckboxChecked) {
$('myButton').removeAttr("disabled");
}
else {
$('myButton').attr("disabled", "disabled");
}
}
Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.
Another Simple way is to create & invoke the function validate() when the form loads & when submit button is clicked.
By using checked property we check whether the checkbox is selected or not.
cbox[0] has an index 0 which is used to access the first value (i.e Male) with name="gender"
You can do the following:
function validate() {
var cbox = document.forms["myForm"]["gender"];
if (
cbox[0].checked == false &&
cbox[1].checked == false &&
cbox[2].checked == false
) {
alert("Please Select Gender");
return false;
} else {
alert("Successfully Submited");
return true;
}
}
<form onload="return validate()" name="myForm">
<input type="checkbox" name="gender" value="male"> Male
<input type="checkbox" name="gender" value="female"> Female
<input type="checkbox" name="gender" value="other"> Other <br>
<input type="submit" name="submit" value="Submit" onclick="validate()">
</form>
Demo: CodePen
Target it by id and then use this code:
function check(){
if(document.getElementById('yourid').checked
{
return false;
}
else
{
alert ("checkbox not checked");
return false;
}
}
var testCheckbox = document.getElementById("checkbox");
if (!testCheckbox.checked) {
alert("Error Message!!");
}
else {
alert("Success Message!!");
}
Guys you can do this kind of validation very easily. Just you have to track the id or name of the checkboxes. you can do it statically or dynamically.
For statically you can use hard coded id of the checkboxes and for dynamically you can use the name of the field as an array and create a loop.
Please check the below link. You will get my point very easily.
http://expertsdiscussion.com/checkbox-validation-using-javascript-t29.html
Thanks