getElementByID won't pass the values to variables - javascript

Javascript
function fn1(){
var a = document.getElementById("xa").value;
var b = document.getElementById("ya").value;
var c = document.getElementById("xb").value;
var d = document.getElementById("yb").value;
fn2(a,b,c,d);
}
HTML
<div align="center"><b>Digital Differential Analyzer</b><br /><br />
X0: <input type="text" id="xa"/>
Y0: <input type="text" id="ya"/>
XE: <input type="text" id="xb"/>
YE: <input type="text" id="yb"/>
<input id="button1" type="button" value="Submit" onclick="e.width = e.width;fn1();" /></div>
If I enter function1 as only the call to function2 with ready values (such as 0,0,300,300), it works fine, but when I try to get the variables with getElementById, nothing works, I tried to modify it a lot but still the same result, and it doesn't even show as an error

try:
fn2(+a,+b,+c,+d);
this will convert input values from string to int. your function is not working because you are passing string values to the funcrion.
it adds 0 to the variable a,b,c,d respectively and casts string to int
i.e. 0+a=a but now 'a' is int.
for more accuracy try with parseFloat()
function fn1(){
var a =parseFloat( document.getElementById("xa").value);
var b =parseFloat( document.getElementById("ya").value);
var c =parseFloat( document.getElementById("xb").value);
var d =parseFloat( document.getElementById("yb").value);
fn2(a,b,c,d);
}

Related

Uncaught TypeError: document.getElementById(...).value.totoUpperCase is not a function [duplicate]

