How can I access these form values? - javascript

I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.

There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>

Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>

getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`

Related

How to return the first character of a text input? [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();
}

How to convert Javascript numbers to a string and pass it to an input box

i'm stuck trying to convert feet to miles. here is my code so far:
function convertData() {
var distance = document.getElementById('distance').innerHTML;
var mile = 5280;
var result = distance /mile;
document.getElementById('distance').innerHTML = result;
};
and from the answer here, i'm trying to implement this to the
document.getElementById tag up in the beginning of the document found here..
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
..so when a user clicks that button, the data gets converted.
this is the default line when a user opens a page on first try:
any advice or thoughts?
function convertData() {
var distance = document.getElementById('distance').value;
var mile = 5280;
var result = distance / mile;
document.getElementById('answer').innerHTML = +result;
};
<div id="answer"></div>
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
I will recommend displaying the answer in another element, and leaving the input free for the user to make changes.
the simpliest way
html inputs with a type=number have the valueAsNumber property to directly process their numeric value.
(There is also a valueAsDate for those of type=date)
const
distance_el = document.getElementById('distance')
, mile = 5280
;
function convertData()
{
distance_el.valueAsNumber /= mile
}
<input type="button" value="Convert to Miles" onclick="convertData();">
<input id="distance" type="number" value="453454">
You should be getting/setting the input value property rather than the innerHTML.
The innerHTML property is used to return the HTML content of an element, while the value property is used to return the value of a text field.
function convertData() {
var distance = document.getElementById('distance').value;
var mile = 5280;
var result = distance / mile;
document.getElementById('distance').value = result;
};
<input type="button" value='Convert to Miles' onclick="convertData();">
<input id="distance" type="number" value=453454>
Simplified version:
function convertData(t) {
t.nextElementSibling.value = t.nextElementSibling.value/5280;
};
<input type="button" value='Convert to Miles' onclick="convertData(this);">
<input id="distance" type="number" value=453454>

failed: First argument "email" must be a valid string." javascript [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();
}

nodeChild.value is null and i dont know why [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 calculation using input and span fields

<input type="number" name="quantity" id="quantity">
<span id="price">4000</span>
<input type="text" value="" id="total" readonly>
<input type="button" value="calculate Total Price" onClick="calculate()">
I need values from field name="quantity" and id="price" above and calculate using javascript function and to display it in field id="total" only when I click calculate button. I tried the javascript function below but the result is showing as NaN.
function calculate(tot) {
var quan = document.getElementsByName('quantity').value;
var pri = document.getElementById('price');
var pr = parseInt(pri);
var tot = quan * pr;
document.getElementById("total").value = tot;
}
Whenever you see a method in plural, such as getElementsByName it gets multiple elements, or what we call a nodeList, and even if there's only one matching element, you still get a nodeList, and a nodeList has no value, you can access a nodeList like an array and get the first element in the list like :
var quan = document.getElementsByName('quantity')[0].value;
Also, getElementById gets an element, not a number, you'd have to get the innerHTML
var pri = document.getElementById('price').innerHTML;
and remember the radix for parseInt
parseInt(pri, 10)
not that you really need to parse it when you're multiplying
FIDDLE
You will need a for loop and iterate over every individual value and put that in a value. Like this:
for(i=0; i<quan.length; i++) {
var total+= quan[i];
}

Categories

Resources