Jquery validation of input array elements manually - javascript

<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
How do i validate these 4 fields so that they are not blank.. without using jquery validate plugin.?

You can cancel the form submission by registering a submit event handler and prevent the default behavior if one of your fields is empty:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]'][value='']", this).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
EDIT: As naveen correctly points out, the code above would still submit the form if the fields only contain whitespace. You can use $.trim() with filter() to fix the problem:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]']", this).filter(function() {
return $.trim(this.value) == "";
}).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});

$('input:submit').click(function() {
$('form').submit(function(e) {
$("input:text[name^='member_name']").each(function() {
if (!$.trim($(this).val()).length) {
alert('Name Field should not leave empty');
return false; // or e.preventDefault();
}
});
});
});

var valid = true;
$('input').each(function(){
if($(this).val() == "") {
valid = false;
}
});
// use valid here

var invalidInputs = $('input').filter(function() {
return $(this).val() == "";
});
var valid = invalidInputs.length == 0

Not most advance, but simple & clear method.
$("form").submit(function(event) {
var inputLength = $('input[type="text"]').val().length; // check for value length
if ($('input').val().length > 0) {
// submit if input value is length > 0
alert('Form submitted.');
}
else {
// error if input value is NOT length > 0
alert('Fill the form.');
event.preventDefault();
}
});

Related

Get the input selector using this

