I have a login form.
Field: Username textbox, password text box, 2 check boxes, submit button--- everything inside a form.
submit button initially disabled. It is enabled only when username, password or AT LEAST any one checkbox is checked. button gets enabled when username & password fields are entered. no change happens even if checkbox is checked or unchecked.
<form class="form-horizontal" role="form" action="page2.html">
<div class="form-group">
<label for="txtusername" class="col-sm-4 control-label ">Username</label>
<div class="col-sm-8">
<input type="text" class="form-control textboxprop" id="txtusername" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="txtpassword" class="col-sm-4 control-label ">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control textboxprop" id="txtpassword" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<div class="checkbox">
<input id="chk" type="checkbox" >chk1
<input id="chk" type="checkbox" >chk2
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="signin" class="btn btn-default" disabled>Sign in</button>
</div>
</div>
</form>
This is the form. Below given is the javascript function I use.
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
You need to listen checkboxes change event too. Try this code:
var $input = $('input'),
$check = $input.filter(':checkbox'),
$register = $('#signin');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$check.filter(':checked').length);
});
Demo: http://jsfiddle.net/jy3UR/1/
Your HTML is invalid. A <label> is closed which wasn't started and you have a duplicate ID 'chk'...
You need to put it in the onload event of the document and indeed as #dfsq already stated, you need to add a check for the checkboxes too, like so:
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$chk = $('input[type=checkbox]');
$register.attr('disabled', true);
$input.on('keyup change', function() {
var trigger = false;
$input.each(function() {
if (this.type != 'checkbox' && !$(this).val()) {
trigger = true;
}
});
$register.prop('disabled', trigger || !$chk.filter(':checked').length);
});
})
otherwise it will get executed when the DOM has not fully loaded yet and your fields will not be available...
DEMO
First of all you have used same id for both the check box.
rename it like below
<input id="chk1" type="checkbox" >chk1</label>
<input id="chk2" type="checkbox" >chk2</label>
and modify your code like below :
<script>
$(document).ready(function() {
var $input = $('input'),
$register = $('#signin');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
var checked = $("input[type='checkbox']:checked");
if(checked.length >0) // check if atleast one checkbox checked
trigger = true;
if(!trigger){
if(!$(this).val()) {
trigger = true;
}
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
});
</script>
You should try this simple solution :
jQuery(function($) {
$('form input').on('change',function() {
isDisabled = !(($('#txtusername').val().length > 0 && $('#txtpassword').val().length > 0) || $('input[type="checkbox"]:checked').length > 0);
$('#signin').attr('disabled', isDisabled);
});
});
It does its job.
Related
I am trying to make a form with Materialize that validates one email. I start off with a submit button toggled to disabled. Ideally, when the email is filled in and validated, the submit button will stop being disabled and the user can click it to the next page. Here is my HTML:
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="text" name= "email" class="validate" required="" aria-required="true">
<label for="email">Email Address</label>
</div>
<br></br>
<a class="waves-light btn red lighten-2 disabled" id="submit">Submit
<i class="material-icons right">send</i>
</a>
<br></br>
<br></br>
<br></br>
</form>
Here is the JavaScript/jQuery:
$(document).ready(function(){
$('.parallax').parallax();
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
$('body').on('click', 'input', function() {
checkValidity($(this));
});
$('body').on('focusout', 'input', function() {
checkValidity($(this));
});
function checkValidity (current) {
let isValid = true;
if (!current.val()) {
isValid = false;
} else {
isValid = iteratatingForm(current);
}
const submit = $('#submit');
if (isValid) {
submit.removeClass('disabled');
} else {
if (!submit.hasClass('disabled')) {
submit.addClass('disabled');
}
}
}
function iteratatingForm (current) {
if (!document.forms['survey']['email'].value) return false;
return true;
}});
Please let me know what I'm doing wrong! Thanks!
You can use email type for your input and a button submit who will trigger validation input.
I added a function to check if email is valid with a regex. (Found here : How to validate email address in JavaScript? )
You have to add jQuery Validation Plugin
$(document).ready(function(){
$('#survey input').on('keyup', function(){
var validator = $("#survey").validate();
if (validator.form() && validateEmail($('#email').val())) {
$('#submitButton').prop('disabled', false);
$('#submitButton').removeClass('disabled');
}
else{
$('#submitButton').prop('disabled', true);
$('#submitButton').addClass('disabled');
}
} );
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email.toLowerCase());
}
/*
Confirmation Window
*/
$('body').on('click', '#submit', function() {
let decision = confirm('Are you sure you would like to submit your survey?');
if (decision) {
$.post('insert.php', $('#survey').serialize());
window.location.href = 'thankyou.php';
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet"/>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<form id="survey">
<div class="input-group">
<p class="input-header">Enter Your Email</p>
<div class="input-block input-field">
<input id="email" type="email" name= "email" class="validate" required="true" aria-required="true">
<label for="email">Email Address</label>
</div>
<button type="submit" form="survey" value="Submit" class="waves-light btn red lighten-2 disabled" disabled='disabled' id="submitButton">Submit</button>
</form>
StackOverflow snippet bug due to jQuery validation plugin, but it works in CodePen
Another way to solve this is to add a regex field to your <input ... elements e.g.
<div class="input-field col s6">
<input id="email" type="text" class="validate" value="hello#email.com" regex="(?!.*\.\.)(^[^\.][^#\s]+#[^#\s]+\.[^#\s\.]+$)" required="" aria-required="true" value="hello#email.com" >
<label for="email">Email</label>
<span class="helper-text" data-error="Invalid email address."></span>
</div>
The nice thing about this is you can have individual regex validation for other fields. For example, you could have other inputs such as name / age e.g.
name (only contain groups of UPPER-CASE characters separated by a single space e.g. JAMES JONES - regex = ^[A-Z]*(\s[A-Z]+)*$).
age (only contain numbers - regex = ^\d+$).
NOTE: - I recommend the https://regex101.com/ website to test our your regex expressions against example text.
To validate using e.g. JQuery - you would add listeners to each of your input elements: -
$(document).ready(function(){
$("input").on('input propertychange blur', function(event) {
var elm = event.currentTarget;
var val = elm.value;
var isValid = true; // assume valid
// check if required field
if (elm.hasAttribute("required")) {
isValid = val.trim() !== '';
}
// now check if regex
if (isValid && elm.hasAttribute("regex")) {
var regex = new RegExp(elm.getAttribute("regex"), 'g');
isValid = regex.test(val);
}
elm.classList.remove(isValid ? "invalid" : "valid");
elm.classList.add(isValid ? "valid" : "invalid");
updateButtonState();
});
});
function updateButtonState () {
var numOfInvalid = $('input.invalid').length;
if (numOfInvalid > 0) {
$('.submit-button').prop('disabled', true);
$('.submit-button').addClass('disabled');
}
else{
$('.submit-button').prop('disabled', false);
$('.submit-button').removeClass('disabled');
}
}
When the page loads the JQuery function listens to changes to the input (and also blur events). It first of all checks if the input is a required field and validates that first. Next of all, it checks if a regex attribute exists, and if so, performs regular expression based validation.
If the validation fails, then the function adds/removes classes related to Materialize CSS and then finally updates the button state. This is optional but very nice if you are filling in a form (button is only enabled if everything is valid).
See the following CodePen to see everything in action: -
https://codepen.io/bobmarks/pen/oNGGvWq
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'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.
I am trying to run the following function:
var getFavorite = function(){
var favCheck = document.querySelector("#fav");
var status;
if(favCheck.checked){
status = "Yes!";
}else{
status = "No";
}
return status;
};
The html form contains the following:
<form action="#" id="flavorForm">
<ul id="errors"></ul>
<div data-role="fieldcontain">
<label for="drug">Flavor: </label>
<input type="text" name="flavor" id="flavor" class="required" />
</div>
<div data-role="fieldcontain">
<label for="favorite">Favorite?</label>
<input type="checkbox" id="favorite" value="Yes" class="checkbox" />
</div>
<div data-role="fieldcontain">
<label for="notes">Notes: </label>
<textarea name="notes" id="notes"></textarea>
</div>
<input type="submit" value="Save Flavor" id="submitFlavor" data-theme="b" />
</form>
And the values for favCheck should come from the second ... block of the form. But I'm getting a 'TypeError: favCheck is null' whenever I input a value on the form, whether I check the checkbox or not. I am using jQuery to retrieve the values. Any suggestions are appreciated. Thanks.
You misspelled the id name. Please use #favorite instead of #fav
Try this,
var getFavorite = function(){
var favCheck = document.querySelector("#favorite");
var status;
if(favCheck.checked){
status = "Yes!";
}else{
status = "No";
}
return status;
};
DEMO
HTML
<input type="checkbox" id="checkme" checked="checked" />
jQuery
$('#checkme').change(function () {
var checkbox = $('#checkme').prop('checked');
if (checkbox) {
alert('checkbox is checked');
} else {
alert('checkbox is not checked');
}
});
http://jsfiddle.net/rjE8P/
Since you're using an ID rather than a class
favcheck = document.getElementById('fav');
Also, you need to actually use that ID fav rather than favorite as it is now.
$('#favorite').change(function(){
var status;
if($(this).is(':checked')) {
status = 'Yes';
}
else{
status = "No";
}
alert(status);
});
I can't figure out why the script isn't working with the form. Why doesn't the $("form").submit(function() call the form with id form? This script isn't even performing the window.onbeforeunload so I guess the script is faulty. Does anyone know what's wrong?
<form id="formID" class="access_form" name="form" method="post" action="site.com">
<div class="row">
<label for="email">Email Address:</label>
<input class="txt_email" type="text" id="email" name="email" value="" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" />
</div>
<div class="row">
<input type="submit" class="btn_access" value="Get Immediate Access" name="submit1" />
</div>
</form>
JavaScript:
var formHasChanged = false;
var submitted = false;
$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form
select, form.confirm-navigation-form textarea', function (e) {
formHasChanged = true;
});
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (formHasChanged && !submitted) {
var message = "Please enter your email", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
$("#formID").submit(function () {
submitted = true;
});
});
just try this.The id of the form is form itself.So select the form like this using jQuery
$("#form").submit(function () {
submitted = true;
});
OR
Or try giving another id for the form for example "formID".Then select using that id like this.
$("#formID").submit(function () {
submitted = true;
});