I have been tearing my hair trying to figure out why adding a line of text to an if statement would cause a form to submit without validating.
Here is the part of the code which is causing the issue:
var firstName = document.getElementById("firstName");
// if first name is empty
if (firstName.value == "") {
var fnError = document.getElementById("fnError");
fnError.innerHTML = "*Please enter your first name";
fnResult = false;
} else {
// Store firstName using local storage
localStorage.setItem("firstName", firstName.value);
}
I am trying to enter the following line of code into the else statement:
fnError.innerHTML = "";
The form is validated using an onsubmit event handler:
var btnSubmit = document.getElementById("formUser");
btnSubmit.onsubmit = validate;
And the validate function returns either true or false depending on whether the validation's conditions are met. All of this currently works well until I try to add that line of code and then the form is sent the next time the user presses the submit button regardless of whether the conditions are met or not.
I am new to JavaScript, so it is possible that I am missing something obvious.
Many thanks!
Here's one possible problem: If you're inserting the offending line into your code as shown below, your function is failing before it returns a value. In the "else" block, fnError would be in scope, but its value would be undefined. Attempting to set a property on an undefined value causes an error.
} else {
// Store firstName using local storage
fnError.innerHTML = "";
localStorage.setItem("firstName", firstName.value);
}
To fix this, move the following line before the "if" block:
var fnError = document.getElementById("fnError");
Now the fnError variable will contain a valid reference to the error-message element in both the "if" and the "else" block.
Related
I have a form wherein a user can enter a value associated with a nullable long property of my ViewModel. But because I have an 'onblur' event on that text box, I am trying to validate the entered value in my textbox.onblur() event and ensure that it does not exceed the C#'s, long.MaxValue. Here is my "blur" code on that text box.
var value = $(this).val();
console.log(value > 9223372036854775807);
if (value<= 1 || value > 9223372036854775807) {
$('#divValueError').text("Invalid Value!");
return false;
}
But Javascript is returning false on that console.log statement if I enter 9223372036854775808. How do I check if the number entered by the user falls within the limits of a C# long value?
I understand 64 bit numbers are not supported by Javascript. I also could not get my [Range] data annotation on that property to fire before this blur event is called, even though I tried
if (!$(this).valid()) {
return false;
}
Please let me know how I can throw a client side error if the value entered by the user falls outside the boundaries of a C#'s long data type value.
Thanks!
Perfect Answer :
I am Providing example that will solve your problem.
In this , you first have to convert your value in string and then in biginteger.
Reference link added for better guidance.
var valuecompare = BigInt("9223372036854775808");
var valuebase = BigInt("9223372036854775807");
console.log(valuecompare);
console.log(valuebase);
if (valuecompare > valuebase) {
console.log('greater value');
}
else{
console.log('less value');
}
Reference Link : https://www.smashingmagazine.com/2019/07/essential-guide-javascript-newest-data-type-bigint/
This returns NaN in the browser alert:
var in1 = parseFloat(document.getElementById('input1').value);
var form = document.getElementById('formC');
form.addEventListener('submit', function() {
alert(in1);
});
However this works:
var form = document.getElementById('formC');
form.addEventListener('submit', function() {
var in1 = parseFloat(document.getElementById('input1').value);
alert(in1);
});
Could someone explain whats going on here? From the error it looks like "in1" is outside the scope of the 'function()' block however doesn't "var" make it global?
The html part:
<form id="formC">
<input type="text" id="input1">
</form>
Because in the first example, you are attempting to get the value of the input and parse the float out of it immediately (before the user has had a chance to enter any data into it). So, trying to parse a float out of an empty string will yield NaN.
But in the second, you wait until the form is submitted to get the data, which is after the user has entered some data into the input.
On page render the text field is blank.
Yes, and that is when this runs:
var in1 = parseFloat(document.getElementById('input1').value);
and sets the value of in1 to NaN.
But in both cases I manually type a number (5 or 3) into the text
field before clicking the submit button.
In the first case, it doesn't matter what you do because the variable in1 already has its value. It's too late, that line has already been executed. You have no code that updates it to use the number you entered.
In the second case, it works because the variable isn't attempting to get the value until you've submitted the form, which is after you entered some data in the input field.
When the page is rendered I am assuming there is no value in the input. And you already calculated the value of it and just using on submit.
But in the second case you are reading the live value of the input
Sushanth -- and Scott Marcus are correct, you can verify by making following changes in your code
var form = document.getElementById('formC');
var in1 = document.getElementById('input1');
form.addEventListener('submit', function() {
alert(parseFloat(in1.value));
});
as you can see in1 is accessible inside the function, you just need to read the value once you submit, not before.
Above code should not return NaN unless provide invalid float number.
I've got an two if() statements, for which the conditions are both met with the default values in the <select> and <input> form fields I've tested this by assigning the values to a variable and writing the variable. (0 and Url).
However, it seems that neither if() statement's contents execute properly.
Here's a link to my JSFiddle: http://jsfiddle.net/cfRAk/2/
Any edits/answers as to why this is happening would be greatly appreciated!
Change this line:
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
To this:
var geo_select_val = parseInt($('select[name=g_country\\[1\\]]').val());
The thing is geo_select_val is actually "0" and not 0. Converting a string to boolean will only result in false if string is empty. "0" is not empty, so it was being evaluated as true. Since you are going !geo_select_val, it never goes in.
Caveat: this fix will only work if you make sure all values are numbers. If that's not the case, check for equality with "0"
Here's the code you're asking about:
$('#post-form').click( function() {
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
if(!geo_select_val) {
var geo_url_val = $('input[name=g_url\\[1\\]]').val();
if(geo_url_val != "http://google.com") {
$('#notification').html("You need to enter a valid url");
}
}
});
When I set a breakpoint in this click function and then click on the Post Form div, geo_select_val comes back as "0" which means that if(!geo_select_val) will fail because geo_select_val does have a value so the first if condition will never be executed.
Perhaps you want the first if condition to be:
if (geo_select_val != "0") {
which will tell you if some other value besides the default has been selected (assuming you add other options to that select tag with different values).
What would a JavaScript script be that, on submit, gets all form elements with class="required" and if they're empty, displays an alert box, "you must fill out so-and-so"?
I was thinking of an if-else, and in the if section we would get a while that loops through all the class=required elements, and the else would submit the form.
There are many many JavaScript libraries on the internet that do exactly this.
Try this one:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Or try a Google search for JavaScript Form Validation.
It is fairly easy to loop over the elements of a form and check that those with a certain class have a value that meets certain criteria:
<form name="f0" onsubmit="return validate(this);">
<input name="inp0" class="required" >
<input name="inp2" class="required" >
<input type="submit">
</form>
<script type="text/javascript">
var validate = (function() {
var reClass = /(^|\s)required(\s|$)/; // Field is required
var reValue = /^\s*$/; // Match all whitespace
return function (form) {
var elements = form.elements;
var el;
for (var i=0, iLen=elements.length; i<iLen; i++) {
el = elements[i];
if (reClass.test(el.className) && reValue.test(el.value)) {
// Required field has no value or only whitespace
// Advise user to fix
alert('please fix ' + el.name);
return false;
}
}
}
}());
</script>
The above is just an example to show the strategy.
Using an alert is less than optimal, usually an area is set aside adjacent to the required fields so that error messages can be written there to direct the user's attention to the invalid fields. You can also set all the error messages in one go, then return, rather than one at a time.
Edit—updating multiple errors
Have an element adjacent to each control to be validated with an id like the element's, so if an input is called firstName, the error element might have an id of firstName-err. When an error is found, it's easy to get the related element and put a message in it.
To do all at once, use a flag to remember if there are any errors, say "isValid" that is set to true by default. If you find any errors, set it to false. Then return it at the end.
Using the example above, the HTML might look like:
<input name="firstName" class="required" >
<span id="firstName-err" class="errMsg"></span>
Errors for firstName will be written to firstName-err.
In the script, if an error is found:
// At the top
var isValid = true;
var errEl;
...
// When entering the for loop
el = elements[i];
errEl = document.getElementById(el.name + '-err');
// when error found
isValid = false;
if (errEl) errEl.innerHTML = '... error message ...';
// else if error not found
// remove message whether there is one or not
if (errEl) errEl.innerHTML = '';
...
// At the end
return isValid;
You can also use a popup to show the errors, however that is really annoying and the users must dismiss the popup to fix the errors. Much better to just write next to each one what is wrong and let the user fix things in their own time.
I have a PHP form validation function that I developed in chrome and now will not work in firefox or Opera.
The function checks to see if a section of the form is blank and shows and error message. If there is no error then then the form submits through document.events.submit();
CODE:
function submit_events()
{
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && dj_amount.value==""){
//Error Control Method
//alert ('You didn\'t enetr an Amount for DJ\'s Card!');
var txt=document.getElementById("error")
txt.innerHTML="<p><font color=\"#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</font></p>";
window.document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
window.document.getElementById("company_amount_label").style.color = '#000000';
window.document.getElementById("own_amount_label").style.color = '#000000';
}else{
document.events.submit();
}
The document.events.submit();does work across all my browsers however the check statements do not.
If the box is not ticked the form submits. If the box is ticked it does not matter whether there is data in the dj_amount.value or not. The form will not submit and no error messages are displayed.
Thanks guys.
Here are some things I noticed. Not sure if it will solve the problem, but you need to fix some of these; some of them are just observations.
dj_amount is not declared nor referenced; my guess is you mean documents.events.dj_amount
You should put a ; at the end of every statement in javascript, including the end of var txt = document.getElementById("error")
You don't need to escape the string in the txt.innerHTML line; you only need to escape like quotes, such as "\"" or '\'', not "'" or '"'
You don't need the window.document referenced; document will do in almost all cases
EDIT - As Guffa points out, FONT is an old and deprecated element in HTML. It's not the cause of your problems, but modern markup methods mean you don't need it. Consider omitting and applying the style to the paragraph tag instead.
See edits below.
function submit_events() {
//Check to see if a number is entered if the corosponding textbox is checked
if (document.events.dj_card.checked == true && document.events.dj_amount.value == "") {
//Error Control Method
//alert ('You didn't enetr an Amount for DJ\'s Card!');
var txt = document.getElementById("error");
txt.innerHTML = "<p style=\"color: #FF0000;\"> You didn't enter an Amount for DJ's Card!</p>";
document.getElementById("dj_card_label").style.color = '#FF0000';
//Reset
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
} else {
document.events.submit();
}
}
Consider Firebug so that you can see and log to console javascript errors and messages:
http://getfirebug.com
I believe one of the above answers would solve your problem. For future reference, although it might not be suitable for your project, please know that writing forms and javascript feedback is much easier and faster when you use a library like jQuery.
To have minimal changes in code, just add this line before the first if statement:
var dj_amount = document.forms["events"].elements["dj_amount"];
However your code need serious optimization let us know if you're interested.
Edit: here is the optimization. First the "small" things - instead of whatever you have now for "error" container, have only this instead:
<p id="error"></p>
Now add this CSS to your page:
<style type="text/css">
#error { color: #ff0000; }
</style>
This will take care of the red color, instead of hard coding this in the JS code you now control the color (and everything else) from within simple CSS. This is the correct approach.
Second, right now you are submitting the form as response to onclick event of ordinary button. Better approach (at least in my humble opinion) is having submit button then overriding the form onsubmit event, cancelling it if something is not valid. So, first you have to change the function name to be more proper then have proper code in the function. Cutting to the chase, here is the function:
function ValidateForm(oForm) {
//declare local variables:
var oCardCheckBox = oForm.elements["dj_card"];
var oAmoutTextBox = oForm.elements["dj_amount"];
//checkbox cheched?
if (oCardCheckBox.checked) {
//store value in local variable:
var strAmount = oAmoutTextBox.value;
//make sure not empty:
if (strAmount.length == 0) {
ErrorAndFocus("You didn't enter amount for DJ's Card!", oAmoutTextBox);
return false;
}
//make sure it's numeric and positive and not too big:
var nAmount = parseInt(strAmount, 10);
if (isNaN(nAmount) || nAmount < 1 || nAmount > 1000000) {
ErrorAndFocus("DJ's Card amount is invalid!", oAmoutTextBox);
return false;
}
}
//getting here means everything is fine and valid, continue submitting.
return true;
}
As you see, when something is wrong you return false otherwise you return true indicating the form can be submitted. To attach this to the form, have such form tag:
<form ... onsubmit="return ValidateForm(this);">
And instead of the current button have ordinary submit button:
<input type="submit" value="Send" />
The code will be called automatically.
Third, as you can see the function is now using "helper" function to show the error and focus the "misbehaving" element - this makes things much more simple when you want to validate other elements and show various messages. The function is:
function ErrorAndFocus(sMessage, element) {
var oErrorPanel = document.getElementById("error");
oErrorPanel.innerHTML = sMessage;
document.getElementById("dj_card_label").style.color = '#FF0000';
document.getElementById("company_amount_label").style.color = '#000000';
document.getElementById("own_amount_label").style.color = '#000000';
}
Last but not least, the "new" code also makes sure the amount is positive number in addition to check its existence - little addition that will prevent server side crash.
Everything else is pretty much self explanatory in the function: naming conventions, using local variables.... most important is have as little redundancy as possible and keep the code readable.
Hope at least some of this make sense, feel free to ask for clarifications. :)
You should bring up the error console so that you see what the error actually is.
Lacking that information, I can still make a guess. Try some less ancient HTML code; the parser can be picky about code you add to the page using innerHTML:
txt.innerHTML="<p style=\"color:#FF0000\"> You didn\'t enetr an Amount for DJ\'s Card!</p>";