Javascript - set focus after alert message - javascript

I'm tryng to focus on the same element when validation fail. Here's my HTML code :
<input
id="potatoes" name="potatoes" value="" type="text" class="tooltip"
onblur="Validate('potatoes')" autocomplete='off'>
and here's my javascript code :
function Validate(id) {
var errors = {
potatoes : 'enter potatoes',
hamburgers : 'enter'
};
if (document.getElementById(id).value === '') {
if (id in errors) {
alert(errors[id]);
//setTimeout(function(){document.getElementById(id).focus();}, 1);
}
}
}
I've tried to set focus using .focus() method but it doesn't work. I've read that it might depend on "onblur" in HTML, when I call my function Validate(), so i've tried to change it but nothing worked till now.

There is a problem here. This code is going in loop. When 'focus' is triggered, the function Validate is called again, showing another alert dialog.
That's a working code
HTML
<input id="potatoes" name="potatoes" value="" type="text" class="tooltip" onblur="Validate(this)" autocomplete='off'>
Javascript
var validating = false; //<-- IMPORTANT
function Validate(element) {
var id = element.id;
var errors = {
potatoes : 'enter potatoes',
hamburgers : 'enter'
};
if (document.getElementById(id).value === '') {
if (id in errors) {
if(validating == false) {
validating = true
alert(errors[id]);
setTimeout(function(){
document.getElementById(id).focus();
validating = false;
}, 1);
}
}
}
}
In the html I'm passing this, doing so I'm passing the element and in the Validate function you can access to the id just calling
var id = element.id;
For the focus problem (caused by a loop problem) as you can see I'm using a validating variable to know when is validating when is not. This let Validate function avoids to go in loop.
So:
1) Define a validating var outside the Validate function and set it to false.
2) Fire the focus and alert only if validating is false, and after that set it to true

The javascript function alert(string) is synchronous. The script is paused while the user is reacting to the alerted message. There is no need to do something special. The following snippet should work:
alert(errors[id]);
document.getElementById(id).focus();
The element got focus directly after the user has submitted the alerted message.

You can use jQuery like this:
setTimeout(function() {$('#yourInputId').focus();},1);

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

Jquery, onBlur - if not empty show an alert

