Grabbing User Input - javascript

First name: <input type="text" name="firstname"></input>
<input type="submit" value="Submit" />
Let's say I have the simple form above. How would I grab what the user inputted in the First Name field in JS. I tried:
document.getElementsByTagName("input")[1].onclick = function() {
inputted = document.getElementsByTagName("input")[0].innerHTML;
}
But that doesn't work. How would I do this?

Use value for text inputs:
inputted = document.getElementsByTagName("input")[0].value;
Also make sure to add var keyword to your variables so that you don't create a global variable:
var inputted = document.getElementsByTagName("input")[0].value;
You should also not put closing </input> tag since it is self-closing tag:
<input type="text" name="firstname" />
By the way you can also get elements value using below syntax:
formName.elementName.value;
Or
document.forms['formName'].elementName.value;
In your case it would be:
var inputted = formName.firstname.value;
Or
var inputted = document.forms['formName'].firstname.value;
Replace formName with whatever name is of your <form> element.
Lastly you can also get element's value if you apply id to it:
<input type="text" name="firstname" id="firstname" />
and then use getElementById:
var inputted = document.getElementById('firstname');

var inputs=document.getElementsByTagName("input"),
i=inputs.length;
//
while(i--){
inputs[i].onclick=myClickEventHandler;
};
//
function myClickEventHandler(evt){
var myVal;
switch (this.name) {
case 'firstname':
myVal = this.value;
break;
};
};

If you are using a form, you could try something like this instead :
var input = document.forms["formName"]["fieldName"].value;
Else, make use of the .value attribute :
var input = document.getElementsByTagName("input")[0].value;

Related

how to remember inputs value by using local storage?

