Sorry this might be a duplicate Q , but could not find a direct solution easily,
I have gone through SO answer and found , enable submit if all values are filled ,
$(document).ready(function() {
$('.field input').keyup(function() {
var empty = false;
$('.field input').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').attr('disabled', false);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
But how to achieve the same(enable submit) if atleast one field is non-empty
You can try this:
$(document).ready(function() {
$('.field input').keyup(function() {
var hasValue = $('#username,#password').filter((index, input) => input.value.length > 0).length;
$('.actions input').attr('disabled', hasValue ? false : 'disabled');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Update:
$('#username,#password').filter((index, input) => input.value.length > 0).length
This line means we will check the value of the 2 input elements username and password, if all of them don't have any value, the button will be disabled. If you want to check another input element before enabling/disabling, you can add:
$('#username,#password,#input_3,#input_4').filter(...).length
By this way, the button will be disabled when username, password, input_3 and input_4 elements don't have any value. Make sure you have a specific id for each input element.
Update 2:
Checking for both username and password have some value:
var hasValue = $('#username,#password').filter((index, input) => input.value.length > 0).length === 2
Checking for field, field4 and field5 have some value:
var hasValue = $('#field,#field4,#field5').filter((index, input) => input.value.length > 0).length === 3
Use jQuery props method.
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}else{
$(':input[type="submit"]').prop('disabled', true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Another way to go about it:
Store the fields, and create a new collection of them each time a key is pressed, filtering each one by its value.
If the length of our empty fields is the same as the length of all fields, disable the button:
$(document).ready(function() {
var $fields = $('.field input');
$fields.keyup(function() {
var $emptyFields = $fields.filter(function(){
return !this.value;
});
$('.actions input').prop('disabled', $emptyFields.length === $fields.length);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Documentation:
.filter()
.prop()
You could with Jquery.map and Array.find
Jquery.map().get() is get all the input value length with condition.
Array.find will find the any one of the input as valid length of string
Then finally the result will be reversely compare prop('disabled', !filled)
$(document).ready(function() {
$('.field input').keyup(function() {
var res = $('.field input').map(function() {
return $(this).val().length != 0
}).get()
var filled = res.find(a=> a == true)
$('.actions input').prop('disabled', !filled);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Updated with select option
Required field based .Button only enabled after required field 1 and 3 both are filled
$(document).ready(function() {
$('.field input,.field select').on('keyup change',function() {
var res = $('.field input[required],.field select[required]').map(function() {
return $(this).val().trim().length != 0
}).get();
var filled = res.every(a => a == true)
$('.actions input').prop('disabled', !filled);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username *</label>
<input id="username" required type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='field'>
<label for="password">email *</label>
<input id="password" required type="password" />
</div>
<div class='field'>
<label for="password">select email *</label>
<select required>
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
</select>
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
You can try this in a simple way, as shown below:
var filled = false;
$('.field input').each(function() {
if ($(this).val().length > 0) {
filled = true;
return; // just add return means break from loop whenever any field is filled.
}
});
if (filled) {
$('.actions input').attr('disabled', false);
} else {
$('.actions input').attr('disabled', 'disabled');
}
});
Related
I have a form which has various input field with a common name(input array field). I tried to access the value of all elements once the form gets submitted. I able to access all the input field apart from the radio button.
$(document).ready(function() {
function getValue(elem) {
let val = $(elem).val();
if (val === "video") {
let other = $("#videoLink").val();
return other;
}
if (val === "youtube") {
let other = $("#youtubeLink").val();
return other;
}
}
$("#submit").on("click", function() {
$("#form").trigger("submit");
})
$("#form").on("submit", function(e) {
e.preventDefault();
var firstNameValues = $("input[name='firstName[]']").map(function() {
return $(this).val();
}).get();
var lastNameValues = $("input[name='lastName[]']").map(function() {
return $(this).val();
}).get();
var linkValues = $("input[name='link[]']:checked").map(function() {
return getValue(this)
}).get();
})
$("#add-more").on("click", function() {
$("#form > .container").clone().insertAfter("#form");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
<form name="form" id="form" class="form" method="post">
<div class="container">
<div class="col-md-12 form-group">
<input type="text" name="firstName[]" class="form-control" placeholder="First name" />
</div>
<div class="col-md-12 form-group">
<input type="text" name="lastName[]" class="form-control" placeholder="Last Name" />
</div>
<div class="col-md-12 form-group">
<input type="email" name="email[]" class="form-control" placeholder="Email" />
</div>
<div class="col-md-12 form-group">
<input type="radio" name="link[]" value="youtube">Youtube:<input type="text" id="youtubeLink" name="youtubeLink[]" placeholder="Youtube" />
<input type="radio" name="link[]" value="video">Video<input type="text" id="videoLink" name="videoLink[]" placeholder="Video" />
</div>
</div>
</form>
<button type="button" id="add-more">Add</button>
<button type="button" id="submit" name="submit">Submit</button>
</div>
My HTML code is
<body>
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
<script>
function search() {
var Tab = document.getElementById("Tab").value;
alert(Tab);
var Eamillogin = document.getElementById("UEmailLogin").value;
if (Eamillogin == "") {
alert("please enter email");
Eamillogin.focus();
}
}
</script>
</body>
When I click on submit button, JavaScript alert shows "please enter email". It works fine. But Eamillogin.focus(); not working. After showing alert, the form automatically direct to test1.php page.Pointer not focus on Email. How to correct it?
Eamillogin variable contains the value of the #UEmailLogin element.
To set the focus on the element, use element.focus();
Here's updated code
var Eamillogin = document.getElementById("UEmailLogin"); // Removed .value from here
if (Eamillogin.value === "") { // Added .value here
alert("please enter email");
Eamillogin.focus(); // Focus element
}
function search() {
var Tab = document.getElementById("Tab").value;
var Eamillogin = document.getElementById("UEmailLogin");
if (Eamillogin.value === "") {
alert("please enter email");
Eamillogin.focus();
}
}
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
I have created a web page using bootstrap. There are 2 text boxes and a button to submit. I have written JavaScript function to give an alert if any text field is empty. I am amazed to see that it is not working. My JavaScript function is:
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
My form code is:
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
How have you included the validateForm javascript?
for instance the following works for me:
<html>
<body>
<script>
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
</script>
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
</body>
</html>
Basically, I want to prepend a div only if the div I'm prepending isn't already showing.
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
At the moment, I'm trying to make it so the jquery will only do the if empty if statement if the error isn't currently visible however it's not working...
<div class="pageCont">
<div class="title">
<h1>LetsChat</h1>
<h4>The new way of interaction.</h4>
</div>
<div class="login box">
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" /><br>
<input type="password" class="loginInput password" placeholder="Password" /><br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
</div>
<div class="signup box">
<form method="POST" action="#" class="signupForm">
<input type="text" class="signupInput" placeholder="First Name" /><br>
<input type="text" class="signupInput" placeholder="Last Name" /><br>
<input type="text" class="signupInput" placeholder="Aquinas Email" /><br>
<input type="password" class="signupInput" placeholder="Password" /><br>
<input type="submit" class="purple btn signup" value="Sign Up Today!">
</form>
</div>
</div>
The below should work if I'm understanding your question correctly?
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error").length;
if (!username || !password)
{
if(errorvisible == 0)
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
I have used this type of code many times:
if(!$('#myFancyDiv').is(':visible')) {
//prepend or do whatever you want here
}
BTW just for clarity, this code checks if 'myFancyDiv' is not visible.
You can check whether the .error.alert elements exists, if so don't do anything else create a new one
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
if (!$('.error.alert').length) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$(this).remove();
});
}, 6000);
}
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" />
<br>
<input type="password" class="loginInput password" placeholder="Password" />
<br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
I'm trying to disable submit button until first two fields have input. I've written a function to do that but for some reason it's not working.
Here is my HTML:
<html>
<Head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="Stuff.js"></script>
</Head>
<body>
<div class="container">
<form role="form">
<div class="form-group has-error">
<label for="FirstName">First Name</label>
<input type="text" class="form-control" id="First" placeholder="First Name">
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
<input type="text" class="form-control" id="Last" placeholder="Last Name">
</div>
<div class="form-group">
<label for="Age">Age</label>
<input type="text" class="form-control" id="Age" placeholder="Age">
</div>
<button type="submit" class="btn btn-default" id="submit" >Submit</button>
</form>
</div>
</body>
This is my function:
$('#submit').keyup(function () {
if ($('#First').val() != "" && $('#Last').val() != "") {
$('#submit').removeattr('disabled');
} else {
$('#submit').attr('disabled', true);
}
});
You could use something like this:
$('#First, #Last').keyup(function () {
if ($('#First').val() !== "" && $('#Last').val() !== "") {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
});
Note that you need to check the fields themselves upon keyup.
Also, use prop() to set the underlying boolean property of the disabled attribute to true/false, instead of removing it completely - see here for why.
jsFiddle here.