Pointing to first field after validation - javascript

I have a webpage which has check-boxes, input fields, dropdowns etc.,
Mandatory conditions are checked using javascript. If anyone fails to fill these fields and press next button validation errors popup.
Now what I want to achieve is when someone fails to enter information in the mandatory fields, the cursor should go to the first field which caused the error.
Can anyone suggest me how to do this?

Add a class (something like input-error) for every invalid field. Then use something like:
var errors = document.querySelectorAll(".input-error");
if (errors.length > 0) {
errors[0].focus();
}
Here's an example: http://jsfiddle.net/NtHzV/1/
It really all depends on the structure of your code, how you're validating, what you're actually doing with validation, and what your HTML is.
At the same time, if you're doing something similar to my example, you might as well keep track of the first input with an error, then focus() it at the end of validation. Something like this:
http://jsfiddle.net/NtHzV/2/
UPDATE:
Bergi pointed out that querySelector might as well be used (instead of querySelectorAll) because you're only looking for the first input with errors. So here's an update:
var error_input = input_area.querySelector(".input-error");
if (error_input !== null) {
error_input.focus();
}
http://jsfiddle.net/NtHzV/3/
Here's specs on querySelector: https://developer.mozilla.org/en-US/docs/DOM/element.querySelector - Note that < IE8 does not support it.
The use of ".input-error" is because that is the CSS class selector, and will find the first (if any) element in a specific area with the class "input-error".

This line will focus the page on the element you specify. You should be able to implement this into your validation checks to focus on the bad elements.
document.getElementById("ID_Of_bad_field").focus();

Related

jquery validation plugin detects errors, but no messages appear, why not?

I'm using the jQuery Validator plugin 1.19.5 on a slightly large (but simple) form generated from a PDF by an online converter to html5
The form has a Submit button implemented as a button with onclick to a javascript function within the formviewer.js file that is part of the conversion to html5. If I open the form in Chrome 107.0.5304.107 Developer Tools, I can see that the Submit button goes to the following code that I added to the success branch of the function that handles the submit in formviewer.js:
success: function() {
const OSHform=$("form").eq(0);
if (OSHform.valid()) {
top.document.location.href = "/Adsentry/completed";
}
else {
alert("Fields did not validate, please fix errors and try again");
}
},
failure: function() {
alert("Form failed to submit, please try again")
}
In a separate script, I invoked validate() on the form element, passing it rules for the fields to validate.
var $j = jQuery;
var OSHform = $j("form");
OSHform.validate({
rules: {
"NAME OF DRIVER": "required",
"EMAIL": "required",
"EMAIL": "email",
"ADDRESS": "required"
}
});
If I omit required fields, or enter an invalid email address in an email field, the call to valid() returns false. And in fact, if I look at the input elements in the Elements tab, I can see that class="error" gets added, and if I correct the error it changes to class="valid". Additionally, with class="error", a label gets added for that element, also with class="error", and correcting the problem adds style="display:none;" to the label.
So everything is great, except that there is no text or message that goes with the label, so its presence/absence, or the presence/absence of display:none on it, has no effect on the normal display of the page.
I have tried stepping through the code in the debugger, but I'm afraid my javascript is so weak I can't really figure out what's going on to the extent of understanding why the messages are not being displayed.
You can play with it live here for the time being, but I can't promise to stop fiddling with it! There are currently only 3 required fields: Name of driver, Address, and Email. If they are all correct, the form submits as intended.
A little disappointed that this didn't even get any comments, let alone answers. On the other hand, it turned out the answer was exactly as anyone even slightly more experienced than me would likely have guessed: errors were being reported in HTML elements, but there was no CSS to put them in the right location on the page. The plugin seemed to be buggy in failing to produce default message text describing the errors; instead, it just produced message text that was simply the name attribute of the erroneous input element. But without appropriate CSS, that name attribute was output in the black strip at the bottom of the page, making it essentially invisible. It took a sharp eye to notice the sudden appearance of "fly specs" at the bottom of the page when clicking the submit button.
The plugin just inserts an HTML element into the DOM immediately following the bad input element. But the files generated from the PDF include a style sheet with selectors using the ID of each input element to give the input element absolute placement on the page. And simply inserting an element into the DOM as the next sibling of the input element, without a style, results in having it rendered at the bottom of the page. Even when I figured out that the lack of CSS was the problem, it took me a while to get something that worked: good old selector specificity in action. All of the input elements were placed using ID selectors with absolute position, and I could find no way to have the simple next-sibling relationship of the message to the input element cause the message to be rendered immediately after the input element. Although it made me feel "icky" to do it, the solution I came up with was to use jQuery to iterate over all the message elements with the "error" class, get the ID of the input element it was reporting, and then use $.css() to get the input element's effective top, left, and width style attributes. Then strip off the trailing "px", multiply by 1 to get a numeric value, add the width to the left numeric value, and specify new top and left attributes using $.css() on the message elements. This put the messages I defined in the messages sub-object of the object passed to the validate constructor appear in the right locations. It only remains a mystery why the default messages didn't appear instead of the names of the input elements for elements that were invalid.