I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.
here is the HTML code
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
and here is javascript
<script type="text/javascript">
var nameArr = ["name"];
var inputs = document.getElementsByName('name');
inputs.forEach(function(el){
el.value = getSavedValue(el);
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
</script>
if there is a way to solve this problem please tell me.
and if there is a way to do that with jquery I will be thankful to tell me that.
Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.
Secondly use a common class inputs in this case and give separate name to each element.
Then get all the elements with same class, iterate through it and get value of name property using getAttribute. Use this value to check if there exist a key in localStorage
var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
console.log()
el.value = getSavedValue(el.getAttribute('name'));
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
<input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" />
On your code you are passing the input object as a parameter instead of its name (or value; you choose). As localStorage only stores String key-value pairs, it won't work as you're trying to find a key that is an object.
in the forEach instead of:
el.value = getSavedValue(el);
set:
el.value = getSavedValue(el.name);
or let the "getSavedValue" function accept an object as parameter, but to access localStorage you must pass a string as the key.

How to assign variable to value attribute in input element?

I need to assign variable to value attribute in the input element
Here is my input tag.
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" value="myValue">
Here is my variable.
var myValue = document.getElementById('userVal');
Anyone, please help me to fix this problem?
You can set input default value. You can not bind myValue in the html without some js framework. To get input value use change event. Check my code snippet.
var input = document.getElementById('Name');
var myValue = 'Name example';
input.value = myValue;
var myFunction = function (e) {
console.log(e.target.value);
}
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" onchange="myFunction(event)" value="myValue">
ASSIGN INPUT VALUE TO VARIABLE:
You need to assign the variable to the element's value, not the element itself. Also, your current input id is Name, not userVal. Change that to userVal then retrieve the value like this:
var myValue = document.getElementById('userVal').value;
Check the following Code Snippet for a practical example on how to retrieve an input value and assign it to a variable:
/* JavaScript */
document.querySelector("button").addEventListener("click", function() {
var myValue = document.getElementById('userVal').value;
alert(myValue);
})
<!-- HTML -->
<input type="text" id="userVal" class="form-control form-control-alternative" placeholder="Username">
<button>Check Value</button>
ASSIGN VARIABLE TO INPUT VALUE:
To assign your input element's value to a variable, just reverse the above assignment like this:
var newValue = newValue;
document.getElementById('userVal').value = newValue;
Check the following Code Snippet for a practical example on how to assign a variable to your input element's value attribute:
/* JavaScript */
document.querySelector("button").addEventListener("click", function() {
var newValue = "newValue";
document.getElementById('userVal').value = newValue;
});
<!-- HTML -->
<input type="text" id="userVal" class="form-control form-control-alternative" placeholder="Original" value="myValue">
<br /><br />
<button>Change Value</button>
if you want to assign value to this input:
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" value="myValue">
you should use this code:
var myValue = document.getElementById('userVal').value;
document.getElementById("Name").value = myValue;
You can look to the documentation and example here:
https://www.w3schools.com/jsref/prop_text_value.asp
In JavaScript, add value property to your code as:
var myValue = document.getElementById("name").value
In HTML, use the same id to refer the input tag as:
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Usernam" value="myValue">

How to assign some value to input tag

I need to put some value to element.
Here is my code snippet.
var userId = localStorage.getItem('keyName');
var Name = document.getElementById('Name');
var dbRefName = firebase.database().ref().child('Web App').child('Users').child(userId).child('Name');
dbRefName.on('value', snap => Name.innerText = snap.val());
I am trying to assign this Name value using id to the input element shown as below.
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Username" >
It can assign using id to <span> elements. But it is not working with <input> elements.
Could anyone please help me on this matter?
Use .value instead of .innerText for <input> elements, like so:
document.getElementById('input').value = 'foo'
<input id="input"></input>
Input HTML elements needs name tag, and the way to assign it a value is by the value tag or by .value in Javascript
var input = document.getElementById('name');
//input.value = localStorage.getItem('keyName');
input.value = 5;
<input type="number" name="name" id="name" placeholder="Your name here" value="1">

How to insert the value of input to another inputs in JS?

Why can't I insert the value of an input into another input? The following example doesn't work:
document.getElementById("input").oninput = () => {
const input = document.getElementById('input');
const output = document.getElementById('output');
// Trying to insert text into 'output'.
output.innerText = input.value;
};
<input id="input" placeholder="enter value of temperature" />
<br>
<input id="output" />
Thank you!
You should use .value instead of .innerText to set the value to an input element, like:
output.value = input.value;
document.getElementById("input").oninput = () => {
const input = document.getElementById('input');
const output = document.getElementById('output');
output.value = input.value;
};
<input id="input" placeholder="enter value of temperature" />
<br>
<input id="output" />
may be this will be helpful. as per my knowledge. your code will not work on IE. because arrow functions are not supported in IE. however error in your code is "value1.innerText" which is not a right property. because in your code you can see.
value1.innerText=currentValue.value
so if you are fetching value using 'value' property of input. you have to assign a same property for another input box.
so function will be something like this.
var convertTemperature = function convertTemperature() {
var currentValue = document.getElementById("currentValue");
var value1 = document.getElementById("value1");
value1.value = currentValue.value;
};
You can get real time value by below code,
jQuery('input#currentValue').change(function(){
var current_value = jQuery('input#currentValue').val();
jQuery('input#value1').val(current_value );
});

Format input text to uppercase

I'm begginer and I would like to build an event that started on change of input. The text entered in the input would be automatically formatted as follows:
The first letter must always be uppercase;
All other letters must be lowercase.
function formating() {
var nameOfPerson = document.getElementById("nameOfPerson").textContent;
var nameOfPerson = nameOfPerson[0].toUpperCase() + (nameOfPerson - nameOfPerson[0]);
document.getElementById("nameOfPerson").textContent = nameOfPerson;
}
<input type="text" id="nameOfPerson" onchange="formatting()" placeholder="type your name">
Try this:
function formatting() {
var nameOfPerson = this.value;
if (nameOfPerson.length > 0) {
nameOfPerson = nameOfPerson[0].toUpperCase() + nameOfPerson.substr(1).toLowerCase();
this.value = nameOfPerson;
}
}
<input type="text" id="nameOfPerson" onchange="formatting.call(this)" placeholder="type your name">
If you want to do this using CSS, then this is the tricks:
<input type="text" id="nameOfPerson" placeholder="type your name" style="text-transform: capitalize;">
CSS text-trasform property can change your input text as capitalize, lowercase and uppercase.
A simple way to achieve this is:
nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1);
When to do it?
Blur
You can do it when input looses focus(blur) event. This will allow user to input in any format and when he is done, then you apply your formatting.
function formatting() {
var nameOfPerson = this.value
this.value = nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1).toLowerCase();
}
var input = document.getElementById("nameOfPerson");
input.addEventListener('blur', formatting)
<input type="text" id="nameOfPerson" placeholder="type your name">
Input
Or you can enforce formatting using input event. This will take care of typing and pasting actions.
function formatting() {
var nameOfPerson = this.value
this.value = nameOfPerson.charAt(0).toUpperCase() + nameOfPerson.substring(1).toLowerCase();
}
var input = document.getElementById("nameOfPerson");
input.addEventListener('input', formatting)
<input type="text" id="nameOfPerson" placeholder="type your name">
Pointers
Avoid binding handlers in HTML. Anyone can change DOM using dev tools and change behaviour of your page.
textContent as name suggest is used for text bindings and will return static text. Inputs have value binding and you should use .value
When you use onclange="formatting()", handler will not have context pointing to element and you will have to fetch it again and again and DOM queries are expensive. Using .addEventListener() will bind context and is preferred as you can add more than 1 handler.
In (nameOfPerson - nameOfPerson[0]), - operator will convert value to numeric value and would yield NaN. When dealing with strings, use string helper functions.

Categories

Resources