need help with nested jquery function - javascript

Please find my code below. My problem is that I the inner jQuery.get() doesn't get executed. Could some one help me out with this?
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert(url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
});
});
My html form looks like
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
I'd really appreciate any pointers.
Thanks!

The problem you are experiencing is that you dont do anything to stop your form from being submitted, thus it submits the form before it gets a chance to get the data from the worldweatheronline.com.
Change your click handler to be like this:
$(".button").click(function(event) {
event.preventDefault();
Here is my completed sample code that works the way you want it to:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function() {
$('.error').hide();
$(".button").click(function(event) {
event.preventDefault();
// validate and process form here
$('.error').hide();
var zipCode = $("input#name").val();
if (zipCode == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var key = 'ac9c073a8e025308101307';
var noOfDays = 5;
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=' + zipCode + '&format=json&num_of_days=' + noOfDays + '&key=' + key;
alert('first'+url);
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ){
return false;
}
});
}, 'jsonp');
});
});
</script>
</head>
<body>
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
</body>
</html>

Turn on Fiddler or Firebug and watch the HTTP call go out. You'll see the HTTP error message there. Also, turn on your console in Chrome or Firefox to see a potential JavaScript error.

Part of the problem could be the extra set of parentheses after your .get() function call. You have:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
}); }, 'jsonp')();
It should be:
jQuery.get(url, function(test) {
alert(url);
$.each(test.data.weather, function(i, item){
$("body").append("<p>Date: "+item.date+"</p>");
if ( i == 3 ) return false;
});
}, 'jsonp');

Im going to go out on a limb and guess that (based on the url 'http://www.worldweatheronline.com/feed/weather.ashx?q=' ) that you are attempting to perform an AJAX request to an external site. This violates Same Domain Policy and will fail silently.

Related

form data not saving to chrome local storage

I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?
function submit() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var feedback = document.getElementById("feedback").value;
localStorage.setItem("name", name);
localStorage.setItem("email", email);
localStorage.setItem("feedback", feedback);
return true;
}
function init() {
var name = localStorage.getItem("name");
var email = localStorage.getItem("email");
var feedback = localStorage.getItem("feedback");
document.write("passed value = " + name);
document.write("passed value = " + email);
document.write("passed value = " + feedback);
}
HTML
<form action="form.html" method="get" onsubmit="submit()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
<script src="form.js" type="text/javascript"></script>
You have created a very pesky and hard to find bug there!
No it's not the event doubling in <input type="submit" value="Submit" onclick="submit()"> <input type="submit" value="Submit" onclick="submit()">
even though it can be considered a bad practice
Spot it?
it's submit()!
Try this and submit the form
<form action="form.html" method="get" onsubmit="alert(getAttributeNames()); submit()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
Surprised eh? You haven't defined getAttributeNames() anywhere yet it works! How is that you ask??
This is because it is one of many inbuilt DOM method that every html element inherits. Now you get the idea what happened when you used onsubmit="submit()" It didn't call the submit() function you wrote instead it called the inbuilt submit (form's native) method that submits it to server and once it submits obviously it won't do any localstorage business
The fix is simple just use names that won't collide with the built-in(s). Or you can also use addEventListener() because in that you can tell browser explicitly "no, use this function that I've written not the inbuilt one, please"
Here is a fixed version I just changed the name of your function
<form action="form.html" method="get" onsubmit="submit2()">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit" onclick="submit()">
</fieldset>
</form>
</section>
<script>
function submit2() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var feedback = document.getElementById("feedback").value;
localStorage.setItem("name", name);
localStorage.setItem("email", email);
localStorage.setItem("feedback", feedback);
return true;
}
function init() {
var name = localStorage.getItem("name");
var email = localStorage.getItem("email");
var feedback = localStorage.getItem("feedback");
document.write("passed value = " + name);
document.write("passed value = " + email);
document.write("passed value = " + feedback);
}
</script>
The thing is that localstorage cannot store objects, but you could always store json formatted objects as a string and parse it later whenever you want to you the data!
And also the form submission should be stopped before it refreshes the page! just by adding the return false on the onsubmit event.
<form action="form.html" method="get" id="myForm">
<fieldset style="width: 80%; margin: auto;">
<legend>Feedback:</legend>
<label for="name">Name:</label><br />
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br />
<input type="email" id="email" name="email"><br><br>
<label for="feedback">Feedback:</label><br />
<textarea id="feedback" name="feedback"></textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<script>
var myForm = document.querySelector("form#myForm");
myForm.onsubmit = function(){
const data = {};
const dataToFetch = this.querySelectorAll("input, textarea, button, select");
for(let element of dataToFetch){
if( element && element.tagName && element.name )
data[element.name] = element.value;
}
let jsonData = JSON.stringify( data );
localStorage.setItem("formData", jsonData);
alert("Data stored to localStorage itemName:'formData'");
return false;
}
</script>
I use a function for this so I can call it at any time.
// add to local storage
const addToLocalStorageObject = function (name, key, value) {
// Get the existing data
let existing = localStorage.getItem(name);
// If no existing data, create an object
// Otherwise, convert the localStorage string to an object
existing = existing ? JSON.parse(existing) : {};
// Add new data to localStorage object
existing[key] = value;
// Save back to localStorage via stringify
localStorage.setItem(name, JSON.stringify(existing));
};
// retrieve from local storage
const retrieveFromLocalStorageObject = function (name) {
let data = localStorage.getItem(name);
// read the localStorage item and convert it to an object
return data ? JSON.parse(data) : null;
};
Then call addToLocalStorageObject('name', name);
And retrieveFromLocalStorageObject('name');
NB: I did not write the above functions but I have found them extremely useful.