I am working on a search with JavaScript. I would use a form, but it messes up something else on my page. I have this input text field:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
And this is my JavaScript code:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
How do I get the value from the text field into JavaScript?
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1
document.getElementById('textbox_id').value to get the value of
desired box
For example
document.getElementById("searchTxt").value;
 
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0],
for the second one use [1], and so on...
Method 2
Use
document.getElementsByClassName('class_name')[whole_number].value which returns a Live HTMLCollection
For example
document.getElementsByClassName("searchField")[0].value; if this is the first textbox in your page.
Method 3
Use document.getElementsByTagName('tag_name')[whole_number].value which also returns a live HTMLCollection
For example
document.getElementsByTagName("input")[0].value;, if this is the first textbox in your page.
Method 4
document.getElementsByName('name')[whole_number].value which also >returns a live NodeList
For example
document.getElementsByName("searchTxt")[0].value; if this is the first textbox with name 'searchtext' in your page.
Method 5
Use the powerful document.querySelector('selector').value which uses a CSS selector to select the element
For example
document.querySelector('#searchTxt').value; selected by id
document.querySelector('.searchField').value; selected by class
document.querySelector('input').value; selected by tagname
document.querySelector('[name="searchTxt"]').value; selected by name
Method 6
document.querySelectorAll('selector')[whole_number].value which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.
For example
document.querySelectorAll('#searchTxt')[0].value; selected by id
document.querySelectorAll('.searchField')[0].value; selected by class
document.querySelectorAll('input')[0].value; selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value; selected by name
Support
Browser
Method1
Method2
Method3
Method4
Method5/6
IE6
Y(Buggy)
N
Y
Y(Buggy)
N
IE7
Y(Buggy)
N
Y
Y(Buggy)
N
IE8
Y
N
Y
Y(Buggy)
Y
IE9
Y
Y
Y
Y(Buggy)
Y
IE10
Y
Y
Y
Y
Y
FF3.0
Y
Y
Y
Y
N IE=Internet Explorer
FF3.5/FF3.6
Y
Y
Y
Y
Y FF=Mozilla Firefox
FF4b1
Y
Y
Y
Y
Y GC=Google Chrome
GC4/GC5
Y
Y
Y
Y
Y Y=YES,N=NO
Safari4/Safari5
Y
Y
Y
Y
Y
Opera10.10/
Opera10.53/
Y
Y
Y
Y(Buggy)
Y
Opera10.60
Opera 12
Y
Y
Y
Y
Y
Useful links
To see the support of these methods with all the bugs including more details click here
Difference Between Static collections and Live collections click Here
Difference Between NodeList and HTMLCollection click Here
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
See this functioning in codepen.
I would create a variable to store the input like this:
var input = document.getElementById("input_id").value;
And then I would just use the variable to add the input value to the string.
= "Your string" + input;
You should be able to type:
var input = document.getElementById("searchTxt");
function searchURL() {
window.location = "http://www.myurl.com/search/" + input.value;
}
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
I'm sure there are better ways to do this, but this one seems to work across all browsers, and it requires minimal understanding of JavaScript to make, improve, and edit.
Also you can, call by tags names, like this: form_name.input_name.value;
So you will have the specific value of determined input in a specific form.
Short
You can read value by searchTxt.value
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
<script type="text/javascript">
function searchURL(){
console.log(searchTxt.value);
// window.location = "http://www.myurl.com/search/" + searchTxt.value;
}
</script>
<!-- SHORT ugly test code -->
<button class="search" onclick="searchURL()">Search</button>
<input type="text" onkeyup="trackChange(this.value)" id="myInput">
<script>
function trackChange(value) {
window.open("http://www.google.com/search?output=search&q=" + value)
}
</script>
Tested in Chrome and Firefox:
Get value by element id:
<input type="text" maxlength="512" id="searchTxt" class="searchField"/>
<input type="button" value="Get Value" onclick="alert(searchTxt.value)">
Set value in form element:
<form name="calc" id="calculator">
<input type="text" name="input">
<input type="button" value="Set Value" onclick="calc.input.value='Set Value'">
</form>
https://jsfiddle.net/tuq79821/
Also have a look at a JavaScript calculator implementation.
From #bugwheels94: when using this method, be aware of this issue.
If your input is in a form and you want to get the value after submit you can do like:
<form onsubmit="submitLoginForm(event)">
<input type="text" name="name">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<script type="text/javascript">
function submitLoginForm(event){
event.preventDefault();
console.log(event.target['name'].value);
console.log(event.target['password'].value);
}
</script>
Benefit of this way: Example your page have 2 form for input sender and receiver information.
If you don't use form for get value then
You can set two different id (or tag or name ...) for each field like sender-name and receiver-name, sender-address and receiver-address, ...
If you set the same value for two inputs, then after getElementsByName (or getElementsByTagName ...) you need to remember 0 or 1 is sender or receiver. Later, if you change the order of 2 form in HTML, you need to check this code again
If you use form, then you can use name, address, ...
You can use onkeyup when you have more than one input field. Suppose you have four or input. Then
document.getElementById('something').value is annoying. We need to write four lines to fetch the value of an input field.
So, you can create a function that store value in object on keyup or keydown event.
Example:
<div class="container">
<div>
<label for="">Name</label>
<input type="text" name="fname" id="fname" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Age</label>
<input type="number" name="age" id="age" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Email</label>
<input type="text" name="email" id="email" onkeyup=handleInput(this)>
</div>
<div>
<label for="">Mobile</label>
<input type="number" name="mobile" id="number" onkeyup=handleInput(this)>
</div>
<div>
<button onclick=submitData()>Submit</button>
</div>
</div>
JavaScript:
<script>
const data = { };
function handleInput(e){
data[e.name] = e.value;
}
function submitData(){
console.log(data.fname); // Get the first name from the object
console.log(data); // return object
}
</script>
function handleValueChange() {
var y = document.getElementById('textbox_id').value;
var x = document.getElementById('result');
x.innerHTML = y;
}
function changeTextarea() {
var a = document.getElementById('text-area').value;
var b = document.getElementById('text-area-result');
b.innerHTML = a;
}
input {
padding: 5px;
}
p {
white-space: pre;
}
<input type="text" id="textbox_id" placeholder="Enter string here..." oninput="handleValueChange()">
<p id="result"></p>
<textarea name="" id="text-area" cols="20" rows="5" oninput="changeTextarea()"></textarea>
<p id="text-area-result"></p>
<input id="new" >
<button onselect="myFunction()">it</button>
<script>
function myFunction() {
document.getElementById("new").value = "a";
}
</script>
One can use the form.elements to get all elements in a form. If an element has id it can be found with .namedItem("id"). Example:
var myForm = document.getElementById("form1");
var text = myForm.elements.namedItem("searchTxt").value;
var url = "http://www.myurl.com/search/" + text;
Source: w3schools
function searchURL() {
window.location = 'http://www.myurl.com/search/' + searchTxt.value
}
So basically searchTxt.value will return the value of the input field with id='searchTxt'.
Short Answer
You can get the value of text input field using JavaScript with this code: input_text_value = console.log(document.getElementById("searchTxt").value)
More info
textObject has a property of value you can set and get this property.
To set you can assign a new value:
document.getElementById("searchTxt").value = "new value"
Simple JavaScript:
function copytext(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
}

