Disable submit button until all form inputs have data - javascript

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}

Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">

Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/

You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});

Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}

Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.

Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!

Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>

function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

Related

Disable form submit button if all input and textarea are empty except one

I need to enable a submit button only when each input fields has a value except one. The except one.
HTML:
// start of form
<input type='text /> // cant be blank
<input type='text /> // cant be blank
<input type='text /> // cant be blank
<textarea type='text /> // cant be blank
<button type='submit'>Submit</button>
// end of form
<input id='subscription-input' type='text /> // exclude this one only
[...]
JS:
function doCheck(){
var allFilled = true;
$('input[type=text]').not('#subscription-input').each(function(){
if($(this).val() == ''){
return false;
}
});
if (allFilled) {
// Apply active css and enable button
$('button[type=submit]').removeClass('form-submit--plain').addClass('form-submit--active');
$('button[type=submit]').prop('disabled', !allFilled);
}
}
$(document).ready(function(){
$('input[type=text]').keyup(doCheck).focusout(doCheck);
});
Basically I need a way to get the textarea field so I thought adding wilecard (*) would work:
$('*[type=text]').not('#subscription-input').each(function(){...}
How to get the input and textarea fields?
Apply the same class to all the fields and attach event to that class with a not for the ID:
function doCheck() {
var allFilled = true;
$('.form-fields:not(#subscription-input)').each(function() {
if ($(this).val() == '') {
allFilled = false;
}
});
$('button[type=submit]').prop('disabled', !allFilled);
if (allFilled) {
$('button[type=submit]').removeAttr('disabled');
}
}
$(document).ready(function() {
doCheck();
$('.form-fields').keyup(doCheck);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-fields' />
<input type='text' class='form-fields' />
<input type='text' class='form-fields' />
<textarea class='form-fields'></textarea>
<input id='subscription-input' class='form-fields' type='text' />
<button type='submit'>Submit</button>
change code to:
function doCheck(){
var allFilled = true;
$('input[type=text]:not(#subscription-input),textarea').each(function(){
if($(this).val() == ''){
allFilled=false;
}
});
if (allFilled) {
// Apply active css and enable button
$('button[type=submit]').removeClass('form-submit--plain').addClass('form-submit--active');
$('button[type=submit]').prop('disabled', !allFilled);
}
}
$(document).ready(function(){
$('input[type=text]').keyup(doCheck).focusout(doCheck);
});
Here you go with the solution https://jsfiddle.net/ehjxvz4j/1/
function doCheck(){
var allFilled = true;
$('input[type=text]').not('#subscription-input').each(function(){
if($(this).val() == ''){
allFilled = false;
}
});
if($('textarea').val() == ''){
allFilled = false;
}
if (allFilled) {
// Apply active css and enable button
$('button[type=submit]').removeClass('form-submit--plain').addClass('form-submit--active');
}
$('button[type=submit]').prop('disabled', !allFilled);
}
$(document).ready(function(){
$('input[type=text], textarea').focusout(doCheck);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<textarea></textarea>
<button type='submit' disabled>Submit</button>
<input id='subscription-input' type='text'/>

making all input fields borders red when no one at least was filled in

I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.
HTML
<form id="myform" action="" method="post">
<input name="destination" class="form-control" type="text" >
<input name="thingstodo" class="form-control" type="text">
<input name="gsearch" class="form-control" type="text">
<button type="submit" name="search">Search</button>
</form>
JavaScript
$(function(){
$("#myform").submit(function(){
var valid=0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") valid+=1;
});
if(valid){
return true;
}
else {
alert("error: you must fill in at least one field");
return false;
}
});
});
Thanks
You can do it by setting the CSS style. This is done most easily with jQuery syntax.
$(function(){
$("#myform").submit(function(){
var valid = 0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") {
valid++;
$(this).css("border-color", "initial");
}
else {
$(this).css("border-color", "red");
}
});
if (valid > 0) { return true; }
else { return false; }
});
});
Modify the code like so
$(function(){
$("#myform").submit(function(){
var valid=0;
$(this).find('input[type=text]').each(function(){
if($(this).val() != "") valid+=1;
else
$(this).style.border = "solid 1px red"
});
if(valid){
return true;
}
else {
return false;
}
});
});
How about this ?
$(function(){
$("#myform").submit(function(){
var dirty = false;
$('input[type=text]').each(function(){
if($(this).val().length){
dirty = true;
}
});
if(!dirty){
$('input[type=text]').each(function(){
$(this).css('border','1px solid red');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="" method="post">
<input name="destination" class="form-control" type="text" >
<input name="thingstodo" class="form-control" type="text">
<input name="gsearch" class="form-control" type="text">
<button type="submit" name="search">Search</button>
</form>

If I check 2 input radio the disabled Submit button enables, but if I uncheck them...the Submit button doesn't disable back

I just need a little help with this code.
var prv3;
var markIt3 = function(e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
};
$(function() {
$('input.class_x').on('click', markIt3);
});
$('input[type=radio]').on('change', function() {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled = true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}).change();
My request is the following:
can anybody just FIX what is missing in order for the form Submit button to go back to be disabled as it is supposed to be, because this form only enables it when 2 input type radio have been checked?
This form previous description is the main idea of everything:
A form, with several input type radios. Check at least 2 and the Submit button enables. But if you uncheck any of them, the Submit button should disable back, but I cannot manage to achieve this PART.
I just need a little HELP with IT, nothing else.
Please, DON'T change my code too much!Can it be done?
Check the fiddle right here: https://jsfiddle.net/Suiberu/70tkgk5t/13/
Thanks!
Actually problem is deselecting radio button not detected as a change. How about this
var prv3;
var markIt3 = function(e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
checkIfValid();
};
$(function() {
$('input.class_x').on('click', markIt3);
});
function checkIfValid() {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled = true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
};
input {
display: block;
margin: 0.5em 0;
}
input[type='submit']:disabled {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" autocomplete="off" method="post">
<input class="class_x" type="radio" name="name_1" value="value_1" id="id_1" />
<input class="class_x" type="radio" name="name_2" value="value_2" id="id_2" />
<input class="class_x" type="radio" name="name_3" value="value_3" id="id_3" />
<input type="submit" name="name_submit" value="OK" class="class_submit" id="SubmitButton" required/>
</form>
Or you can change the type of your inputs to checkBoxes and it will simply do the magic.
Here is the JSFiddle link.
var prv3;
var markIt3 = function (e) {
if (prv3 === this && this.checked) {
this.checked = false;
prv3 = null;
} else {
prv3 = this;
}
};
$(function () {
$('input.class_x').on('click', markIt3);
});
$('input[type=checkbox]').on('change', function () {
var current = $('input.class_x').filter(':checked');
var sbmtBtn = document.getElementById('SubmitButton');
sbmtBtn.disabled=true;
if (current.length > 1) {
sbmtBtn.disabled = false;
} else {
sbmtBtn.disabled = true;
}
}).change();
input {
display: block;
margin: 0.5em 0;
}
input[type='submit']:disabled {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" autocomplete="off" method="post">
<input class="class_x" type="checkbox" name="name_1" value="value_1" id="id_1" />
<input class="class_x" type="checkbox" name="name_2" value="value_2" id="id_2" />
<input class="class_x" type="checkbox" name="name_3" value="value_3" id="id_3" />
<input type="submit" name="name_submit" value="OK" class="class_submit" id="SubmitButton" required />
</form>
Only the type has been changed from radio button to checkbox.
this.checked = false
..does not fire the change event, so the change code doesn't get fired when a radio button is unchecked.
Add the following line of code after that line:
$(this).change();
That will fire the change code.
Try using .prop() function instead
$('input[type=radio]').on('change', function() {
var current = $('input.class_x').filter(':checked');
var $sbmtBtn = $('#SubmitButton');
$sbmtBtn.prop('disabled', true);
if (current.length > 1) {
$sbmtBtn.prop('disabled', false);
} else {
$sbmtBtn.prop('disabled', true);
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" class="class_x">
<input type="radio" class="class_x">
<input id="SubmitButton" type="submit">
</form>
.prop() documentation

onsubmit() form on mobile browser

I current use a javascript function on the onsubmit() event of my form to check if all the input are not empty.
This works fine on computer, but on mobile phone, it changes the background color (as I want to do when the input is empty) but it still submits the form !!!
My form :
<form id="formContact" action="envoi-message.php" method="post" class="normal" onsubmit="return valideChamps();">
<div class="ddl">
<span>VOUS ÊTES...</span>
<div class="ddlOption">
<ul>
<li onclick="ddlContact('entreprise')"><span>UNE ENTREPRISE</span></li>
<li onclick="ddlContact('ecole')"><span>UNE ÉCOLE</span></li>
<li onclick="ddlContact('personne')"><span>UNE PERSONNE</span></li>
</ul>
</div>
</div>
<input class="cache" type="text" name="entreprise" placeholder="NOM DE L'ENTREPRISE" />
<input class="cache" type="text" name="ecole" placeholder="NOM DE L'ÉCOLE" />
<input type="text" name="nom" placeholder="VOTRE NOM" />
<input type="email" name="email" placeholder="VOTRE EMAIL" />
<textarea name="message" placeholder="VOTRE MESSAGE" ></textarea>
<input id="btnEnvoi" type="submit" value="Envoyer">
</form>
My function :
function valideChamps(){
var bResult = true;
if ($("input[name*='nom']").val() == "") {
$("input[name*='nom']").addClass("error");
bResult = false;
} else {
$("input[name*='nom']").removeClass("error");
}
if ($("input[name*='email']").val() == "") {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
var regex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex.test($("input[name*='email']").val()) == false ) {
$("input[name*='email']").addClass("error");
bResult = false;
} else {
$("input[name*='email']").removeClass("error");
}
}
if ($("#formContact textarea").val() == ""){
$("#formContact textarea").addClass("error");
bResult = false;
}else {
$("#formContact textarea").removeClass("error");
}
if ($("div.ddl > span").text().contains("entreprise")){
if ($("input[name*='entreprise']").val() == "") {
$("input[name*='entreprise']").addClass("error");
bResult = false;
}else {
$("input[name*='entreprise']").removeClass("error");
}
} else if ($("div.ddl > span").text().contains("école")){
if ($("input[name*='ecole']").val() == "") {
$("input[name*='ecole']").addClass("error");
bResult = false;
}else {
$("input[name*='ecole']").removeClass("error");
}
}
return bResult;
}
Do you have any idea about what is wrong...?
Best regards
Audrey
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true
Try registering your submit handler to the form using JS, so you can access the event and call preventDefault() instead of (or in addition to) returning false;
Like so:
document.getElementById('formContact').onsubmit = function(e) {
//your validateChamps stuff goes here
if(!bResult) e.preventDefault();
};
EDIT : I changed my submit button; I put a with onclick which submits the form if bResut == true

How do I enable a button when fields are filled in?

I'm trying to hide part of the form with the button disabled and have the user click on the button to show rest of form when previous fields are filled in. Can anyone help? Here's my code as an example:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1"/><br/>
<label>Field 2:</label>
<input type="text" class="field2"/><br/>
<label>Field 3:</label>
<input type="text" class="field3"/><br/>
</div>
<div align="center">
<button id="show_form" onClick = "this.style.display= 'none'" disabled="disabled">
Enter Billing Info</button>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
JQUERY
<script>
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
$("#show_form").prop("disabled", true);
$("#group2").hide();
$("#show_form").show();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
</script>
Try this jQuery:
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
var flag = true;
$('#group1').find('input[type="text"]').each(function () {
if ($(this).val().length === 0) {
flag = false;
return;
}
});
if (flag) {
$("#show_form").prop("disabled", false);
} else {
/* This will hide the bottom form and disable the button again if
* any of the field above will be emptied.
* NOTE: This will just hide the form; it will not clear the fields.
*/
$("#show_form").prop("disabled", true);
$("#group2").hide();
}
});
$("#group2").hide();
$("#show_form").click(function (){
$("#group2").show();
return false;
});
});
This will enable the button when all the fields in the initial form are filled. Then the user will be able to click on the button to see the rest of the form.
You just need to loop through each input and check if a value is set when the button is clicked like this:
$('#show_form').click(function () {
var fields = $('.js-field');
var pass = true;
for (var i = 0; i < fields.length; i++) {
if (!$(fields[i]).val()) {
pass = false;
}
}
if (pass === true) {
$('#group2').show();
}
});
I also needed to add some classes to your html:
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1 js-field"/><br/>
<label>Field 2:</label>
<input type="text" class="field2 js-field"/><br/>
<label>Field 3:</label>
<input type="text" class="field3 js-field"/><br/>
</div>
<button type="button" id="show_form" value="Show_Form">Enter Billing
Info</button>
<div id="group2" style="display: none;">
<label>Field 4:</label>
<input type="text" class="field4"/><br/>
<label>Field 5:</label>
<input type="text" class="field5"/><br/>
<label>Field 6:</label>
<input type="text" class="field6"/><br/>
</div>
</form>
To see it in action visit this fiddle.
You can add some logic to the click event and check all the input fields to have a value like this
$("#show_form").click(function(){
var allFilled = true;
$('#group1').find('input').each(function(){
//if someone is empty allFilled will keep false
if(this.value === ''){
allFilled = false;
//this breaks the each
return false;
}
});
if(allFilled){
$("#group2").show();
}
});
Keep in mind the previous code only work with input fields.

Categories