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.
Related
I have a big html form with multiple email fields. What I want to do is make sure the user can't enter the same email in more than one field.
I have managed to detect duplication successfully by defining an array where each email value the user inputs is pushed to the array and that's where the comparison happens.
the problem happens when after detecting duplication I delete the value from the input field but the value still exists in the array so my function still returns that there is a duplicate value.
here is my function code:
var filledEmail = [];
var allEmailFields = $("form input[type='email']");
function checkIfArrayIsUnique(myArray) {
return myArray.length === new Set(myArray).size;
}
function addToEmails() {
allEmailFields = $("form input[type='email']");
filledEmail = [];
allEmailFields.each(function(){
var currentEmail = $(this);
currentEmail.bind('change',function() {
console.log("email value changed");
filledEmail.push(currentEmail.val());
console.log(filledEmail);
if (checkIfArrayIsUnique(filledEmail) == true) {
console.log("emails unique")
}
else {
console.log("emails not unique");
}
})
});
}
Any help would be so much appreciated.
This is how you could do it:
Attach change event listeners to each of your elements and check if the entered value exists. If it does not exist add it to your filledEmail array otherwise do nothing.
You will see that if you type the same name in different input element boxes it will not be added, hence will not appear as the output in the console
var filledEmail = [];
document.querySelectorAll("input[type='email']").forEach((mailField,i) => {
mailField.addEventListener("change", e => {
const email = e.target.value;
const hasMail = filledEmail.find(x => x === email);
if (!hasMail) {
filledEmail = filledEmail.filter((x, j)=> j!==i);
filledEmail.push(email);
}
console.log('filled mails without duplicates', filledEmail)
});
});
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />
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 );
});
i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again?
<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}
</script>
<input class="input_field2" type="text" readonly name="advance"
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">
You could keep a property on the read-only text field to keep the old value:
function B()
{
var adv = document.getElementById('advance'),
rec = document.getElementById('recamt');
if (typeof adv.oldvalue === 'undefined') {
adv.oldvalue = parseFloat(adv.value); // keep old value
}
adv.value = adv.oldvalue + parseFloat(rec.value));
rec.value = '';
return false;
}
You're calling the sum function every time the readonly input is focused using the new value. If you only want it to add to the original value, you need to store it somewhere.
HTML:
<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">
JS:
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onclick = function() {
this.value = parseFloat(originalValue) +
parseFloat(document.getElementById('recamt').value);
return false;
};
http://jsfiddle.net/hQbhq/
Notes:
You should bind your handlers in javascript, not HTML.
The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox.
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;
taking value in 1st textbox and want to display it in 2nd..
1st <input type="text" value=" " id = "marks1" name = "marks1" onblur = "myFunction('marks1')" />
2nd <input type="text" value=" " id = "marks2" name = "marks1" disabled = "disabled" />
and on oblur I am calling a function. Whenever I change the value from UI, on function call I am getting the old value i.e. ' ' instead of changed value.
in the variable "value" the old value which i am getting, i am unable to display it on 2nd textbox.
function myFunction( txtname )
{
alert("call");
var txtobj = document.getElementsByName(txtname);
var value = txtobj[0].value;
alert("my value : "+value);
txtobj[1].value = value;
}
I know the code is okay, but it is not working at me. Is there any other way?
Works for me:
function myFunction(element)
{
var txtobj = document.getElementsByName(element);
var value = txtobj[0].value;
txtobj[1].value = value;
}
http://jsfiddle.net/pwTwB/1/
Are you getting an error?
Try it this way:
function myFunction( txtname )
{
var txtobj = document.getElementById(txtname);
var target = document.getElementById("marks2");
target.value = txtobj.value;
}
Here is a simple way to set the next textbox's value.
function moveText(ele){
document.getElementById("marks2").value = ele.value;
}
Then use the following in your html markup
<input type="text" id="marks1" onblur="moveText(this)" />
<input type="text" id="marks2" disabled="disabled" />