javascript function Math.pow taking decimal value from an input text

I searched a lot on the web on this, but I've not found anything that would help me.
I did this:
montante <input type='text' id='A' onkeyup='calcola()' value='15000' /><br />
tasso <input type='text' id='i' onkeyup='calcola()' value='0.07' /><br />
anni <input type='text' id='n' onkeyup='calcola()' value='6' />
<script>
var A = document.getElementById('A').value;
var n = document.getElementById('n').value;
var float i = document.getElementById('i').value;
var R = A / ((1 - Math.pow((1 + i), -n)) / i);
document.write(R);
</script>
This works well if you declare the three variables normally, but if you take the values from an input the script does not give the correct answer...
I think the problem is in the function Math.pow that does not recognize the "i" var as a number cause of the dot in the input...
I need this working with the inputs, any help?
Thanks in advance
The type of the value that is read from your html input-elements will be determined by javascript as a String.
If you use the + operator on a variable of type number and a variable of type String, Javascript will perform a string-concatenation:
var a = "1";
var b = 2;
var c = a + b;
Var c will get the value: "12"
To prevent this behavior you have to to parse the value of your input first. You can do this by using the Javascript parseFloat() function.

parseInt returns NaN

spent 45min trying figure why it returns NaN, please point me to the right direction.
My code is:
<form name="calc">
<input type="text" value="0" name="first" onchange="add()">
<input type="text" value="0" name="second" onchange="add()">
<input type="text" name="result" onchange="add()">
</form>
<script type="text/javascript">
var a = parseInt(document.calc.first.value);
var b = parseInt(document.calc.second.value);
var c = a + b;
function add(){
document.calc.result.value = parseInt(c);
}
</script>
You're looking for:
function add() {
var a = parseInt(document.calc.first.value, 10);
var b = parseInt(document.calc.second.value, 10);
var c = a + b;
document.calc.result.value = c;
}
You have to re-read a and b values each time they're changed.
Note 1: Also, remember about radix parameter in parseInt(val, radix). It's 10 in your case (as I suppose). See this MDN article on why that's important.
Note 2: no need to call parseInt(c), because c is already of the type number.
a and b are calculated once at page load, when the form is still empty, obviously the result will be NaN.
Put all the logic in the add function, so you retrieve the current state of the form.

Javascript calculation letters and numbers

<SCRIPT Language = JavaScript>
function calculate() {
a = 12
b = eval(document.form.number.value)
c = 5J7S
d = (a + b + c)
alert(d)
}
</SCRIPT>
<FORM NAME = form>
Phone: <INPUT TYPE = text SIZE = 3 value ="">
-
<INPUT TYPE = text name = number SIZE = 3 value ="">
-
<INPUT TYPE = text SIZE = 4 value ="">
<P>
<Input Type = Button NAME = b1 VALUE = "Grab Code" onClick = calculate()
</FORM>
5JG7S (Fixed Value)
5+7=12 (Added both numbers from Fixed Value)
Phone number 123-456-7890
4+5+6=15 (Prefix added together)
12+15=27 (Added numbers from the Fixed Value and the numbers that were added from the prefix)
27+5JG7S=275JG7S (Those numbers were added to the beginning of the orginal Fixed Value)
Now this Script that I have:
a is the added numbers from the Fixed Value
b is the input from the form(phone number)
c is the Fixed Value
d is adding each one up so they will display the code as an alert.
Now, if I take out c and just add a and b it performs the addition, if c is in there, it stops the process and produces nothing.
My question is, how do we add the calculated number and append it to the beginning of the fixed value?
Also, the addition works, but not the way I want it to, I want to add the 3 numbers together, the javascript adds 456+12= 468
I know this is very simple code, I am not familiar with Javascript programming and I pretty much pieced together what I found from searching.
I hope this makes sense, if this is not possible I understand.
Thanks!
using parseInt on the values should help with the math. your results are currently inaccurate because the form values are strings: rather than adding numbers you are concatenating strings.
i changed your 'number' input to have an ID attribute, so that you can select with getElementById and replaced the eval call with a call to parseInt.
the value of c in the calculate function needs to be corrected though, not sure what you meant but that will generate an error.
other various HTML tidyness issues (nothing that would break, just easier to read IMHO).
<script type="text/javascript">
function calculate() {
var a = 12;
var b = parseInt(document.getElementById("number").value);
// var c = 5J7S;
var d = (a + b + c);
alert(d);
}
</script>
<form name="form">
Phone: <input type="text" size="3" value=""/>
-
<input type="text" name="number" id="number" size="3" value=""/>
-
<input type="text" size="4" value=""/>
<p>
<input type="button" name="b1" value="Grab Code" onclick="calculate()">
</p>
</form>
hope that helps! cheers.