Capture "auto-suggest" event using JavaScript

I have created a nice cross-browser utility which ensures that form "placeholders" behave in the same way (including IE which does not implement them)
However, this has created a different problem when a user fills a form and the browser helpfully provides an auto-suggest for the remaining fields in the form, eg, for a registration form: You might type your name, and the browser will auto-suggest your surname, email address, postal address, etc...
I don't care what the auto-suggested values are, but I need find a way of capturing "event" on each field so I may hide my implementation of the place holder.
I've had a look at the DOM elements in Chrome to see if the auto-suggest value is stored in a custom attribute, but have been unsuccessful.
Has anyone else seen or experienced this? Does anyone know if its even possible to capture such an event?
NOTE: This issue disappears when the user accepts the auto-suggest, and this becomes an auto-complete, which fires a change event on the fields; so I only need to capture the suggest event
I have produced the following script which "detects" when the fields have become auto-suggested by Webkit:
I am assuming anyone using this knows Underscore and jQuery.
var $form = $('form'),
autoCompleteSetting = $form.attr('autocomplete');
if (_.isUndefined(autoCompleteSetting) || autoCompleteSetting === "on") {
_($form.find('input')).each(function($input){
setInterval(function() {
if ($input.is(":-webkit-autofill")) {
// do your code here to detect the webkit autofill setting
}
}, 100);
});
}
I personally have put the webkit-autofill check into a ternary operator.
Obviously use at your own risk; having these intervals running for every field on your page every millisecond may cause problems for some users!

jQuery prefil dashes in text field

I have a text field where a user inputs a value in the form of 2012-112233-123. I would like the dashes to be automatically added to the field as the input is entered.
I can implement a basic check on the keyup event that checks if the cursor is in the 5th or 12th position, but this causes issues when backspacing (dashes are re-added upon removal). If possible I would also like to ignore the user input if they decide to manually add the dash.
Is there an easy way of doing this, or a simple plugin I can use? Seems like a lot of code and checking for something that I would assume is a fairly common requirement.
Take a look at input masks.
This jQuery plugin looks good.
It allows you to do things such this:
jQuery(function($){
$("#date").mask("99/99/9999");
$("#phone").mask("(999) 999-9999");
$("#tin").mask("99-9999999");
$("#ssn").mask("999-99-9999");
});
There's even a callback available for when the input is filled.
I once used this plugin:
http://digitalbush.com/projects/masked-input-plugin/
for your need just define
$(".yourinput").mask("9999-999999-999");

Input fields examples from title tag, with toggle

