Onsubmit validate change background requried fields? - javascript

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?

Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.

Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});

I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

Related

javascript validating the whole form

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>.

apply a jQuery effect in ASP based on validation result

I have a webform with a control panel (#pnlStepOne). The panel includes two textfields "txtFname" and "txtLname". I have a validator setup for each textfield. I have tested the form and all works as desired.
My questions is how do I add a jQuery effect to the panel onclick event only if one (or both) of the textfields ("txtFname" and "txtLname") don't validate. (this effect would "shake" the panel).
And I would like to add another jQuery effect to "flip" the control panel and switch the current one (#pnlStepOne) for another one (#pnlStepTwo) if both fields are validated by the asp:RequiredFieldValidators.
Just a sample code that I will tweak once I have the right If condition.
$(document).ready(function () {
$("#btnStepOne").click(function (event) {
if (**this is the condition that I am missing**)
{
$('#pnlStepOne').css({
background: 'red',
});
}
});
});
You can modify your code to be like this:
$(document).ready(function () {
$("#btnStepOne").click(function (event) {
var fvFname = document.getElementById('client-id-of-your-fvFname-validator');
var fvLname = document.getElementById('client-id-of-your-fvLname-validator');
ValidatorValidate(fvFname);
ValidatorValidate(fvLname);
if (!fvFname.isvalid || !fvLname.isvalid) {
$('#pnlStepOne').css({
background: 'red',
});
}
});
});
Have a rad of my answer to a similar question here:
Enable/Disable asp:validators using jquery
Which has the MSDN link here: http://msdn.microsoft.com/en-us/library/aa479045.aspx
In one of my projects I use a prettifyValidation function, so you could have something like:
$(document).ready(function () {
$("#btnStepOne").click(function (event) {
prettifyValidation();
});
});
function prettifyValidation() {
var allValid = true;
if (typeof Page_Validators != 'undefined') {
// Loop through from high to low to capture the base level of error
for (i = Page_Validators.length; i >= 0; i--) {
if (Page_Validators[i] != null) {
if (!Page_Validators[i].isvalid) { // The Control is NOT Valid
$("#" + Page_Validators[i].controltovalidate).removeClass("makeMeGreen").addClass("makeMeRed");
allValid = false;
} else { // Control is valid
$("#" + Page_Validators[i].controltovalidate).removeClass("makeMeRed").addClass("makeMeGreen");
};
};
};
};
}
This will loop through all controls on the page that have an ASP.NET validator attached, and then add or remove a class depending if they are valid or not.
Obviously from here you can limit the function to a specific control by matching the controlToValidate property, and you can restyle, add controls, change classes but this should hopefully provide you a decent base to work from.

JavaScript for HTML5 required field set up to work in Safari

I am using the following script to change the HTML5 required attribute of my input elements. I am wonder whether there is a way to modify this script to make it also work in Safari browsers, since Safari does not support this attribute.
Here is the script:
$(document).ready(function() {
$_POST = array();
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field can't be blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
You can also do this:
var valid = true;
$('input[required]').each(function() {
if (this.value == '') {
// Alert or message to let them know
valid = false;
return false; // stop on first error, or remove this and it'll go through all of them.
}
});
if (valid === false) {
return false;
}
Check out this page here. It contains a hacky solution that should add the desired functionality
http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/#toc-safari
You're going to need to run the check yourself using an event handler on your form submission. In that handler, you run the check yourself, and if it fails, you display whatever error message and block the submission using preventDefault or return false.
An example can be found here, though as it notes, you need to be careful if you use checkValidity as your means of checking the form.

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

I have a bunch of controls:
When a user clicks the Generate button, a function uses all of the values from the other controls to generate a string which is then put in the Tag text box.
All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.
What is the best way to perform this using Javascript/jQuery?
This can be further optimized, but should get you started:
var pass = true;
$('select, input').each(function(){
if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
$(this).focus();
pass = false;
return false;
}
});
if (pass) {
// run your generate function
}
http://jsfiddle.net/ZUg4Z/
Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.
This code assumes that all the form fields have a default value of the empty string.
$('selector_for_the_parent_form')
.bind('focus blur click change', function(e){
var
$generate = $('selector_for_the_generate_button');
$generate.removeAttr('disabled');
$(this)
.find('input[type=text], select')
.each(function(index, elem){
if (!$(elem).val()) {
$generate.attr('disabled', 'disabled');
}
});
});
Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.
Disclaimer: I have not tested the code above, just wrote it in one pass.
If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.
function updateGenerateButton() {
if (isAnyInputEmpty()) {
$("#generateButton").attr("disabled", "disabled");
} else {
$("#generateButton").removeAttr("disabled");
}
}
function isAnyInputEmpty() {
var isEmpty = false;
$("#input1, #input2, #select1, #select2").each(function() {
if ($(this).val().length <= 0) {
isEmpty = true;
}
});
return isEmpty;
}
$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);
The above assumes that your input tags have "id" attributes like input1 and select2.

jQuery validation without "form" tag

According to http://docs.jquery.com/Plugins/Validation the "form" tag is necessary in order to do validation. In my case I don't have form tag. How can I validate(required field) my textbox on click of "button" type control
Why not just add a form tag? If it's an input, then it should normally be part of a form.
You could always wrap it with a fake form and validate it.
var $textbox = $("#textbox");
$("<form>").append($textbox).validate();
Note, however, that in most cases this should imply that we're going about something wrongly, and I'd consider a form for every element that's submitted in any form (whether it's through standard GET/POST, AJAX, etc.).
I know, it is quite old question, anyway, I had almost the same problem: I had defined form:
<form id="some-form-id"></form>
And than in document I had inputs like this:
<input type="text" form="some-form-id" />
jQuery validator cannot validate this, because elements weren't within the form, so I made small update:
There is method elements which load elements to validate and I edit it into version bellow this text. I add loading items which are not inside form, which I load into variable outForm. This items are loaded only if form has attribute id. I test it and it works. I hope that this will help to someone.
elements: function () {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
var inForm = $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled], [readonly]")
.not(this.settings.ignore)
.filter(function () {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
var formId = $(this.currentForm).attr('id');
if(typeof formId == 'undefined')
return inForm;
var outForm = $("input[form='"+formId+"'], select[form='"+formId+"'], textarea[form='"+formId+"']")
.not(":submit, :reset, :image, [disabled], [readonly]")
.not(this.settings.ignore)
.filter(function () {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
return $.merge(inForm,outForm);
},

Categories