Disable submit if inputs empty jquery - javascript

Disclaimer: I know there are quite a few questions out there with this topic and it has been highly addressed, though I need assistance in my particular case.
I am trying to check if the input values are empty on keyup then disable the submit button.
My HTML snippet:
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" />
</div>
</form>
</div>
I have used the example answer from here with some modifications:
(function() {
$('.field input').keyup(function() {
var empty = false;
$('.field input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', true);
} else {
$('.actions input').attr('disabled', false);
}
});
})()
Any help would be greatly appreciated!

I would suggest disabling the button by default. I would also look at the length of the .val(), not check for an empty string. Lastly, I think document.ready() is much more readable than your existing code: Here is the full code:
HTML
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>​
JS/jQuery
$(document).ready(function() {
$('.field input').on('keyup', function() {
let empty = false;
$('.field input').each(function() {
empty = $(this).val().length == 0;
});
if (empty)
$('.actions input').attr('disabled', 'disabled');
else
$('.actions input').attr('disabled', false);
});
});
Here's a working fiddle.

I use this in my project and it succes.
$(document).ready(function() {
$('.field').keyup(function() {
var empty = false;
$('.field').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$('.actions[type="submit"]').attr('disabled', 'disabled');
} else {
$('.actions[type="submit"]').removeAttr('disabled');
}
});
});

Related

How can I disable submit form button until form is filled using jquery?

I've managed to disable the submit button but it is not re-enabling after there is text in the input field. How can I fix this?
<form>
<div class="col-lg-10 mb-3">
<div class="input-group mycustom">
<input type="text" class="form-control rounded-0" id="validationDefaultUsername" placeholder="Enter Your Name" aria-describedby="inputGroupPrepend2" required>
<div class="input-group-prepend">
<input type="submit" id="register" value="Submit" disabled="disabled" class="btn btn-secondary btn-sm rounded-0" id="inputGroupPrepend2" />
</div>
</div>
</div>
</form>
High Scores
Jquery:
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
You have multiple id's attributes in your submit button hence why you are having trouble with your code. One id is inputGroupPrepend2 and other is register - you can not have both in input
To disable the button use .prop() method and set to true if you want to disable and false when you want to enable it.
$('#register').prop('disabled', true); //disable
I have simplified your code and is working as expected.
$(function() {
$('input[type=text]').each(function(index, element) {
$(element).keyup(function() {
if ($(this).val() == '') {
$('#register').prop('disabled', true); //disable
} else {
$('#register').prop('disabled', false); //enable
}
});
})
});
Live Working Demo:
$(function() {
$('input[type=text]').each(function(index, element) {
$(element).keyup(function() {
if ($(this).val() == '') {
$('#register').prop('disabled', true); //disable
} else {
$('#register').prop('disabled', false); //enable
}
});
})
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<form>
<div class="col-lg-10 mb-3">
<div class="input-group mycustom">
<input type="text" class="form-control rounded-0" id="validationDefaultUsername" placeholder="Enter Your Name" aria-describedby="register" required>
<div class="input-group-prepend">
<input type="submit" value="Submit" disabled="disabled" class="btn btn-secondary btn-smrounded-0" id="register" />
</div>
</div>
</div>
</form>
High Scores
The > combinator selects nodes that are direct children of the first element.
Child combinator
Your keyup wasn't firing at all as well as $('form > input').each(function() { as that did not select input at al...
(function() {
$('form * input').keyup(function() {
console.log(true);
var empty = false;
$('form * input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="col-lg-10 mb-3">
<div class="input-group mycustom">
<input type="text" class="form-control rounded-0" id="validationDefaultUsername" placeholder="Enter Your Name" aria-describedby="inputGroupPrepend2" required>
<div class="input-group-prepend">
<input type="submit" id="register" value="Submit" disabled="disabled" class="btn btn-secondary btn-sm rounded-0" id="inputGroupPrepend2" />
</div>
</div>
</div>
</form>
High Scores
(function() {
$(document).on('keyup', 'input[type=text]', function(){
var empty = false;
$('input[type=text]').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
})
})()
You could update the bottom bit of code to this.
if (empty) {
if ($('#register').is(':disabled')) {
$('#register').removeAttr('disabled');
}
else {
$('#register').attr('disabled', 'disabled');
}
};

How to check if at least one input is completed?

I have this sample:
link
CODE HTML:
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>
CODE JS:
function sendForm() {
var status_form = false;
$(".add-patient input").each(function(){
if($(this).val() == ""){
status_form = true;
}
});
console.log(status_form);
var createdBy = jQuery('#created_by').val();
if( status_form )
{
alert('Fill at least one field');
}else{
alert("now it's ok");
}
}
I want to do a check ... if an input is complete when displaying the message "it; s ok" ... otherwise displaying another message
probably means the code clearly what they want to do.
You can help me with a solution please?
Thanks in advance!
Use .filter to get the length of the input elements having value as ''
Try this:
function sendForm() {
var elem = $(".add-patient input[type='text']");
var count = elem.filter(function() {
return !$(this).val();
}).length;
if (count == elem.length) {
alert('Fill at least one field');
} else {
alert("now it's ok");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>

How to show form fields on keyup

I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
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 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>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>

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.

Preventing user to enter more then 3 numbers before decimal point in javascript

In PHP textfield: Prevent the user from entering more then 3 numbers before decimal point
for example:
if user enter 123.12 its acceptable,
if user enter 12.12 its also acceptable,
but if user enter 1234.12 its not acceptable.
Just check this fiddle:
http://jsfiddle.net/S6uky/
HTML:
<form method="post">
<div class="row">
<label>Val 1</label>
<input type="text" class="validate" name="val1" maxlength="5"/>
</div>
<div class="row">
<label>Val 2</label>
<input type="text" class="validate" name="val2" maxlength="5" />
</div>
<div class="row">
<label>Val 3</label>
<input type="text" class="validate" name="val3" maxlength="5" />
</div>
<div class="row">
<button type="submit">Send</button>
</div>
</form>
JAVA SCRIPT:
$(function(){
$('.validate').blur(function(){
var reg=/^[0-9]{1}[0-9]{1}[\.]{1}[0-9]{1}[0-9]{1}$/g;
if($(this).val().match(reg)==null)
alert('Invalid input!');
});});
function isAccept(number){
return number.indexOf('.') < 4;
}
Try this code:
DEMO
$(function(){
$('.validate').blur(function(){
var reg=/^[0-9]{0,3}[.][0-9]{0,2}$/g;
console.log($(this).val().match(reg));
if($(this).val().match(reg)==null)
alert('Invalid input!');
else
alert('valid input!');
});});
Try with .test() this way:
$(function () {
$('.validate').blur(function () {
var reg = /^[0-9]{0,3}[\.]{1}[0-9]{0,2}$/g; //<---updated this
if (!reg.test(this.value)) {
alert('Invalid input!');
$(this).focus();
return false;
}
});
});
Demo Fiddle
Another way is make a global function and use it as a callback:
function isValidInput() {
var reg = /^[0-9]{0,3}[\.]{1}[0-9]{0,2}$/g;
if (!reg.test(this.value)) {
alert('Invalid input!');
$(this).focus();
return false;
}
}
$(function () {
$('.validate').blur(isValidInput);
});
Another fiddle

Categories