How to disable/enable submit button depending on checkbox state? - javascript

There's a form with two text fields and one checkbox, all of them are required and have the required attribute.
The submit button should only get enabled if the required inputs are filled and checked.
With the current code the text field validation seems to work fine however it doesn't have an effect on the checkbox.
Jsfiddle
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>
<script>
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = true;
$(this.form).find(inputSelector).each(function() {
if (!this.value.trim()) {
isValidForm = false;
}
});
$(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
return isValidForm;
}
$('.monitored-btn').closest('form')
// in a user hacked to remove "disabled" attribute, also monitor the submit event
.submit(function() {
// launch checkForm for the first encountered input,
// use its return value to prevent default if form is not valid
return checkForm.apply($(this).find(':input')[0]);
})
.find(inputSelector).keyup(checkForm).keyup();
</script>

I would do this very similarly to Kubwimana Adrien's answer with initially rendering a disabled button.
Also, generally, it is not considered secure to set initial state of validation booleans to TRUE. Thus, changing the code a little.
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = false;
$(this.form).find(inputSelector).each(function() {
if (((this.type != 'checkbox') && (this.value.trim() != "")) || (this.type == 'checkbox' && this.checked)) {
isValidForm = true;
}
else{
isValidForm = false
return false //break out of each loop
}
});
$(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
return isValidForm;
}
$('.monitored-btn').closest('form')
// in a user hacked to remove "disabled" attribute, also monitor the submit event
.submit(function() {
// launch checkForm for the first encountered input,
// use its return value to prevent default if form is not valid
return checkForm.apply($(this).find(':input')[0]);
})
.find(inputSelector).on("keyup change", checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form></body>

CSS only required
#otherForm-submitBtn {
enabled: false;
color: grey;
}
input[type='checkbox']:checked ~ #otherForm-submitBtn {
enabled: true;
color: black;
}
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>

Keyup event won't work on a checkbox also it's better to check for checked prop instead of value on a checkbox. Try this:
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = true;
$(this.form).find(inputSelector).each(function() {
if (!this.value.trim() || (this.type == 'checkbox' && !this.checked)) {
isValidForm = false;
}
});
$(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
return isValidForm;
}
$('.monitored-btn').closest('form')
// in a user hacked to remove "disabled" attribute, also monitor the submit event
.submit(function() {
// launch checkForm for the first encountered input,
// use its return value to prevent default if form is not valid
return checkForm.apply($(this).find(':input')[0]);
})
.find(inputSelector).on("keyup change", checkForm);