I have set of input fields which are generated dynamically, hence I can't use an ID. For each of the input fields I have a focusout method which validates the value input by the end user.
If the validation fails, I would like to clear the value of the input and bring back the focus to the same input. When I tried to use this keyword scope seems to be set to the windows rather than the input control.
Input fields screenshot:
function validate(reg){
debugger;
if(isNaN(reg)==false){
return;
}
else
{
alert("The field should contain number");
$(this).val(""); //clear the value
$(this).focus();
}
}
In the above code, this keyword doesn't seem to work.
Pass the event to your validate() function, and then you can use event.target to target the input element.
function validate(reg, e){
debugger;
if(isNaN(reg)==false){
return;
}
else
{
alert("The field should contain number");
$(e.target).val(""); //clear the value
$(e.target).focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input onfocusout="validate(this.value, event)"/>
<input onfocusout="validate(this.value, event)"/>
<input onfocusout="validate(this.value, event)"/>
Another method:
$(document).ready(function () {
var inputs = document.querySelectorAll("input[type=text]");
for (i = 0; i < inputs.length; i++)
inputs[i].addEventListener("focusout", function () { validate(this); });
});
function validate(reg) {
if (isNaN($(reg).val()) == false) {
return;
}
else {
alert("The field should contain number");
$(reg).val(""); //clear the value
$(reg).focus();
}
}
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />

Unable to stop form from submitting with empty inputs

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

enabled button if password match

here is my script
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
enter.disabled = true;
} else if (user_pass == user_pass2 ){
enter.disabled = false;
} else {
enter.disabled = true;
alert("Your password doesn't same");
}
});
this my html
Password : <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
i am really new in Javascript and jQuery, and this is my first using jquery. i need to make a disabled button if the password doesn't match but, after i put the same password the button is still disabled.
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
//var enter = $("#enter").val();
if (user_pass.length == 0) {
alert("please fill password first");
$("#enter").prop('disabled',true)//use prop()
} else if (user_pass == user_pass2) {
$("#enter").prop('disabled',false)//use prop()
} else {
$("#enter").prop('disabled',true)//use prop()
alert("Your password doesn't same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Password :
<input type="password" name="user[user_pass]" id="reg_pass" required="required">Confirm password
<input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
Use .prop()
You need to set disable attribute like this in jquery $("#enter").attr('disabled',true);
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").attr('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").attr('disabled',false);
} else {
$("#enter").attr('disabled',true);
alert("Your password doesn't same");
}
The .prop( propertyName, value ) allow you set one or more properties for the set of matched elements.
JS
$(function() {
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var confirm_user_pass = $("#reg_confirm_pass").val();
var enter = $("#enter");
if (user_pass.length == 0) {
alert("please fill password first");
enter.prop('disabled', true)
}
else if (user_pass == confirm_user_pass) {
enter.prop('disabled', false)
}
else {
enter.prop('disabled', true)
alert("Your password doesn't match");
}
});
});
HTML
Password: <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password: <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
I believe the other answers are right on target. I set up a simple 'jsfiddle' using jquery and its .prop() method to better illustrate here.
NOTE: I would probably bind to another event to make it fire when changes are made to either input element.
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").prop('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").prop('disabled',false);
} else {
$("#enter").prop('disabled',true);
alert("Your password doesn't same");
}
});
Actually blur will not enable the button instantly, keyup eventhandler does the best job. Here's the below code.
$("#reg_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
$("#reg_confirm_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
Here it responds to the changes in either of the text boxes instantly.
Check it here.
Any better solution than this, please let me know. Thank you.

Check if every elemnt from a form is filled JQUERY

I have a form with all types of form elemnts and I have a code that should run through every single one of the elemnts and check their value after the submit button is clicked. Unfortunatelly, this code doesn't work completely. What I mean is that if I don't enter any value in the input, it will print the message, but if I enter some text in it, we go to the else statement, without checking the other.
Could somebody tell me why?
if($('form.registration-form :input').val() == '')
{
// Print Error Message
}
else
{
// Do something else
}
You can use filter method for this:
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
// all IS filled in
} else {
// all is NOT filled in
}
$('#submit').click(function(){
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
alert('All Filled');
} else {
alert('1 or more not filled')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" class="registration-form">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="submit" id="submit" value="Check">
</form>

Submit Form when all fields completed

I have this form
<form method="post" name="lunch" id="lunch">
<input type="number" id="people" name="people" onchange="calculo_lunch()" class="form-control">
<input type="number" id="duration" name="duration" onchange="calculo_lunch()" class="form-control">
</form>
And i use this jquery script to submit it
$(function(){
$("#lunch").submit(function(){
//jquery code
return false; // Evitar ejecutar el submit del formulario.
})
});
$('input[type="number"]').on('change', function() { $("#lunch").trigger('submit'); })
This submit my form when one of the fields is changed but now i need that this form triggers when both of the fields are completed
This will check each 'number' type input and count up the number that have some value. If the number of inputs with values matches the number of inputs, the form submits. This will work for any number of inputs, so if you add 10 more it will still work.
$('input[type="number"]').on('change', function() {
//initialize counter
var completed_fields = 0;
//count up the number of completed number inputs
$('#lunch').find('input[type="number"]').each(function(){
if($(this).val()){
completed_fields += 1;
}
});
//test the number of completed fields vs the total number of fields
if($('#lunch').find('input[type="number"]').length == completed_fields)
{
$("#lunch").trigger('submit');
}
});
Try this.
var fields = $('input[type="number"]'); //store all fields ref
fields.change(function() {
if(fields.filter(function(){
return !!$(this).val();
}).length == field.length) { //all fields has values.
$("#lunch").submit();
}
})
$(function(){
$("#lunch").submit(function(){
//check if both values are whatever you need -->
if (parseInt($('#people').val()) > 0 && parseInt($('#duration').val()) > 0){
//jquery code
}else{
return;
}
}
});
return false; // Evitar ejecutar el submit del formulario.
})
});
$('input[type="number"]').on('change', function() { $("#lunch").trigger('submit'); })
You want to make sure that each input has a value before triggering the submit event and bind your onChange event within DOM ready.
$(function(){
$("#lunch").submit(function(){
//jquery code
return false; // Evitar ejecutar el submit del formulario.
}); // end submit
$('input[type="number"]').on('change', function() {
if( $('input[type="number"]').filter(function() { return this.value == ''; }).length === 0 ) {
$("#lunch").trigger('submit');
}
});
});
You can use html5 required tag on the fields:
<input type="number" id="people" name="people" onchange="calculo_lunch()" class="form-control" required>
that should prevent submitting if field is empty..

Categories

Resources