I'm having issues trying to get my form to reset without the required fields error messages appearing. On submit, if the form is valid I call the following function.
$scope.reset = function() {
$scope.createUser.$submitted = false;
$scope.createUser.$dirty = false;
$scope.createUser.$pristine = true;
$scope.user = angular.copy($scope.master);
$scope.createUser.$setPristine(true);
}
This resets the form but prompts the following messages.
Ive been looking for a way of reseting the form to prestine without any luck, im not sure if its because of the way I'm adding the has-error class.
ng-class="{'has-error': (createUser.name.$dirty || submitted) && createUser.name.$error.required}"
I would be grateful for any help with this, I have a plunker to go with it.
Im not sure if this is what you wanted but does this plunker solve your issue?
first of all like Mathew stated you had an issue with the submitted variable, $submitted is not defined anywhere you wanted to use submitted.
and you want to check your form and only if correct then set it as false.
also I would do validations like so
ng-class="{'has-error': (createUser.name.$dirty &&
createUser.name.$invalid && submitted)}"
but you dont have to, for the controller:
$scope.reset = function() {
$scope.submitted = true;
if($scope.createUser.$valid){
$scope.submitted = false;
$scope.createUser.$dirty = false;
$scope.createUser.$pristine = true;
$scope.user = angular.copy($scope.master);
$scope.createUser.$setPristine(true);
}
}
It doesn't look like you're resetting your submitted variable that you're using in has-error. You're resetting $submitted
Edit your reset function:
$scope.reset = function() {
$scope.createUser.$submitted = false;
}
you need nothing else.. good luck :)
Related
Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.
I wrote below code
var checkLightOn = $localstorage.getObject('LightOn');
if(checkLightOn == true){
$scope.LightOn = true;
}else{
$scope.LightOn = false;
}
$scope.checked = function(){
if($scope.LightOn){
$localstorage.set('LightOn','');
}else{
$localstorage.set('LightOn',true);
}
}
and expect my toggle with work fine with localstorage. But the second click doesn't change the localstorage's value, It work only I do the refresh. I have no idea why. I put an alert() within the ng-change, it trigger every time I clicked on it.
The view
<input ng-model="LightOn " ng-change="checked()" type="checkbox">
You also need to change the LightOn scope variable not only localStorage, try:
$scope.checked = function(){
if($scope.LightOn){
$localstorage.set('LightOn','');
}else{
$localstorage.set('LightOn',true);
}
$scope.LightOn = !$scope.LightOn;
}
may be something goes wrong with $localstorage I guess. I have an example here (bases on you code) and it works well.
No need to reassign $scope.LightOn
Check this Link:
https://jsfiddle.net/0qwtbppf/1/
I'm trying to validate a form before it is submitted. I've tried a couple of methods but I cant get the form to submit after preventDefault. This is the code I have at the moment:
$('#formquote').submit(function(e){
e.preventDefault();
console.log('here');
validating = true;
var tval = valText('input[name=contactname]');
var pval = valPhone('input[name=telephone]');
var eval = valEmail('input[name=email]');
console.log(tval);
console.log(pval);
console.log(eval);
if(tval && pval && eval){
$("#formquote").unbind('submit');
$("#formquote").submit();
}
});
The console logs you can see output as expected ('here', true, true, true respectively)
At the moment the form submits on the second time you press the button. I've also tried the following suggestions to no avail:
-> $("#formquote").unbind('submit').submit(); //same result
-> $("#formquote").submit(); //by itself, infinite loop
-> $("#formquote")[0].submit(); //non function error
-> $('#formquote').unbind('submit', preventDefault); //'preventDefault' not defined
Any help would be appreciated
Instead of always preventing the form from submitting, doing your validation and submitting again if it passes, why don't you just prevent the submission when the validation fails? Something like this:
$('#formquote').submit(function (e) {
validating = true;
var tval = valText('input[name=contactname]');
var pval = valPhone('input[name=telephone]');
var eval = valEmail('input[name=email]');
if (!(tval && pval && eval)) {
e.preventDefault();
}
});
I guess the accepted answer is the best way of doing this, but if, for some reason, you need to use preventDefault() first and then submit the form, this works for me:
$('#formquote').on('submit', function (e) {
e.preventDefault();
// Do validation stuff..
// Then submit the form
$(this).submit();
}
Im currently trying to do a form that requires the user to enter valid information.
For instance Here's a classic form: jsfiddle
I want the user to put name and address. But I want the button to be unclickable until the user inputs his Name and his Email(in a correct form).
Is there any property that lets me access if a button is unclickable? Something like:
function validateButtonSubmit {
if (validateEmail(email)) {
if (validateName(name)) {
document.getElementById("submitButton").clickable = true;
}
}
}
Whats the best way to accomplish this, am I going in the right direction?
You could probably shorten this up without the nesting if you wanted:
function validateButtonSubmit() {
var btnSubmit = document.getElementById("submitButton");
btnSubmit.disabled = !(validateEmail(email) && validateName(name));
}
Use disabled:
document.getElementById("submitButton").disabled = true;
You could call removeAttribute() on the element and then call setAttribute after you've validated the form:
var button = document.getElementById('submitButton');
button.removeAttribute('click');
// validation stuff
button.setAttribute('click', submitForm());
I am still confused about this. Started learning JQuery about a week now and this is what I have:
var IsValidUserName = false;
$(document).ready(function () {
$('#txtUserName').blur(function () {
if ($('#txtUserName').val().match(isNumberLetter) &&
($('#txtUserName').val().length >= 8)) {
$('#userNameError').removeClass("error").addClass("default");
$('#txtUserName').removeClass("alert");
$('#txtUserName + label').removeAttr("id", "lblUserName");
IsValidUserName = true;
}
else {
$('#userNameError').removeClass("default").addClass("error");
$('#txtUserName').addClass("alert");
$('#txtUserName + label').attr("id", "lblUserName");
}
});
});
Lets say I have another function like above, lets say FirstName:
How do I call this on the submit event? The code works as I need it to when the user leaves a field. Not sure how I can also call this code and also use the variable above to prevent submit if the data entered is invalid.
I need to call the validation above if the user clicks the submit button and stop the submission if the IsValidUserName variable is false.
Somethings just need a little push.
Thanks my friends.
Guy
You could always extract it into a function instead of an anonymous function and pass the reference to the object you want to check. This would give you the added benefit of reusing it for other elements.
function validate(ele) {
var valid;
if (ele.val().match(isNumberLetter)) && (ele.val().length >= 8)) {
valid = true;
// update user here.
} else {
valid = false;
// update user here.
}
return valid;
}
$(function(){
$('#firstName').blur(function(){ validate($(this)); });
$('#lastName').blur(function(){ validate($(this)); });
$("yourFrom").submit(function(){
var firstNameIsValid = validate($('#firstName'));
var lastNameIsValid = validate($('#lastName'));
if (!nameIsValid) && (!lastNameIsValid) {
return false;
// User has already been updated
}
});
});
Also, since you are already heavily using javascript for your validation (hope this is convenience and not the only security), you can also disable the submit button entirely until the form meets the proper requirements.