How to remove a class from input - javascript

I have a piece of JavaScript code that validates a form. If the input field is empty I'm adding the "empty" which puts a red background on the input field.
Is there a way to remove that class when the user clicks on the field?
I had tried this, but it did not work.
$('input').bind('blur', function(){
$(this).removeClass('empty');
});
function register()
{
var errornotice = "This field is required";
if(document.myForma.userid.value == '')
{
var id = $("#userid");
id.addClass("empty");
id.val(errornotice);
}
if(document.myForma.fullname.value == '')
{
var name = $("#fullname");
name.addClass("empty");
name.val(errornotice);
}
if($(":input").hasClass("empty"))
{
return false;
}
else
{
errornotice.hide();
return true;
}
$('input').bind('blur', function(){
$(this).removeClass('empty');
});
}
.empty
{
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form role="form" action="index.php" method="post" id="apply-form input" onSubmit="return(register());" name="myForma">
<div class="form-group">
<label for="userN">User Name<span class="error">*</span></label>
<input type="text" name="userid" class="form-control" id="userid">
</div>
<div class="form-group">
<label for="fullname">Full name<span class="error">*</span></label>
<input type="text" id="fullname" name="fullname" class="form-control">
<p id="empty"></p>
</div>
<input type="submit" value="submit" id="submit">
</form>

It looks like you were on the right track by using on blur, but I would recommend using on focus and also change the text to the empty string. Also, the way it looks like you want your text to behave is more like a placeholder, so you may want to consider using that, but the code below doesn't use it.
function register()
{
var errornotice = "This field is required";
if(document.myForma.userid.value == '')
{
var id = $("#userid");
id.addClass("empty");
id.val(errornotice);
}
if(document.myForma.fullname.value == '')
{
var name = $("#fullname");
name.addClass("empty");
name.val(errornotice);
}
$('.form-control').bind('focus', function(){
$(this).val('');
$(this).removeClass('empty');
});
}
.empty
{
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form role="form" action="index.php" method="post" id="apply-form input" onSubmit="return(register());" name="myForma">
<div class="form-group">
<label for="userN">User Name<span class="error">*</span></label>
<input type="text" name="userid" class="form-control" id="userid">
</div>
<div class="form-group">
<label for="fullname">Full name<span class="error">*</span></label>
<input type="text" id="fullname" name="fullname" class="form-control">
<p id="empty"></p>
</div>
<input type="submit" value="submit" id="submit">
</form>

You can use the focus() method to remove the class when the user clicks on this control. This will work with a mouse and a keyboard as well.
$('input[type="text"]').focus(function(){
$(this).removeClass('empty').val('');
});
function register()
{
var errornotice = "This field is required";
if(document.myForma.userid.value == '')
{
var id = $("#userid");
id.addClass("empty");
id.val(errornotice);
}
if(document.myForma.fullname.value == '')
{
var name = $("#fullname");
name.addClass("empty");
name.val(errornotice);
}
if($(":input").hasClass("empty"))
{
return false;
}
else
{
errornotice.hide();
return true;
}
}
$('input[type="text"]').focus(function(){
$(this).removeClass('empty').val('');
});
.empty
{
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form role="form" action="index.php" method="post" id="apply-form input" onSubmit="return(register());" name="myForma">
<div class="form-group">
<label for="userN">User Name<span class="error">*</span></label>
<input type="text" name="userid" class="form-control" id="userid">
</div>
<div class="form-group">
<label for="fullname">Full name<span class="error">*</span></label>
<input type="text" id="fullname" name="fullname" class="form-control">
<p id="empty"></p>
</div>
<input type="submit" value="submit" id="submit">
</form>

function register()
{
var errornotice = "This field is required";
if(document.myForma.userid.value == '')
{
var id = $("#userid");
id.addClass("empty");
id.val(errornotice);
}
if(document.myForma.fullname.value == '')
{
var name = $("#fullname");
name.addClass("empty");
name.val(errornotice);
}
if($(":input").hasClass("empty"))
{
return false;
}
else
{
errornotice.hide();
return true;
}
}
$('input[type="text"]').bind('focus', function(){
$(this).removeClass('empty').val('');
});
.empty
{
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form role="form" action="index.php" method="post" id="apply-form input" onSubmit="return(register());" name="myForma">
<div class="form-group">
<label for="userN">User Name<span class="error">*</span></label>
<input type="text" name="userid" class="form-control" id="userid">
</div>
<div class="form-group">
<label for="fullname">Full name<span class="error">*</span></label>
<input type="text" id="fullname" name="fullname" class="form-control">
<p id="empty"></p>
</div>
<input type="submit" value="submit" id="submit">
</form>

Related

How to call mutiple id using `this` in jquery

here I'm doing contact forms.In the same page, I have 10 forms and I want to validate all form.I want to use same validation code for all forms.here I gave id's but the problem is the same id's not working on the same page.I want to use current id.Can anyone suggest how should I do?
Feel free to tell is there any mistakes in my code.
Thanks
$(document).ready(function(){
/* name*/
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* E-mail */
$('#contact_email').on('input', function() {
var input=$(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email=regex.test(input.val());
if(is_email){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* select People*/
$('#contact_select').change(function() {
var select=$(this);
var selectOption = $("#contact_select option:selected").val();
if(selectOption){
select.removeClass("invalid").addClass("valid");
}
else{
select.removeClass("valid").addClass("invalid");
}
});
/* select Time*/
$('#contact_time').change(function() {
var select=$(this);
var selectTime = $("#contact_time option:selected").val();
if(selectTime){
select.removeClass("invalid").addClass("valid");
}
else{
select.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("#contact_submit button").click(function(event){
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#contact_"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free){
return false;
}
else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row current" id="demo1">
<form id="contact" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
<div class="row current" id="demo2">
<form id="contact" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
It seems you are using HTML5, then adding custom methods for validation is not a good idea.
Try using jquery validation and pattern attribute like:
function submitForm(id){
var isValid = $("#" + id).valid();
if(isvalid)
/* Yes valid*/
else
/* Invalid*/
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<div class="row current" id="demo1">
<form id="contact1" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="button" class="btn" onclick="submitForm('contact1')"> Submit</button>
</div>
</form>
</div>
<div class="row current" id="demo2">
<form id="contact2" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"/>
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="button" onclick="submitForm('contact2')" class="btn"> Submit</button>
</div>
</form>
</div>
UPDATE:
Dynamic function called on button clicked. Type is button instead of submit
Hope you will get the point and it helps.
Happy Coding !!!!
You can use a custom attribute like data-validation="validation-type" on your input controls then do a for each on your form with
$('<myform>').find('*[data-validation]').each(function(){
// in here get the this object for each input control the code to validate comes here
var valType = $(this).attr('data-validation');
switch(valType)
{
case 1:
//validation of case 1
break;
//add other cases as of your need.
}
});
Edit 1
For example you can play around with this snippet:
var button = $("button")
// handle click and add class
button.on("click", function() {
//validating controls for form 1
debugger;
$('#myform1').find('*[data-validation]').each(function(e) {
validateInput(this);
});
//validating controls for form 2
$('#myform2').find('*[data-validation]').each(function(e) {
validateInput(this);
});
})
function validateInput(control) {
if (control == null || control === undefined)
return null;
var validType = $(control).attr('data-validation');
if (validType == null || validType === undefined)
return null;
switch (validType) {
case "text":
if ($(control).val().trim().length == 0)
$(control).addClass('invalid').removeClass('valid');
else
$(control).addClass('valid').removeClass('invalid');
break;
case "number":
debugger;
var value = $(control).val().trim();
if (isNaN(value) || value.length == 0)
$(control).addClass('invalid').removeClass('valid');
else
$(control).addClass('valid').removeClass('invalid');
break;
}
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
.valid {
border: 2px solid green;
}
.invalid {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
Form 1
</h4>
<form id="myform1">
<label>Enter name</label>
<input type="text" data-validation="text" value="">
<br/>
<label>Enter Age</label>
<input type="text" data-validation="number" value="">
<br/>
</form>
<h4>
Form 2
</h4>
<form id="myform2">
<label>Enter name</label>
<input type="text" data-validation="text" value="">
<br/>
<label>Enter Age</label>
<input type="text" data-validation="number" value="">
<br/>
</form>
<button>
Click me to validate
</button>

JavaScript Onclick is not working in tag

HTML:
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="new User().register()">REGISTER</div>
</div>
</form>
Js File
var User = function() {
var self = this;
self.register = function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/
var regEight = /^8[0-9].*$/
if($("#empId").val() =='')
{
alert(Language.InvalidEmployeeId);
return false;
}
if(mobile =='')
{
alert(Language.EmptyMobileNumber);
return false;
}
}
};
if i write a coding for click event like below its working when i use OnClick event function is not calling
$("#regBtn").click(function ()
{
new User().register();
})
how to make the onclick work.. thanks in advance
In onclick call a function that does new User().register().
Do not write literal expression, wrap that expression in function and call that function.
try with this code
$("#regBtn").click(function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/;
var regEight = /^8[0-9].*$/;
if ($("#empId").val() == '') {
// alert(Language.InvalidEmployeeId);
console.log("InvalidEmployeeId");
return false;
}
if (mobile == '') {
//alert(Language.EmptyMobileNumber);
console.log("Empty mobile number");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="javascript:if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn">REGISTER</div>
</div>
</form>
</div>
Do something like this...
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="registerUser()">REGISTER</div>
</div>
</form>
</div>
Java script
function registerUser(){
new User().register();
}
In this case the function registerUser() is re-usable as you commented above "Actually i want to make use of the onclick event so that function can be reused if i give a id i cant reuse that in another page".

How to send localstorage with form

I have html form and localstorage
I need send data from localstorage and form on email
Now I am sending two letter :(
When user submit form I get two letter. First letter from form and second letter from localstorage
So, I want get one letter with localstorage and form
My form:
<form action="/send.php" id="form-cart-send" onsubmit="return sendCartdata();" method="post" enctype="multipart/form-data" required>
<div class="form_fields" data-count="3">
<div class="form_field" data-type="name" data-is-required="true">
<label class="field_title">Имя<i>*</i></label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="name" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="phone" data-is-required="1">
<label class="field_title">Телефон<i>*</i></label>
<div class="form_field_text">
<input type="tel" class="form_field_text_input form_phone" id="phone" name="phone" data-check="phone" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="email" data-is-required="0">
<label class="field_title">Ваш e-mail</label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="email" data-check="email" autocomplete="off" required>
</div>
</div>
</div>
<div class="form_fields_advanced"></div>
<div class="form_submit">
<a class="component-button form_field_submit filled squared" id="checkout" data-modal-id="cart_done">
<div class="btn-content">
<div class="form_submit_text">Заказать</div>
</div>
</a>
</div>
</form>
Script for localstorage:
<script>
function sendCartdata() {
var phone = document.getElementById("phone").value;
if (phone === '') {
alert("Заполните, пожалуйста, обязательные поля.");
return false;
} else {
setTimeout(function() {
var value = localStorage.getItem('cart');
jQuery.post("/cart-send.php", {
cart: value
}, function(data) {
}).fail(function() {
alert("Damn, something broke");
});
}, 100);
return false;
}
}
</script>

validation is not working on submit

I've created a HTML form, which takes some input values,like this:
<form name="form1" action="" method="POST" onSubmit="return validate()">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row"></div>
<div class="row>
<div class="col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center><button type="button" class="btn btn-lg btn-info">Submit</button></center>
</div>
</form>
And I kept some validation in javascript to validate the shop name, phone number and email id.
<script type="text/javascript">
function validate()
{
var shop_name=document.form1.shop_name.value;
var email=document.form1.email.value;
var phn=document.form1.phn1.value;
var phnre=/^[0-9]*$/;
var emailre = /^(([^<>()\[\]\\.,;:\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,}))$/;
if(shop_name==='')
{
alert("Shop Name is required.");
return false;
}
if(phn==="")
{
alert("Mobile number is required.");
return false;
}
if(!phnre.test(phn))
{
alert("Invalid mobile number.");
return false;
}
if(!emailre.test(email))
{
alert("Invalid Email Id.");
return false;
}
return true;
}
</script>
but,it is not working on submitting the form,
Can anyone help me on this issue.
Firstly, your html has a few errors. The main reason this is working is because your button has type="button" this should be type="submit".
All in all your html should be:
<form name="form1" action="" method="POST" onSubmit="return validate()">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row">
<div class=" col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center>
<button type="submit" class="btn btn-lg btn-info">Submit</button>
</center>
</div>
</form>
Also, <center> is not supported in HTML5.
Hope this helps!
Change button to type submit.
function validate()
{
var shop_name=document.form1.shop_name.value;// better use like var shop_name=document.getElementById("shop_name").value
var email=document.form1.email.value;
var phn=document.form1.phn1.value;
var phnre=/^[0-9]*$/;
var emailre = /^(([^<>()\[\]\\.,;:\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,}))$/;
if(shop_name==='')
{
alert("Shop Name is required.");
return false;
}
if(phn==="")
{
alert("Mobile number is required.");
return false;
}
if(!phnre.test(phn))
{
alert("Invalid mobile number.");
return false;
}
if(!emailre.test(email))
{
alert("Invalid Email Id.");
return false;
}
return true;
}
<form name="form1" action="" method="POST" onSubmit="return validate();">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row"></div>
<div class="row>
<div class="col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center><button type="submit" class="btn btn-lg btn-info">Submit</button></center>
</div>
</form>
You should read value in another way:
var shop_name=document.getElementById("shop_name").value;
var email=document.getElementById("email").value;
var phn=document.getElementById("phn1").value;
Additionally on 9 line you missed quoata after "row
button should be "submit":
<button type="submit" class="btn btn-lg btn-info">Submit</button>
Please use submit instead of button.
replace
<button type="button" class="btn btn-lg btn-info">Submit</button>
with
<input type="submit" class="btn btn-lg btn-info" value="submit">
just replace input type="button" to input type="submit"
<button type="submit" class="btn btn-lg btn-info">Submit</button>
try whole code it should be like this
<script type="text/javascript">
function validate(){
if(document.form1.shop_name.value == ""){
alert("Shop Name is required.");
return false;
}
var emailID=document.form1.email;
if ((emailID.value==null)||(emailID.value==""))
{
alert("Please Enter your Email ID")
emailID.focus()
return false;
}
var chk;
chk = echeck(emailID.value);
if(chk == "wrong")
{
emailID.value=""
emailID.focus()
return false;
}
function echeck(str)
{
var at="#"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
if (str.indexOf(at)==-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(at,(lat+1))!=-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(dot,(lat+2))==-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
if (str.indexOf(" ")!=-1)
{
alert("Invalid E-mail ID")
return "wrong";
}
return "correct";
}
if(document.form1.phn1.value == ""){
alert("Please provide phone ");
return false;
}
return true;
}
</script>
<form name="form1" action="abc.php" method="POST" onSubmit="return validate()">
<div class="row">
<div class="col-sm-3 form-group">
<input type="text" id="shop_name" name="shop_name" placeholder="Shop Name" class="form-control">
</div>
</div>
<div class="row"></div>
<div class="row>
<div class="col-sm-3 form-group">
<input type="text" id="phn1" name="phn1" placeholder="Phone No.(Primary)" class="form-control">
</div>
<div class="col-sm-3 form-group">
<input type="text" id="email" name="email" placeholder="E-Mail" class="form-control">
</div>
<center><button type="submit" class="btn btn-lg btn-info">Submit</button></center>
</div>
</form>
Thank you...
I don't know how you reference this script to your HTML but i expect you are putting it in an unknown place regarding the HTML itself , here are Three working ways:-
Common thing in the three ways:
<button type="submit" class="btn btn-lg btn-info">
instead of
<button type="button" class="btn btn-lg btn-info">
as in the Fiddles
put the validate function definition in the window object:
window.validate = function(){.......};
Fiddle Here
Embed the script into the HTML itself:
<form></form>
<script>your validate function definition</script>
Fiddle Here
Put the script in an external file and reference it in the HTML file (Recommended)

Allow only x number of form fields to be filled in

I have a very noob question, I have a form with input fields. The form has 10 fields, and the user needs to enter from 1-3 (one being most preferred, to 3 being last choice). After 3 have been filled, I want to either disable all other fields, or just disallow any further input and give an error.
I've got the counting up working, but i can't restrict or pop an error.
here's the code,
jQuery(document).ready(function($){
$("#choices").on('keyup change', function() {
var maxAllowed = 3;
var number = 0;
$(this).find('input, textarea').each(function () {
//if (number < maxAllowed && this.value !== '')
if (this.value !== '')
{
$('.input_count').val(number++);
}
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<form method="post" id="userForm" role="form">
<h3>Selection form</h3>
<p>Fill in your choices from 1-3 (please select only three).</p>
<div id="choices">
<div class="form-group">
<label for="Recreational fishing">Recreational fishing</label>
<input type="text" value="" size="3" name="form[Recreational fishing]" id="Recreational fishing" class="form-control" />
</div>
<div class="form-group">
<label for="Recreational boating">Recreational boating</label>
<input type="text" value="" size="3" name="form[Recreational boating]" id="Recreational boating" class="form-control" />
</div>
<div class="form-group">
<label for="Sightseeing tourist">Sightseeing tourist</label>
<input type="text" value="" size="3" name="form[Sightseeing tourist]" id="Sightseeing tourist" class="form-control" />
</div>
<div class="form-group">
<label for="Exercise">Exercise</label>
<input type="text" value="" size="3" name="form[Exercise]" id="Exercise" class="form-control" />
</div>
<div class="form-group">
<label for="Picnics BBQ">Picnics/BBQ</label>
<input type="text" value="" size="3" name="form[Picnics BBQ]" id="Picnics BBQ" class="form-control" />
</div>
<div class="form-group">
<label for="Sunsets and socialising">Sunsets and socialising</label>
<input type="text" value="" size="3" name="form[Sunsets and socialising]" id="Sunsets and socialising" class="form-control" />
</div>
<div class="form-group">
<label for="Bird watching">Bird watching</label>
<input type="text" value="" size="3" name="form[Bird watching]" id="Bird watching" class="form-control" />
</div>
<div class="alert alert-info">
<div class="form-group">
<label for="counter">Counter:</label>
<input class="input_count form-control" type="text" id="counter" value="">
</div>
</div>
</div>
<input type="submit" value="Submit" name="form[Submit]" id="Submit" class="btn btn-primary btn-block">
</form>
</div>
</div>
.... or here's a fiddle.
http://jsfiddle.net/Flocktome/wmdnnm4j/
any thoughts would be really appreciated. Thanks in advance.
jQuery(document).ready(function($){
$("#choices").on('keyup change', function() {
var maxAllowed = 4;
var number_done = 0;
$(this).find('input, textarea').removeAttr('disabled');
$(this).find('input, textarea').each(function () {
//if (number < maxAllowed && this.value !== '')
if (this.value !== '')
{
$('.input_count').val(++number_done);
}
});
if( number_done >= maxAllowed){
$(this).find('input,textarea').filter(function(){
if($(this).val()== '')
return true;
return false;
}).attr('disabled', 'disabled');
}
});
});
Here the max allowed is set to 4.because of you counter field.Which should be ingnored i think for the test purpose.Once this field is removed the maxallwoed can be set as 3
Try this code. I have found number of fields filled using filter function and disabled other fields using each, when the maximum number of fields allowed are filled. JSFiddle
jQuery(document).ready(function($){
$("#choices").on('keyup', function() {
var maxAllowed = 3;
var els = $(this).find('input, textarea');
var elsFilled = els.filter(function(i,el){ return el.value!="" }).length;
if(elsFilled==maxAllowed)
els.each(function(i,el){ if(el.value=="") el.disabled = true; });
else
els.each(function(i,el){ if(el.value=="") el.disabled = false; });
});
});

Categories

Resources