Reading a number value from a form javascript - 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"]);

Related

How to get number values from inputs?

I'm trying to recreate the "check if hit" sistem from D&D in a small aplication and I need to get numeric values vrom input fields. Problem is, the normal document.queryselector('.input-class').value, only returns streengs. Any sugestions?
yes you can cast the string with parseInt():
let text = '42px';
let my_number = parseInt(text, 10);
// returns 42
Add + before value to convert to the number.
Like:
let item = '2019';
assert(+item).toEqual(2019);
If you need some check, function isNaN() can be used after converting to number:
https://www.w3schools.com/jsref/jsref_isnan.asp

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

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.

Fetch array value - JQuery

Consider that i have the following html
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
To fetch the values i use
a = $('#other_floor_plans').val()
It returns the following
"["Pool","Office","Sprinkler","Boiler"]"
If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.
How to accomplish this?
Your value is a type of string which has a correct JSON syntax. Just parse with JSON.parse into the array and use your syntax.
const value = '["Pool","Office","Sprinkler","Boiler"]';
const array = JSON.parse(value);
console.log(array[0]);
I think you need to change little bit of your code specially in markup.
changed your input markup into this <input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
then get value by jQuery
var a = $('#other_floor_plans').val(),
a = JSON.parse(a);
console.log(a[0]);
you need to use JSON.parse because you get json formate value and need to be parsed.
for my recommendation you just comma separate value like
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="Pool, Office, Sprinkler, Boiler">
then get first value by jQuery
var a = $('#other_floor_plans').val().split(",");
console.log(a[0]);
This one is much more readable and easy I guess.
You can use eval function to convert string to array and get the value.
var a = "['Pool','Office','Sprinkler','Boiler']"; // or you can also assign like this var a ='["Pool","Office","Sprinkler","Boiler"]'
var firstItem = eval(a)[0];
console.log(firstItem); //output will be "Pool"
There you doing a wrong practice when you initialize value in input box you must contain a value in different quotation symbols.
there you take " for value assign and " also for array string, that truncate your string on the second " that's why this return only [ in your value.
Try to use like this:
HTML
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
JQuery
var a = $('#other_floor_plans').val();
a = JSON.parse(a);
console.log(a);

Slicing a string from a textbox

I am trying to take a string entered by user from a textbox. Check the length of that string and if the string is over a given number perform the slice operation on it.
Here's what I came up with but my code does nothing. Checked console, no errors given.
html:
<form id="slice">
Enter a pharse:<input type="text" id="text_box_2"><br>
<input type="button" value="slice" onclick="Slice()">
Result: <input type="text" id="slice_result"><br>
</form>
Javascript function:
function Slice(){
var UserString = document.getElementById("text_box_2").value;
var UserStringValue = UserString.length;
var Result = Userstring.slice(1,6);
if (UserStringValue > 6){
document.getElementById("Slice_result").value = Result;
}
else{
alert("Please enter a longer phrase.")
}
}
what or where did I go wrong?
Be mindful of case-sensitivity.
This:
var Result = Userstring.slice(1,6);
Should be using UserString (capital "S") as defined earlier in your code.
Next, the input ID should be all lowercase, slice_result, to match to HTML, but your code uses different casing:
document.getElementById("Slice_result")
Here's a working JSBin with these fixes.
EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6).
from cursory reading of your code. it seems caused by this line
var Result = Userstring.slice(1,6);
and also this one
document.getElementById("Slice_result").value = Result
it should be
var Result = UserString.slice(1,6);
and
document.getElementById("slice_result").value = Result
Usually use of the following
var Value = $('#input_id').val();
will pull the requested information for you.
You can also set up arguments for your slice function and pass in the value when you run onclick();
I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit.

How can I make the script to work?

I have 3 HTML form inputs fields that is dynamically generated by a "add more" button, with naming for the fields name as fieldName, fieldName1, fieldName2, fieldName3, and so on.
Now, I'm trying to retrieve the value from this fields with JavaScript, using the script below.
var bookingForm = document.forms['formName'];
var qty = bookingForm.fieldName +'i'.value;
with the 'i' been a generated numeric number by a for loop
when I use alert(qty), it returns NaN, when I'm expecting the value for fieldName1, fieldName2, and so on.
But when I use;
var qty = bookingForm.fieldName.value
I can get the value in that field but get NaN when I try to concatenate 1,2,3, with the fieldName.
Any help will be very much appreciated.
You use brackets to access a property using a string:
var qty = bookingForm['fieldName' + i].value;
You can't use code like:
var qty = bookingForm.fieldName +'i'.value;
bookingForm.fieldName +'i' is a string. You have to change that string into a DOM element in order to access the .value parameter.
Try document.getElementsByName('fieldName'+i)[0].value

Categories