I'm trying to modify some other code that I found on SO, but it's not working (I'm still learning JQ)
My code:
$("#Email").blur(function(){
var inp = $("#Email").val();
if(jQuery.trim(inp).length > 0)
{
alert("Yay!");
}
} );
Basically (in case it's not clear) I want to fire that alert() as the user moves away from the textbox - only if the user entered something in the textbox.
Code seems to work, make sure the field is loaded before binding the event, preferably using $(document).ready()
$(document).ready(function(){
$("#Email").blur(function(){
var inp = $("#Email").val();
if(jQuery.trim(inp).length > 0)
{
alert("Yay!");
}
} );
})
Here is the related fiddle

Form validation - How to keep track of multiple fields to prevent submit - Global variable?

I have a form with multiple fields (lets say 4 for this example).
I am using javascript functions on each field to validate them, generating an error indication - a red box, or a hint as text next to the box.
like so ..
<input
...
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
So what I would like to do is not allow a submit if any of the fields do not validate.
So the question is - what is the best way to set it up so submit is disabled unless all 4 fields are valid?
I will use either
document.getElementById("mySubmit").disabled=true;
or
event.preventDefault()
(..though trying to avoid Jquery) to prevent the submit.
How should I keep track of the condition of the 4 fields?
Should I create a global variable like - window.validFields, so I can access it from each of my validation functions - adding one to the variable for each field that is valid, and subtracting one when invalid? (window.validFields==4 allows a submit)
Not sure the best way to accomplish this.
Any help would be appreciated, thanks.
Assuming a form like this …
<form class="is-invalid" id="form" method="post">
<input type="text" id="lorem">
<input type="text" id="ipsum">
<input type="text" id="dolor">
<input type="text" id="amet">
<button id="submit">Submit</button>
</form>
… you could do the following …
(function () {
var fields = {
lorem: false,
ipsum: false,
dolor: false,
amet: false
},
isValid = false,
form = document.getElementById('form'),
i,
tmpInput;
// Binding submit-event to prevent form-submit
form.addEventListener('submit', onSubmit, false);
// Binding events on input-elements (keyup & blur)
for ( i in fields ) {
tmpInput = document.getElementById(i);
tmpInput.addEventListener('keyup', checkInput, false);
tmpInput.addEventListener('blur', checkInput, false);
}
// Checking form state by iterating over the fields object;
// Adding/removing 'is-valid'-class and setting `isValid`-flag
function checkFormState() {
for ( var j in fields ) {
if ( !fields[j] ) {
isValid = false;
form.className += /\bis-invalid\b/i.test(form.className)
? ''
: 'is-invalid';
return;
}
}
form.className = form.className.replace(/\bis-invalid\b/i, '');
isValid = true;
}
// Abort the submit, if the `isValid`-flag is `false`
function onSubmit(evnt) {
if ( !isValid ) {
evnt.preventDefault();
return false;
}
}
// Setting the corresponding value in the `fields`-object;
// Checking the form state
function checkInput() {
fields[this.id] = this.value.length > 5; // or any other validation rule
checkFormState();
}
})();
There's an object with the IDs of the relevant input-fields that holds each validation state. On keyup and blur each input field is checked. If it passes the validation, the corresponding value in the fields-object is set to true. Additionally the state of the form is checked on each event on an input element.
The checkState-function iterates over the fields-object. If it finds a property, that is false, the 'is-invalid'-class is set on the form-element (if it isn't already set), the isValid-flag is set to false and the function is aborted.
Otherwise — all input-fields are valid —, the isValid-flag is set to true and the 'is-invalid'-class is removed from the form-element. Now, the form can be submitted.
This all works without a single global variable. Mission accomplished!
I made a Fiddle where you can test this.
PS: Have in mind, that the addEventListener-method is only supported by IEs down to version 9. If you have to support version 8 and below, you need a workaround like this.
I hope this helps you.
You can use the forms submit event, like this:
HTML:
<form method="post" onsubmit="return MyValidation(); " ...
JS:
(function() {
var field1Valid = false;
var field2Valid = false;
window.validateField1 = function(elmnt) {
// do some validation...
if(everything == OK) {
field1Valid = true;
setButtonDisabled(false);
}
else {
field1Valid = false;
setButtonDisabled(true);
}
}
window.validateField2 = function(elmnt) {
// do some validation...
if(everything == OK) {
field2Valid = true;
setButtonDisabled(false);
}
else {
field2Valid = false;
setButtonDisabled(true);
}
}
window.checkDuplicateName = function() {
// do some more validation...
}
window.setButtonDisabled = function(disabled) {
document.getElementById('submit').disabled = disabled;
}
window.MyValidation = function() {
return field1Valid && field2Valid;
}
}());
The above example also checks whether to disable the submit button or not.
Another way would be to handle all your validation logic within the form submit event, but validating input immediately is always nicer.
There are also quite some validation plugins available for use with jQuery, if you're interested. Building this yourself can get messy quickly if you have multiple fields that need to be validated in multiple ways...

Popup - if user enters bad input, how can I get it to error on submit

I have a popup on my page that has a typeahead input on it. Right now you can type garbage and click submit and it lets you. I'm trying to write code that will throw an error on the popup if you type something that isn't included in the typeahead options and it won't let you submit it until you fix it. Here is my code, it is for making a school schedule that has classes in the typeahead dropdown.
var schedule = schedule.content.get();
var validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
isErrorForValidClasses = Fp.all(inputClasses, function (inputClass) { return Fp.contains(validClasses, inputClass); });
if(validClasses !== inputClasses){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
}
Right now if you enter garbage in the input field, this will throw an error but still let the user submit. How can I stop the user from submitting until the input is correct?
Here is my button:
$submitBtn.on('click', function(event){
if(inputParameters() !== false){
$myPopUp= $modal.find('#myData').detach()[0];
}
event.preventDefault();
});
and I checked the output of inputClasses in the Google developer console, it outputs the class and a prevObject. I just need the class...
Let javascript return either True or false and if the popup comes out return false other wise true.
For instance if it get into if return false other wise true.
since you modified your code i suppose you might want to try this instead:
http://api.jquery.com/event.stoppropagation/
also you might want to be doing something along the lines of this if stoppropagation does not result in the desired effect:
$("#formid").on("submit",function(e){
// declare isValid outside of this and set it in your validation function or call it inside this and check for that.
if(isValid) {
e.stopPropagation();
}
});
at least that's how i went about solving such issues usually. i hope it helps.
got it. the error i had was throwing an error.
var schedule = schedule.content.get(),
validClasses = Fp.filter(schedule.classes, function (class) { return !class.passed; }),
inputClasses = $('.optimizeViaClasses input.className').map(function () { return $(this).val(); }),
actualValidClasses = Fp.pluck(validClasses, 'className');
$.each(inputClasses , function(index, value){
if($.inArray(value, actualValidClasses ) === -1){
$errorMessage.text('Your selection does not match the class(es) in the current schedule!');
$errorMessage.show();
error = true;
return false;
}
});

Stop page refreshing when 'enter' is pressed in input text element

Is there a way to stop a webpage from refreshing completely when the enter button is pressed in a input text element?
I'm looking to create a search field that I can get the text from when enter is pressed to filter objects and only display the ones that contain text from the search field.
I've tried the following to try and catch the enter button but it does not work.
function setupSearchField() {
document.getElementById("searchField").onKeyDown = function(event) {
var holder;
if (window.event) {
holder = window.event.keyCode;
} else {
holder = event.which;
}
keyPressed(holder);
}
}
function keyPressed(key) {
if (key == 13) {
event.cancelBubble = true;
return false;
}
}
If the input element is inside a form, and that form is not actually being submitted to the server, remove the form.
The reason your code doesn't work is becaue the onkeydown event should be in lowercase, and you aren't actually returning something in it (try return keyPressed(holder); - or just move the keyPressed function's code into setupSearchField, since it seems kind of pointless to me to have it as a separate function).
This happens when there is only one text input, regardless of whether your button (if any) has type="submit" or not. It's documented here.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2
So, as suggested by other people earlier, you then have to simply stop this default behavior.
Is your search field inside a element ? Then hitting 'enter' fires a submit event to the form element.
In this case you could process your filtering by defining onsubmit on the form element.
<form id="searchForm">
<input type="text" name="search" />
</form>
<script>
document.getElementById('searchForm').onsubmit = function() {
var searchValue = this.search.value;
// process
return false;
}
</script>
Something like this maybe.
Just add the following javascript code to your Visualforce page:
<script type='text/javascript'>
function stopRKey(evt)
{
var evt=(evt) ? evt : ((event) ? event : null);
var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>

Categories