failed: First argument "email" must be a valid string." javascript [duplicate] - javascript

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();
}

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 can I access these form values?

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>`

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

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 how to calculate values in dynamically added fields with multiple rows

I had one row with three fields: received, issue, balance
<input type="text" name="rcv" class="rcv"/>
<input type="text" name="issue" class="issue"/>
<input type="text" name="blnc" class="balance"/>
I calculated the balance for each row easily, but how do I calculate more than one row?
Each row has receive, issue and balance fields.
How do I calculate each row's balance field?
I tried like this for multiple row but it's not working:
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = $('.t_rcv').val();
var totalRtn = $('.t_rtn').val();
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
you need to parse The value of textbox as it returns string not int
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = parseInt($('.t_rcv').val()) || 0;
var totalRtn = parseInt($('.t_rtn').val()) || 0;
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
If your code is being run on document.ready it will only be applied to elements which exist at that point.
You'd be better with :
$(document).on('blur','.t_rtn, .t_rcv',function(){
var val = $(this).val();
...
});
try this..
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
In addition to parsing the string values into integers you also need to use the correct selectors for those input elements. t_rtn is not the right class name, for example. And if doing this in rows you will want to grab the correct element from the current row (you already did this correctly for the consume field)
Fixed html (Example.. I chose to use div with class name = row):
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
Fixed code:
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
I took the liberty of fixing some inconsistencies with the class names used. I tried to match them up to the variables for totalRcv and totalRtn so that now the balance shows as receipt minus return. If the user enters non-numeric data, it defaults the value to 0 before calculating.
Example fiddle here: http://jsfiddle.net/cp81g4nf/1/
I think problem is because you are subtracting 2 Strings. .val returns an String.
Convert them in number before subtracting like bellow
$('t_rtn').next('.consume').val((+totalRcv)-(+totalRtn));

Categories

Resources