How would you make an iframe if the value is true in javascript?

I have a javascript login page (I know it's not secure!) How would I make the website create an iframe if the value is correct?
I have already tried window.location.assign but doesn't work! When you add any code it deletes the values in the inputs and puts the values you inserted in the url?
<div class="box" id="loginbox">
<h2>Login</h2>
<form id="form1" name="form1" action="" onsubmit="return checkDetails();">
<div class="inputBox">
<input type="text" name="txtusername" id="txtusername" class="info" required />
<label>Username</label>
</div>
<div class="inputBox">
<input type="password" name="txtpassword" id="txtpassword" class="info" required/>
<label>Password</label>
</div>
<input type="submit" name="Login" id="Login" value="Login"/>
</form>
</div>
<script>var remainingAttempts = 3;
function checkDetails() {
var name = form1.txtusername.value;
var password = form1.txtpassword.value;
console.log('name', name);
console.log('password', password);
var validUsername = validateUsername(name);
var validPassword = validatePassword(password);
if (validUsername && validPassword) {
alert('Login successful');
document.getElementById("loginbox").remove();
var next = document.createElement("IFRAME");
next.src = 'https://codepen.io';
next.classList.add("codepen");
document.body.appendChild(next);
} else {
form1.txtusername.value = '';
form1.txtpassword.value = '';
remainingAttempts--;
var msg = '';
if (validPassword) {
msg += 'Username incorrect: ';
} else if (validUsername) {
msg += 'Password incorrect: ';
} else {
msg += 'Both username and password are incorrect: ';
}
msg += remainingAttempts + ' attempts left.';
alert(msg);
if (remainingAttempts <= 0) {
alert('Closing window...');
window.close();
}
}
return validUsername && validPassword;
}
function validateUsername(username) {
return username == 'GG';
}
function validatePassword(password) {
return password == '123';
}</script>
I want the page to create the iframe and remove the login box.
The problem is that you are triggering a form submission when your login button is clicked, which triggers a page load.
<input type="submit" name="Login" id="Login" value="Login"/>
The submit input type type triggers this behaviour. To avoid this, bind to the submit event in the javascript rather than the HTML and use preventDefault() to prevent the page from reloading.
var ele = document.getElementById("loginbox");
if(ele.addEventListener){
ele.addEventListener("submit", checkDetails, false); //Modern browsers
} else if(ele.attachEvent){
ele.attachEvent('onsubmit', checkDetails); //Old IE
}
function checkDetails(e) {
e.preventDefault();
// rest of your code
Code taken from this answer, which you should read for more information about form submission events and how to handle them.

jQuery removing errors generated on validation and stop repeating

still a little new to JS and a little stuck with some validation script i am writing. The errors repeat so need to remove if they exist and also then remove if they are valid.. any ideas?
function validateEmail($email) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test( $email );
}
function inputReset(element) {
if (element.hasClass('error')) {
element.removeClass("error");
element.siblings('.error-message').remove();
}
}
// Validation
$('.validate-form').on('click', function(event) {
event.preventDefault();
var valid = true,
message = '';
$('form.validate input').each(function() {
var $this = $(this);
inputReset($this);
if($this.prop('required')){
// check for errors, if found lets get the messages for output
if(!$this.val()) {
$(this).addClass("error");
var inputName = $this.attr('name');
message = $this.data('error-message');
}
// validate the email input
if($(this).hasClass('validate-email')) {
var emailAddress = $this.val();
if(!validateEmail(emailAddress)) {
$this.addClass("error");
valid = false;
}
}
$('.error-message[data-input-name="' + inputName + '"]').remove();
// if not validated lets display the errors
if(!valid) {
//alert(message);
$this.after('<div class="error-message" data-input-name="' + inputName + '">' + message + '</div>');
}
}
});
if(valid) {
$(".validate-form").submit();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="col-right form-vertical">
<form id="email_signup" class="klaviyo_bare_embed_twtw2v simpsons-form validate" action="//manage.kmail-lists.com/subscriptions/subscribe" data-ajax-submit="//manage.kmail-lists.com/ajax/subscriptions/subscribe" method="GET" target="_blank" novalidate>
<input type="hidden" name="g" value="twtw2v">
<input type="hidden" name="$fields" value="first_name,last_name" />
<div class="klaviyo_messages">
<div class="success_message">
<p class="thank_you" style="display:none;">Thank's for signing up</p>
</div>
</div>
<div class="klaviyo_field_group">
<label for="k_id_first_name" class="kl_label">First Name:</label>
<input type="text" value="" name="first_name" id="k_id_first_name" data-error-message="Error first name" placeholder="First Name" required />
</div>
<div class="klaviyo_field_group">
<label for="k_id_last_name" class="kl_label">Last Name:</label>
<input type="text" value="" name="last_name" id="k_id_last_name" data-error-message="Error last name" placeholder="Last Name" required />
</div>
<div class="klaviyo_field_group">
<label for="k_id_email" class="kl_label">E-mail:</label>
<input type="email" value="" name="email" id="k_id_email" class="validate-email" data-error-message="Error email" placeholder="E-mail" required />
</div>
<div class="klaviyo_form_actions">
<button type="submit" class="btn klaviyo_submit_button validate-form">Sign Up</button>
</div>
</form>
</div>
First of all I would remove the else valid = true; parts of the code otherwise the form will submit if the last field checked is valid.
You probably just need a function to reset your inputs. Place this function outside of your click event then add inputReset($this); at the top of your each function
function inputReset(element) {
if (element.hasClass('error')) {
element.removeClass("error");
element.siblings('.error-message').remove();
}
}
Make sense? Hope it helps.
You may add the following lines at the start of your function:
$('.validate-form').on('click', function(event) {
event.preventDefault();
var valid = true,
message = '';
// Add this
$(".error").removeClass(".error");
$(".error-message").remove();
...
This will remove all the changes done in the DOM during the last execution of this method.
The easiest way for me would be to add a data attribute to the error message, say, data-input-name and set it to the inputName variable, so each time you validate a field, you would first remove the error message and then add it again if the validation still fails like this:
(just the relevant part)
//removing error message, if it exists
$('.error-message[data-input-name="' + inputName + '"]').remove();
// if not validated lets display the errors
if(!valid) {
$this.after('<div class="error-message" data-input-name="' + inputName + '">' + message + '</div>');
};
Hope this helps.
As of my understanding, you missing definition of validateEmail() function. The self-explanation of exception shows it Uncaught ReferenceError: validateEmail is not defined.

Simple form skips validation/sending and goings straight to ajax message

I have been following this tutorial to validate a form on a HTML5 template I am working on modifying. Here is the link: http://englishpearls.net/dev/contact.html
As you see, the form goes straight to the ajax message and skips everything else. What am I doing wrong?
HTML
<div id="contact_form">
<form method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" value="Name" name="userName" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" value="Email" name="userEmail" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" value="Phone" name="userPhone" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Phone';}">
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" value="Subject" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Subject';}" style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" value="Message:" name="userMsg" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
</div>
Jquery EDIT: Updated Script
<script type="text/javascript">
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
var subject = $("input#subject").val();
if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
return false;
}
var message = $("input#message").val();
if (message == "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "contact-post.html",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
return false;
});
});
</script>
Without the validation script, the email sends fine. Thanks!
The way your script is setup right now, the AJAX call will fire immediately, regardless of any input. It needs to be inside of this:
$(".button").click(function () {
}
function, which should have an if statement that will only allow the AJAX to fire if the validation of the form is successful.
Updated:
<div id="contact_form">
<form id="contact-post" method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" placeholder="Name" name="userName" >
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" placeholder="Email" name="userEmail" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" placeholder="Phone" name="userPhone" >
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" placeholder="Subject"style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" placeholder="Message:" name="userMsg">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
JS:
<script type = "text/javascript">
$(function () {
$('.error').hide();
$("#contact-post").submit(function (event) {
alert("submitted");
event.preventDefault();
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var subject = $("input#subject").val();
var message = $("#message").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
} else if (email == "") {
$("label#email_error").show();
$("input#email").focus();
} else if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
} else if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
} else if (message == "") {
$("label#message_error").show();
$("input#message").focus();
} else {
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "app/contact.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
}
});
});
< /script>
That will work. Also I changed all of the value attributes in your HTML to placeholder attributes so they function as expected and don't get in the way of the validation.
Alternatively, since you're already using jQuery, you could check out jQuery Validate, a jQuery plugin that would make this much simpler
UPDATE:
I removed all of the onfocus/onblur attributes from your HTML and it works now. The JS in the onblur tags was filling the form with values, so it was able to pass validation. Look at this JSFIDDLE for a working verison
UPDATE 2:
The var message = $("input#message").val() should be var message = $("#message").val().
The first one is looking for an input with the id of "message", where as you have a textarea with that id. Changing this line will correct the blank message you're getting. (see the updated JS above)
Regarding this question,
I have noticed that in the first link I have the $(".button").submit(function (event) whereas in your config, in the same spot you have $("#contact-post").submit(function (event)
I have the validation being performed when a form with the id of "contact-post" gets submitted, instead of when the button gets submitted (which isn't possible). The reason the page with this JS/form is submitting is that the JS to validate never gets triggered.
It's possible (although unlikely) to submit the form without clicking that button, so we don't want the validation to be skipped on the off-chance that happens.
You could try adding "return true;" to the .click
$(".button").click(function () {
//...
//validation code
//...
//return true if passes validation
return true;
}
Have you thought about combining things like this:
$('yourForm').on('submit', function(event){
if ( formIsvalid() ) {
$.ajax({
...
});
} else {
// Do something else maybe?
}
event.preventDefault();
});
// Form validation.
function formIsvalid() {
... form validation here...
return true;
}

Validate Dynamically Added Input fields

I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>

Categories