You need to check that condition in everytime user type or click checkbox , and toggle disable by removeAttr and attr ..
$("form input").keyup(check);
$("form input:checkbox").on("click", check);
function check() {
if($("input[name='otherForm-name1']").val() != "" &&
$("input[name='otherForm-surname']").val() != "" &&
$("input[name='otherForm-chcekbox']").prop("checked") == true) {
$("#otherForm-submitBtn").removeAttr("disabled");
return;
}
$("#otherForm-submitBtn").attr("disabled",true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#otherForm">
Name * <input name="otherForm-name1" placeholder="required" required> <br />
Tel * <input name="otherForm-surname" placeholder="required" required> <br />
<input type="checkbox" name="otherForm-chcekbox" id="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>

Disable the button with disable attribute. Then listen for the checkbox change event, and either remove the attribute or add it.
<form action="#otherForm">
<input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
<button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>
$(".otherForm-chcekbox").change(function() {
if(this.checked) {
if (checkForm()) {
$("otherForm-submitBtn").removeAttr("disabled");
}
} else {
$("otherForm-submitBtn").attr("disabled", "disabled");
}
});

Related

The order of my jquery validator is working wrong, and I have no idea why

My form validator works, but it works in a certain order, if I check the checkbox, it works fine, but if I fill the inputs first and then use the checkbox, it not works, unless I type something in the inputs
$(document).ready(function() {
$('#send').attr('disabled', true);
$('.input,#check').on('keyup', function() {
var text_value = $('.input-cpk').val();
if (text_value !== '' && (document.getElementById('check').checked)) {
$('#send').attr('disabled', false);
} else {
$('#send').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="block oh fr col-9 margem-d2 text-left" action="enviar-calculo.php" method="post" target="votar" name="cpk">
<input type="text" name="nome" id="nome" class="input-cpk col-20">
<input type="number" name="telefone" class="input-cpk-tel">
<input type="submit" value="CALCULAR" id="send" class="f-josefin-s-b f-branca bg-amarelo botao" onclick="output();">
<input type="checkbox" id="check" name="others" />
</form>
You only run your validation code during the keyup event, which only happens on the input boxes. You also need to do validation during a click event on the checkbox.
You can put multiple event names in the argument to .on(), to handle both with the same code.
You also have an incorrect class .input, there are no elements with class="input" in the HTML. I've changed it to .input-cpk.
$(document).ready(function() {
$('#send').prop('disabled', true);
$('.input-cpk,#check').on('keyup click', function() {
var text_value = $('.input-cpk').val();
if (text_value !== '' && (document.getElementById('check').checked)) {
$('#send').prop('disabled', false);
} else {
$('#send').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="block oh fr col-9 margem-d2 text-left" action="enviar-calculo.php" method="post" target="votar" name="cpk">
<input type="text" name="nome" id="nome" class="input-cpk col-20">
<input type="number" name="telefone" class="input-cpk-tel">
<input type="submit" value="CALCULAR" id="send" class="f-josefin-s-b f-branca bg-amarelo botao" onclick="output();">
<input type="checkbox" id="check" name="others" />
</form>
It's because you're using the wrong selector.
Try this
$('input,#check').on('keyup', function() {
Instead of this
$('.input,#check').on('keyup', function() {
Additionally you might want to use the .on('change') instead of .on('keyup')

How to add class to (or change class of) a form field if it is empty? jQuery

I have a form like below;
<form id="myform" name="myform">
<input type="text" class="required" value="" name="qwer" /><br />
<input type="text" value="" name="asdf" /><br />
<input type="text" class="required" value="" name="zxcv" /><br />
<input type="text" value="" name="tyui" /><br />
<input type="text" class="required" value="" name="ghjk" /><br />
<input type="submit" value="Submit" />
</form>
I want to check if the text fields with class="required" is blank or not at the time of submission. If they are blank, I want to change the corresponding blank field's class to error. If all the required fields are not empty, I want to alert the serialized data. I've tried this;
$('#myform input[type=submit]').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
if($.trim($('#myform input[type=text].required').val()).length == 0){
$(this).addClass("error");
}else{
alert(data);
}
});
How can I do this? Here is the fiddle.
You should loop over every element with the required class.
You are setting the error class on the submit button because you use $(this).addClass(), the $(this) is a reference to the submit button.
$('#myform input[type=submit]').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
[].slice.call($('#myform input[type=text].required')).forEach(function (elem, index) {
$elem = $(elem);
if($elem.val().length == 0)
$elem.addClass("error");
});
});
Fiddle demo
Fyi: HTML5 comes with a bunch of pseudo-classes to check for invalid form inputs so you don't have to code it by yourself, take a look here if you're interested.
After removing the unnecessary value="" on inputs
You can do this:
$('#myform input[type=submit]').click(function (e) {
e.preventDefault();
var data = $('#myform').serialize();
if ($('.required').is('[value=""]')) {
$('.required[value=""]').addClass("error");
} else {
alert(data);
}
});
Demo

how to adapt this script to include a checkbox check if checked

I'm a total noob at javascript. I use this script between my head tags that will force the user to scroll through a textarea before hitting submit button
<script language="JavaScript">
<!--
function textareaAtEnd(textareaObj)
{
return ((textareaObj.scrollTop + textareaObj.offsetHeight) > textareaObj.scrollHeight);
}
function formValidation(formObj)
{
if (textareaAtEnd(formObj.licenseAgreement))
{
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
// -->
</script>
my <form> looks like this:
<form action="step2.php" method="post" onSubmit="return formValidation(this);">
<textarea name="licenseAgreement" rows="20" cols="90">Very long license agreement text</textarea>
<br />
<input name="agree" type="checkbox" value="yes" /> I have read and agreed the above license agreement
<br />
<input type="submit" value="CONTINUE">
</form>
How can I adapt this javascript to also check if <input name="agree" type="checkbox" value="yes" /> is checked and if not to echo a message to the user? I'm a total noob, it's my first time using javascript.
do
function formValidation(formObj) {
if(!formObj.agree.checked) {
alert ("Please agree to terms.")
return false;
} else if (textareaAtEnd(formObj.licenseAgreement)) {
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
Demo: Fiddle
Use the checked property :
var checkbox = document.getElementsByName("agree")[0];
if(checkbox.checked)
alert("Check that");
Here you go:
if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
}
Using ID's is a best practice I would always recommend using for client-side code.
So you would change your validation function to:
function formValidation() {
if (textareaAtEnd(document.getElementById('licenseAgreement')) == false) {
alert ("Please scroll to the end to move on.")
return false;
}
else if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
return false;
}
else {
return true;
}
}
Also be sure to add an id="agree" to your <input type="checkbox" and id="licenseAgreement" to your textarea...
So it should look like this:
<input name="agree" id="agree" type="checkbox" value="yes" />
...
<textarea name="licenseAgreement" id="licenseAgreement" rows="20" cols="90">
And your form tag, you can remove the this parameter:
onSubmit="return formValidation();"
Replace
<input name="agree" type="checkbox" value="yes" />
With
<input name="agree" id="agree" type="checkbox" value="yes" />
Add id=agree attribute for checkbox.
if(document.getElementById("agree").checked == false)
{
alert("Checkbox is not checked , please select checkbox");
}

enabled and disabled text input on checkbox checked and unchecked

i've checkbox and text input
What I need is to enable text input when i check the checkbox and to disable text input when i uncheck the checkbox
I'm using the following code but it do the reverse enable when unchecked / disable when checked so how to adjust it fit with my needs.
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>
any help ~ thanks
You just need to add a ! in front of this.checked.
Here's an example that shows the change:
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').disabled = !this.checked;
};
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" />
A jQuery solution could be this one:
<script>
$('#yourBox').change(function() {
$('yourText').attr('disabled',!this.checked)
});
</script>
It is the same as Minko's answer but I find it more elegant.
Try it. If you use a label then add onmousedown to it
<form >
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" onmousedown="this.form.yourText.disabled=this.checked"/>
</form>
A better solution could be:
var checkbox = document.querySelector("#yourBox");
var input = document.querySelector("#yourText");
var toogleInput = function(e){
input.disabled = !e.target.checked;
};
toogleInput({target: checkbox});
checkbox.addEventListener("change", toogleInput);
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
function createInput( chck ) {
if( jQuery(chck).is(':checked') ) {
jQuery('<input>', {
type:"text",
"name":"meta_enter[]",
"class":"meta_enter"
}).appendTo('p.checkable_options');
}
else {
jQuery("input.meta_enter").attr('disabled','disabled');
}
}
createInput( chck );
<input type="radio" name="checkable" class="checkable" value="3" />
<input type="radio" name="checkable" class="checkable" value="4" onclick="createInput(this)" />

Print value on form submit

I'm new to JavaScript. How can I print the values when an HTML form is submitted?
Assuming your form looks like :
<form action="">
<input type="text" name="User" />
<input type="password" name="Password"/>
<span>Admin</span> <input type="checkbox" name="IsAdmin" />
<span>US</span> <input type="radio" name="Country" value="US" />
<span>UK</span> <input type="radio" name="Country" value="UK" />
<input type="submit" />
</form>
Jquery code should look like this as starting point :
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function () {
User = $("input[name='User']").val();
Password = $("input[name='Password']").val();
IsAdmin = $("input[name='IsAdmin']").attr("checked");
Country = $("input:radio[name='Country']:checked").val(); /* Special case of radio buttons*/
document.writeln(User);
document.writeln(Password);
document.writeln(IsAdmin);
document.writeln(Country);
return false;
})
});
</script>
jQuery code is below:
$('#button_ID').submit(function() {
alert('something');
});
button_ID is id of your submit button if you want to stop form to submit then add return false; at end
$('#button_ID').submit(function() {
alert('something');
return false;
});

Categories

Resources