I'm creating a form, that needs to have examples in the input fields. So when you click in them, example will toggle away and you can insert your own value.
Also the examples need to be in a different class. And I think the best way to load the examples, is from the title tag. Because, when I submit the form.. I don't want the examples to count.
Currently Im using this jQuery plugin: http://jquery.kuzemchak.net/toggleval.php
It basically works like it should, but the issue is with the submit. To clear out the input fields on submit, I made this script:
$(".formtable_submit").hover(function () {
$(this).parents("form").find("input").each(function () {
$(".toggleval:not(.toggleval_foc)").val("");
});
});
So if you hover over submit, it will clear out all input fields with .toggleval class, but not the ones with user-inserted values in them (.toggleval_foc class).
I could also add to that script, that when you hover-out, then it would display the examples again.. But its not the best solution. The best way would be display them from title tag and on submit, the value tag would as it is.
If you could point me to a script or some idea, that would be awesome. I could not find any such script that worked.
What you are describing is placeholder functionality, and it should not be accomplished as a polyfill by putting any values into the real input fields, thus negating your need to clear out invalids on form submittal.
I suggest switching to a plugin that already has this stuff figured out, such as any of the plugins on this page under Web Forms: input placeholder. Modern browsers let you style the placeholder using the ::placeholder CSS pseudo-element and most of these polyfills give you a classed element to style for older browsers.
Put your default values in the field initially, give them a class of wipe, then try something like this...
$('.wipe').addClass('wipeDefault'); $('.wipe').focus(function() {
if (this.value == this.defaultValue) { this.value = '';
$('.wipe').removeClass('wipeDefault');
$(this).removeClass('wipeDefault'); } });
$('.wipe').blur(function() { if (this.value == '') {
this.value = this.defaultValue;
$('.wipe').addClass('wipeDefault');
$(this).addClass('wipeDefault'); } });
Why not bind to the form's submit event instead of the hover? If you do something like this:
$('selector-for-your-form').submit(function() {
$(this).find('input:not(.toggleval_foc)').val('');
return true;
});
Then you'll clear out the default example values right before the form is submitted. You will, of course, have to supply a real selector in place of 'selector-for-your-form'.

Grab text input as the user types

I'm trying to update a span tag on the fly with data from an input text field. Basically I have a text field and I'd like to be able to grab the user's input as they type it and show it to them in a span tag below the field.
Code:
<input id="profileurl" type="text">
<p class="url">http://www.randomsite.com/<span id="url-displayname">username</span></p>
JQuery:
var username;
$('#profileurl').keyup(function(username);
$("#url-displayname").html(username);
See it in JS Fiddle: http://jsfiddle.net/pQ3j9/
I'm guessing the keyup function is not the best way to do this. Since checking the key wouldn't be able to grab prefilled or pasted form input.
Ideally there is some magical jQuery function that can just output whatever info is in the box whenever it detects a key up but if that method exists I haven't found it yet.
EDIT: You guys are fricken amazing. It looks like .val() is that magic method.
Second question: How would you restrict input? Looking at the modified jsfiddle's, when a user inputs an html tag like < hr > the browser interprets it and breaks the form. Do you specify an array and then check against that? Does jquery have anything like PHP's strip_tags function?
$('#profileurl').keyup(function(e) {
$("#url-displayname").html($(this).val());
}).keypress(function(e) {
return /[a-z0-9.-]/i.test(String.fromCharCode(e.which));
});
check out the modified jsfiddle:
http://jsfiddle.net/roberkules/pQ3j9/5/
Update: As #GregL points out, keyup indeed is better, (otherwise e.g. backspaces are not handled at all).
Similar to roberkules' answer, but using keyup() like you proposed seems to work better for me in a Chrome-based browser:
$('#profileurl').keyup(function(e) {
$("#url-displayname").html($(this).val());
});
Updated jsFiddle: http://jsfiddle.net/pQ3j9/3/
For the second question, if you wish to maintain characters and not have them parsed as html entities then you should do this instead :
$('#profileurl').keyup(function(key) {
$("#url-displayname").text($(this).val());
});
Check it out at - http://jsfiddle.net/dhruvasagar/pQ3j9/6/
You can bind multiple events with bind
http://jsfiddle.net/dwick/DszV9/

Categories

Resources