Reseting the form when usering the jquery validations plugin - javascript

I have a simple form like below that I have added the jQuery validations plugin onto (http://docs.jquery.com/Plugins/Validation). I have this form in a modal popup window so if there are errors and the user closes the window when they open it again the form still has the errors. In my popup close callback I tried calling resetForm() but it says the method doesn't exist.
Form HTML:
<form class="validations" id="commentForm" method="get" action="">
<p>
<label for="name">Name</label>
<em>*</em><input id="name" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="email">E-Mail</label>
<em>*</em><input id="email" name="email" size="25" class="required email" />
</p>
</form>
Popup Close Callback:
function(){
$(this).find('form.validations').resetForm();
}
Thanks in advance for the help.

resetForm is part of the object returned by the validate method, not the form. Example:
var validate = $('#commentForm').validate({ ... });
// Later...
validate.resetForm();
// Or if variable scope is in the way...
$('#commentForm').data('validator').resetForm();
The validation plugin stores a reference to the validation object in the form's data store.

If it really is a short form with just a few elements, you could simply reset them by hand when the close button on the modal window is clicked, like so:
$("input[name='formelementName']").val("");

Related

HTML5 email validation avoiding js call

I have the following code:
<form>
<input type="email" id="login_email" required>
<input type="submit" value="Sign in" ng-click="signIn()">
</form>
The problem with above code is that signIn() method gets called even if there is an email validation error from HTML5 side. In general how to ensure that signIn() method gets called only when all the input validation of the form are successful?
Use $pristine to find out if the form is empty, and $invalid to find out if the form is populated but has invalid values (maybe an incorrect email, for example).
<form name="myForm">
<input type="email" name="email" ng-model="email" required />
<button ng-click="signIn()" ng-disabled="myForm.$invalid || myForm.$pristine">Save</button>
</form>
So now your submit button will be disabled (not clickable) until your form is valid.
EDIT
In order to validate only with HTML5 validation, add a name attribute to your form and you can access the validity of it during submission:
<form name="myForm">...</form>
$scope.signIn = function(){
if ($scope.myForm.$valid){
// do sign in logic here
}
}
Maybe even inline the logic on your submit button (if it works):
<input type="submit" value="Sign in" ng-click="myForm.$valid && signIn()">
So signIn would only be called if the first part was true.
EDIT 2
Based on the information found on the AngularJS docs here, can you try the following as well?:
<form name="myForm">
<input type="email" name="email" ng-model="email" required />
<button ng-click="signIn()" ng-disabled="signIn()">Save</button>
</form>
$scope.signIn = function () {
if ($scope.myForm.email.$error.required) {
// ...
}
};
We are now following the $scope.myForm.email.$error.required syntax approach.
Try logging $scope.myForm or $scope.myForm.email and see what you get as you modify the value.

IE, Edge replaces storage text with 'null'

So I have this little contact form on my site, and it's suppose to input some text into an empty p tag telling the client that's it's been submitted. It works fine, it does what it should, but in IE/Edge it ignores everything and inputs the word null into the p tags.
You'll have to forgive me, I'm still new to javascript, but I couldn't find anything anywhere to address this bug. Any help would be greatly appreciated.
<form id="contact-form" method="post" action="#" onsubmit="return setReturn()">
<input type="hidden" value="someone#email.com" name="emailTo">
<fieldset>
<p id="thanks"></p>
<legend>Send me a message</legend>
<div class="contact-info">
<input placeholder="Name*" type="text" name="name" required>
<input placeholder="Email*" type="Email" name="email" required>
</div>
<textarea placeholder="Message*" name="message" required></textarea>
<input type="submit" value="Submit" name="submitContact" class="button">
</fieldset>
</form>
<script>
function setReturn(){
localStorage.setItem("thanks", "Your request was sent successfully!");
}
document.getElementById("thanks").innerHTML = localStorage.getItem("thanks");
localStorage.clear();
</script>
Your issue is that when the innerHTML of the "thanks" element is set, the string in localStorage is unset.
Then when the form is submitted, the localStorage item is set, but the "thanks" element's innerHTML isn't set (it was set to undefined before).
In order to make sure the "thanks" element is updated when the form is submitted, you need to include the lines that set it in the function that fires when the form is submitted.
function setReturn(){
localStorage.setItem("thanks", "Your request was sent successfully!");
document.getElementById("thanks").innerHTML = localStorage.getItem("thanks");
localStorage.clear();
}
On form submit you are calling setReturn function , but when this snippet document.getElementById("thanks").innerHTML = localStorage.getItem("thanks"); is parsed localStorage does not have this key. So you have to first set this local storage before use it's value as innerHTML like in the previous answer.
Also it is odd that you are using localStorge and even you are clearing it, when this thing can be acheived by this snippet
HTML
<form id="contact-form" method="post" action="#" onsubmit="return setReturn()">
<input type="hidden" value="someone#email.com" name="emailTo">
<fieldset>
<p id="thanks"></p>
<legend>Send me a message</legend>
<div class="contact-info">
<input placeholder="Name*" type="text" name="name" required>
<input placeholder="Email*" type="Email" name="email" required>
</div>
<textarea placeholder="Message*" name="message" required></textarea>
<input type="submit" value="Submit" name="submitContact" class="button">
</fieldset>
</form>
JS
function setReturn(){
event.preventDefault()
document.getElementById("thanks").innerHTML = "Your request was sent successfully!";
}
NOTE: I used event.preventDefault just for demo but in real application you dont need to use it as it will prevent default behaviour or the submit button.
Here is a WORKING COPY
Also you can use an IIF to set up this localStorage.This function will be executed as soon as it parsed and will set up the key thanks to it.
(function(){
localStorage.setItem("thanks", "Your request was sent successfully!");
}())
Then onsubmit you can use your function without making any change
function setReturn(){
event.preventDefault();
document.getElementById("thanks").innerHTML = localStorage.getItem("thanks");
localStorage.clear();
}
WORKING COPY WITH IIF
Hope this is helpful

Trigger parsley validation without submit form?

Given this code, it never works and always returns true whatsoever ?
<form id="my-form" data-validate="parsley">
<p>
<label for="username">Username * :</label>
<input type="text" id="username" name="username" data-required="true" >
</p>
<p>
<label for="email">Email Address * :</label>
<input type="text" id="email" name="email" data-required="true" >
</p>
<br/>
<!-- Validate all the form fields by clicking this button -->
<a class="btn btn-danger" id="validate" >Validate All</a>
</form>
<script>
var $form = $('#my-form');
$('#validate').click (function () {
if ( $form.parsley('validate') )
console.log ( 'valid' ); <-- always goes here
else
console.log ('invalid');
});
</script>
So my question is if there is a way to trigger parsley validation without adding a submit button ?
$form.parsley('validate') is 1.x API. It was deprecated in 2.x versions you might use.
Try $form.parsley().validate() instead.
Best
I've been searching high and low to try and make the form validation work with a non-form tag.
I guess my biggest gripe with the framework is that it doesn't work out-of-the-box with non-form elements.
I would be ok using a form element if it didn't scroll to the top of the page every time it tries to validate. Because this behavior is inherent in how form works, there is only this hack to fix it.
Just as a side note, using data-parsley-validate attribute on the div tag also works. You can also initialise the form as normal (meaning you can subscribe to the validation).
example html:
<div id="signupForm" data-parsley-validate>
... put form inputs here ...
<button id="signupBtn">Sign me up</button>
</div>
Just make sure to put js in:
var $selector = $('#signupForm'),
form = $selector.parsley();
form.subscribe('parsley:form:success', function (e) {
...
});
$selector.find('button').click(function () {
form.validate();
});
if you put type="button" on the button, it won't refresh and scroll to top of page when clicked.

Form html, type submit

I'm building one cordova application that uses one tag form with a submit button, the problem is that this is one mobile application, so when a click on my text input, write something and than click on confirm button of my mobile keyboard, my problem happens. Because when I click on this button, I want to move to the next input, but my aplication execute my submit method. What I have to do to my application pass to the next input and if, and only if this is my last input, so verify if all input are filled.
This is my html code:
<form id="form">
<label for="idNome"> Nome: </label> <input name="nome" id="idNome"
placeholder="Seu Nome" required autofocus autocomplete="on"><br>
<label for="idCpf"> CPF:</label> <input type="tel"
autocomplete="on" name="cpf" id="idCpf" placeholder="Seu CPF"
required> <img style="display: none;" id="idValidadeCPF"
src=""><br>
<label for="idEndereco"> Endereço:</label>
<textarea id="idEndereco" rows="1" cols="30"></textarea><br>
<label for="idMensagem"> Mensagem: </label><br>
<textarea cols=30 id="idMensagem" rows="10" name="mensagem"
maxlength="500" wrap="hard"
placeholder="Informe datalhes sobre o seu problema." required></textarea><br>
<input type="submit" value="Enviar" onclick="submitForm()" />
And this is my submitForm method
function submitForm(){
document.getElementById('form').onsubmit= function(e){
e.preventDefault();
alert("Todos os campos devem ser preenchidos");
}
}
Your submitForm() function isn't actually doing the logic it contains, it's just setting a handler. It's basically just doing this:
document.getElementById('form').onsubmit = someFunction;
And that's all. Whatever's inside of someFunction isn't going to be executed until the next time the handler is invoked. But it sounds like you want it invoked right away.
Instead of assigning the submit handler when you submit the form, assign it right away when the page loads. Something like this:
<form id="form">
... your form
<input type="submit" value="Enviar" />
</form>
<script type="text/javascript">
document.getElementById('form').onsubmit = function(e){
e.preventDefault();
alert("Todos os campos devem ser preenchidos");
}
</script>
Notice that I've removed the submitForm function entirely, as well as removed it from the input which was calling it. It isn't really needed in this case. That input is of type submit so it will submit the form by default. But when the page loads this JavaScript adds your anonymous function as the handler for the form's submit event, so this function will run when the input submits the form.
It's worth noting that this will prevent the form from ever actually being submitted, though. You're only submit handler prevents the default action (submitting the form) and shows an alert(). It's not clear to me why you're doing that or what you're trying to accomplish.

jquery .load not applying ready function

On document ready I run this code:
jQuery(document).ready(function(){
jQuery('#button').click(function() {
jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt");
return false;
});
});
Then if I create a form like
<div id="contact_form">
<form name="contact" method="post" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<br />
<input type="submit" name="submit" class="button" id="button" value="Send" />
</fieldset>
</form>
</div>
Everything works fine. However, if I mimic the behavior I want in the actual app (the form is loaded dynamically after document.ready has already been executed. The jquery #button action does not get called and the form acts as if there is no javascript and just runs a post.
jQuery('#contact_form').load("/dynamicform.php");
Is there something that has to be done to .load() in order for the ready function to be applied to it?
Use .live() like this:
jQuery(document).ready(function(){
jQuery('#button').live('click', function() {
jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt");
return false;
});
});
Your element isn't there when you're adding the handler. You need to listen for the click in all cases...this is what .live() is for, is listens up at the DOM root for the click, whereas .click() isn't getting attached to anything because there are no elements that match the selector when you're calling it. live() listens for clicks on matching elements later.
The .ready event is called when the DOM is ready to be used, and therefore it won't be called when you dynamically load and insert something into an already existing DOM.
Also I believe that it is common practice to have a custom form submit work by attaching an event handler to the form, not the submit button. As it will also handle cases where the user submits the form in another way than clicking on the submit button. Example:
jQuery("#contact_form form").submit(function (event) {
event.preventDefault();
// Do your stuff...
})
(event.preventDefault(): http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29)
ready() is not applied after load(). Look in the doc for load(), you can probably specify a callback to be executed when the loading is done, in which you'll be able to reassign the click handler.

Categories

Resources