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.
Related
I have a form and I'm validating the fields "onblur". what I trying to do is that when the user clicks submit make that any field is empty.
What I was trying to do is to pass the value to a function and run that function when the user click "submit" but I'm having a problem in doing that.
can somebody point me in the right direction on how to fix my problem.
HTML:
<form method="post" name="registerForms" >
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
JS:
function validateForm(id)
{
var value = document.getElementById(id).value;
var ok = true;
if(value === "" || value == null)
{
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
ok = false
yesNo(ok);
}
else
{
document.getElementById(id+'Err').innerHTML = "* ";
}
}
var button = document.getElementById('#registerButton');
button.onclick = function yesNo(ok)
{
alert("There's something wrong with your information!")
if(ok == false)
{
alert("There's something wrong with your information!")
return false;
}
}
If you want to attach the validation on the click event for your submit button I would suggest you to repeat the validation for each input field like you do on blur event.
Moreover, I would suggest you to save the ok value as an attribute of each input field. Set those attributes at dom ready to false and change it to true/false in validateForm function.
When submitting it's a good idea to run your valodator function and test for false fields.
You can use addEventListener in order to register a event handler, querySelectorAll for selecting elements.
The snippet:
function validateForm(id) {
var value = document.getElementById(id).value;
if (value === "" || value == null) {
document.getElementById(id+'Err').innerHTML = "* <img src='images/unchecked.gif'> Field is required";
document.getElementById(id).setAttribute('yesNo', 'false');
} else {
document.getElementById(id+'Err').innerHTML = "* ";
document.getElementById(id).setAttribute('yesNo', 'true');
}
}
document.addEventListener('DOMContentLoaded', function(e) {
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
ele.setAttribute('yesNo', 'false');
});
document.getElementById('registerButton').addEventListener('click', function(e) {
var ok = true;
document.querySelectorAll('form[name="registerForms"] input:not([type="submit"])').forEach(function(ele, idx) {
validateForm(ele.id);
if (ele.getAttribute('yesNo') == 'false') {
ok = false;
}
});
if (ok == false) {
console.log("There's something wrong with your information!")
e.preventDefault();
}
});
});
<form method="post" name="registerForms" action="http://www.google.com">
<div class="form-group">
<label for="nusernames">Username: <span id="nusernamesErr" class="error">* </span></label>
<input type="text" class="form-control" id="nusernames" name="nusernames" onblur="validateForm('nusernames')">
</div>
<div class="form-group">
<label for="nemail">Email: <span id="nemailErr" class="error">* </span></label>
<input type="email" class="form-control" id="nemail" name="nemail" onblur="validateForm('nemail')">
</div>
<input type="submit" class="btn btn-default" value="Submit" id="registerButton">
</form>
You were trying to define var button with this
var button = document.getElementById('#registerButton');
but it needs to be this with regular javascript
var button = document.getElementById('registerButton');
That seemed to solve the problem
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>
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">
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>
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');
}
});
});