Focus on the first empty input - javascript

I am trying to focus the first empty input element on first submit but when the email and password inputs are empty, it always focuses on the password (latter) input first.
How can I focus on the first empty input in a way that works across all browsers?
$('input').each(function() {
if ($(this).val() == '') {
this.focus();
}
});

This happens because you are iterating over all input elements and calling .focus() if it has no value. If both the username field and the password field have no value, it will first call .focus() on the username field, but then it will continue iterating and call .focus() on the password field too, which takes focus away from the username field. What you want is to stop iterating over the input fields when you detect the first one with no value. To do this just return false; to tell JQuery's each to stop iterating.
$('input').each(function(){
if($(this).val() == ''){
this.focus();
return false;
}
});
For comparison, see this demo:
Your way: http://codepen.io/Chevex/pen/XbpeMd
With return false;: http://codepen.io/Chevex/pen/VLPMpr
You can see your bug is reproduced in the first demo, and then it's fixed in the second demo. You can load those demos in any browser and see that it works.
Edit: Here it is working in Opera.

Here it is in vanilla JavaScript:
var input = document.getElementsByTagName('INPUT');
for (var i = 0, n = input.length; i < n; i = i + 1) {
// may also need to test for input[i].type
if (!input[i].value) {
input[i].focus();
break;
}
}

Just return false; after you focus the element to break the $.each() loop. Currently the focus will be set to your last empty element as the loop continues.
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
Source: https://api.jquery.com/jquery.each/
Edit, to be clear:
$('input').each(function() {
if ($(this).val() == '') {
this.focus();
return false;
}
});
Edit, so you won't have to read all the comments:
The complete solution was to use event.preventDefault() in the according onSubmit handler and then check the inputs for empty values in it.
Afterwards some further processing (as in: validating and finally submitting it to the (server-side) application) of the inputs is needed of course.
$('#loginForm').on('submit',function (e) {
e.preventDefault();
// focus first empty input
$('#loginForm input').each(function() {
if ($(this).val() == '') {
this.focus();
return false;
}
});
// further input processing
});

Related

Check if text is selected on keydown event

I have a scenario where i prevent user from entering 2nd numeric after a decimal.I have my code on keydown event.
Below is my code:
$scope.Inputkeydown = function (event, value) {
if (event.keyCode != 8) {
if (value != null && value != undefined && value != "") {
var regex = /^\d*\.\d$/; //this regex passes only decimal numbers with one digit after decimal
if (regex.test(value)) {
event.preventDefault();
}
}
}
};
Now the trouble is if user selects on the text(say 50.0) in the textbox and say presses 5 at that time it is getting prevented too, as in the textbox value is 50.0 and regex allows it go and it is getting prevented from being typed in.
Can i check on keydown if text is being copied?? or is there any other way around?
Instead of preventing the user from entering it, you could just remove it after keypress:
function filterDecimals(inp) {
return inp.replace(/^(\d*\.\d)\d*$/g, '$1');
}
Or, if you want to remove everything after it, replace the second \d* with .*
EDIT (example of usage)
This function takes the text as input and returns the new filtered text. To use this, just attach an event handler on keypress like so:
<input type="text" id="filteredbox">
<script>
var txt = document.getElementById("filteredbox");
// on keyup event (you can change to keypress if you want, but this is more logical here
txt.addEventListener("keyup", function(){
// sets value of txt to the returned data from filterDecimals()
// if statement: only filters it if necessary; this eliminates the "selected text" issue you mentioned
if (this.value !== filterDecimals(this.value)) {
this.value = filterDecimals(this.value);
}
});
</script>

Preventing next tab if current tab have empty field

I have a form having few questions set, each displayed at a time (like a slide). I want to prevent next set if current set has an empty field. Below is my script that navigates through each questions set. Any help would be highly appreciated.
$(document).ready(function() {
var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();
$('#next').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion++;
if (currentQuestion == $questions.length - 1) {
$('#next').css('display', 'none');
$('#submit').css('display', 'inline');
}else{
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
}
$('#back').css('display', 'inline');
$($questions[currentQuestion]).slideDown();
});
});
$('#back').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion--;
if (currentQuestion == 0) {
$('#back').css('display', 'none');
} else {
$('#back').css('display', 'inline');
}
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
$($questions[currentQuestion]).slideDown();
});
});
});
Here is my JSFiddle
I came across your question and decided to fork your fiddle.
You should make a function that checks your conditions before continuing on to the next tab.
In your case, the conditions would be: All fields must be filled
I've added this function that checks the active section and returns true / false, in order to continue.
function validateFormSection() {
var valid = true; //As long as it's true, we may continue
var section = $('.question.active'); //Find the active section
var inputs = section.find('input'); //Get all its inputs
inputs.each(function(index, el) {
if ( $(el).val() == "" ) {
valid = false;
}
});
return valid;
}
JSFiddle here
On the third page, the form would submit whether all fields are empty or not.
You can prevent this by hooking onto the submit function and checking for empty fields.
If they're empty, we use e.preventDefault(); to keep it from submitting.
If they're filled, we simply submit by doing $('form').submit();
$('form').submit( function (e) { //Hook into the submit event
var valid = validateFormSection(); //Check if our fields are filled
if ( valid ) { //They are filled?
$('form').submit(); //Very well, let's submit!
} else {
e.preventDefault(); //If not, prevent the (default) submit behaviour
}
});
The fiddle has been edited to reflect these changes.
You could use if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length) to check if there are empty fields. Fiddle: http://jsfiddle.net/ilpo/cuqerfxr/1/
$('.question') selects all the questions
.eq(currentQuestion) selects the question you're currently at
.find('input') selects all the input fields inside the current question
.filter(function(){return this.value==""}) selects only empty input fields
.length counts the amount of matches, e.g. amount of empty inputs
if(number) returns true with a positive value, e.g. if there were any empty inputs
! in front of it all inverts it, returning true if there are no empty fields

jquery - Check specific inputs for empty value and add class to ONLY those inputs that are empty

I have form that has input fields that are required, I point this out with made up class name.
I have piece of code that kind of works. If I focus on required input and then press submit, that input will become red, if empty (which I want). But it only works only on one at a time and if I have focus on the input.
My code is as follows:
function checkIfEmpty(){
$('#register-form input.gv-form-required').blur(function(){
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
return false;
}else{
return true;
}
});
}
I am almost certain that the blur() method is not suitable for my situation.
So help a man out here, please.
Try this : You have to use .each() to check every input inside form and put removeClass in else condition.
function checkIfEmpty(){
var empty = false;
$('#register-form input.gv-form-required').each(function(){
if($(this).val().trim()==""){
empty = true;
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
return empty;
}
The blur event indeed doesn't seem right in your situation. What I would do is that I would itterate through each field and checked whether it is filled or not. If it is, remove (if any) has-error class. If it isn't filled, give it the has-error class
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if($(this).val() === ""){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
change your code to the following:
function checkIfEmpty(){
$('#register-form input.gv-form-required').each(function(){
if( !$(this).is(':empty')){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}
});
}
try
in else condition
$(this).parent().parent().removeClass("has-error");
js code
if( !$(this).val()){
$(this).parent().parent().addClass("has-error");
}else{
$(this).parent().parent().removeClass("has-error");
}

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

Categories

Resources