Reading numbers from inputs with JavaScript always returns NaN

I want to create a calculator which simply sums 2 fields up. But whatever I try it does not work. It also returns "NaN", also if I use parseInt().
Here's the code:
<script type="text/javascript" language="Javascript">
function doSum()
{
var a = document.getElementsByName("a").value;
var b = document.getElementsByName("b").value;
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
Sorry for that noob question, but what I'am doing wrong?
Thanks for any help!
Give ids to your inputs and identify them uniquely using document.getElementById. Then, obtain their decimal int values using parseInt with the radix parameter set to 10 and display the result as you currently do.
<script type="text/javascript" language="Javascript">
function doSum()
{
var a = parseInt(document.getElementById("a").value, 10);
var b = parseInt(document.getElementById("b").value, 10);
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input type="text" id="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input type="text" id="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
getElementsByName returns a list of elements and you'd have to refer to the one you want through an index, even if the list contains only one element.
getElementById on the other hand, returns an uniquely identified element, by its id.
use getElementById and give each of those an Id. getElementsByName returns an array. By the way.. it's not a bad question. It's a common error-- one that is addressed in a way by using jQuery which deals in wrapped sets.
getElementsByTagName returns a node list:
function doSum()
{
var a = document.getElementsByName("a")[0].value;
var b = document.getElementsByName("b")[0].value;
var sum = parseInt(a, 10) + parseInt(b, 10);
document.getElementById("sum").value = sum;
}
So you will need to index it. In addition in order not to do a string concate, parseInt with radix 10 is needed. Unless you plan to accept octal values in your calculator.
getElementsByName returns multiple elements, hence the plural Elements. You need to get the property of the first element found:
var a = document.getElementsByName('a')[0].value;
getElementsByName returns a NodeList: this is a set of all the elements found with that name. It is like an array in that you can use numeric indexes (like [0]) to access the elements found and in that there is a length property; no other array-like functionality is available.
Furthermore, the value property will always be a string if it is set. The + operator is the addition operator when the values are numbers; if they are strings, it is the concatenation operator. "1" + "2" is equal to "12" in Javascript. You need to use parseInt to convert them to numbers:
var a = document.getElementsByName('a')[0].value;
a = parseInt(a, 10); // parse as a number in base 10
Fields in JavaScript are all strings you need int, also .getElementsByName returns an array, you probably need the first element, so:
var a = parseInt(document.getElementsByName("a")[0].value, 10);
var b = parseInt(document.getElementsByName("b")[0].value, 10);
getElementsByName returns an array which gives you the wrong data type for what you are trying to do.
try:
function doSum()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var sum = a + b;
document.getElementById("sum").value = sum;
}
</script>
<form action="" method="POST">
<br/>a:<br/>
<input id="a" type="text" name="a" onblur='doSum()' value="0" size="5" />
<br/>b:<br/>
<input id="b" type="text" name="b" onblur='doSum()' value="0" size="5" />
<br/>Ergebnis<br/>
<input type="text" id='sum' value='' size="50" disabled/>
</form>
OK, two issues, your a fetching the valurs of a and b using getElementsByName which returns an array of values (since there could be many). Use getElementsById and put ids in the HTML.
Also the value properties will be strings so you will need to convert to numbers before doing your addition.
a and b are strings so :
function doSum()
{
var a = parseInt(document.getElementsByName("a").value);
var b = parseInt(document.getElementsByName("b").value);
var sum = a + b;
document.getElementById("sum").value = sum;
}

Categories