Why does parseFloat(value) of form text input give NaN? - javascript

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.

Related

Input Tag returning Empty String after inputting 1st character

I am trying to get the values from an input box. When I first input a character and hit enter it returns an empty string in console and I only get the first value after inputting the 2nd value. For example: If I write 'a' in the input box and hit enter it returns an empty string and then if I write 'b' in the input box then it returns a and so on. Here's my code -
let opts = [];
let optInputs = document.getElementsByName("option_values[]");
for(let j = 0; j < optInputs.length; j++){
opts.push(optInputs[j].value);
}
If I only console.log optInputs then I am getting the Nodelist and inside it, I am getting the values immediately but whenever I want to access it in a loop I seem to get an empty string after I enter the first character. I have faced an issue like this. Can anyone please help me out here I have been scratching my head over this issue for 3 days now.
Try using a different selector like querySelector /getElementById / getElementByClassName
1.I need someway to call my code. here I am telling my form to execute the function every time the user submit the form.
i am also using preventdefault(); inside my function because I don't want it to reload my page.
2.getting the value of the input withdocument.querySelector(".option_values").value; & storing it in optInputs.
3.pushing the value of optInputs into the array opts.
4.document.querySelector(".option_values").value = ""; to clear the input.
everytime you hit enter it will go back to empty.otherwise user has to backspace and removing previous characters.
let opts = [];
function myFunction(event) {
event.preventDefault();
let optInputs = document.querySelector(".option_values").value;
opts.push(optInputs)
document.querySelector(".option_values").value = "";
console.log(opts)
}
<form onsubmit="myFunction(event)">
<input class="option_values" type="text" />
</form>

Validating C#'s Long Variable value in Javascript

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/

Reading a number value from a form javascript

I'm trying to retrieve a number from a from in my HTML, but the javascript doesn't read the value as I would expect it to.
The code I'm using is
<input type="number" id="itemsize" name='itemsize' onChange="calculateTotal()"/>
Note that calculateTotal successfully calls getSizePrice, but doesn't read it as a number
function getSizePrice()
{
var sizePrice=0;
var theForm = document.forms["orderform"];
sizePrice = theForm.elements["itemsize"];
return sizePrice;
}
should it be
sizePrice = parseFloat(theForm.elements["itemsize"].value);
the input is passing in a text value - you will need to parse it to get a number. the following will convert the input value to a number. Also I am unfamiliar with this code structure - are you actually getting the value from the input? should you be using ...theForm.elements["itemsize"].value...
sizePrice = parseInt(theForm.elements["itemsize"]);

How to select and set multiple textboxes text in jquery

Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)

statement causing form to submit without validation

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.

Categories