increment localStorage object name to store data from inputs - javascript

This is for testing purposes only.
i'm trying to store data from 3 inputs (types: text,number) and store them in localStorage. which continuously increment every submit.
i seem to be overwriting value0, value1, value2 on the second submission instead of further incrementing to value3, value4, value5.
expected result:
first submit value0,value1,value2
second submit value3,value4,value5
third submit value6,value7,value8
etc.
JS:
document.getElementById('btn').addEventListener('click', createEntry());
function createEntry(){
const inputs = document.getElementsByTagName("input");
let i;
for (i = 0; i < inputs.length; i++) {
let value = inputs[i].value;
localStorage.setItem(`value${i}`, JSON.stringify(value));
}
};
gather all input by grabbing all input tags, loop through found elements. assign new statement to looped values and store them in localStorage. increment the item name to avoid overwriting the previously looped item.
HTML:
<div class="form">
<input type="text" required>
<input type="text" required>
<input type="number" min="1" max="120" required>
<button type="button" id="btn">Add</button>
</div>

The way you coded it will override the saved values because i always gets reset to 0 when the function runs. There are many different ways to re-write your code, one being the below:
Store the last index used
// By the way, there was an error in this line, you were calling createEntry()
// instead of passing the function as a callback.
document.getElementById('btn').addEventListener('click', createEntry);
function createEntry() {
const inputs = document.getElementsByTagName("input");
let i;
let index = getNextIndex();
for (i = 0; i < inputs.length; i++) {
let value = inputs[i].value;
localStorage.setItem(`value${index}`, JSON.stringify(value));
index++;
}
localStorage.setItem('nextIndex', index);
}
function getNextIndex() {
const index = localStorage.getItem('nextIndex');
return index ? parseInt(index) : 0;
}

Related

increment in the function name and id javascript

I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.

how to store dynamically created checked checkbox in array?

I am having dynamically created checkbox...
I want that checked value from the checkbox should be stored in one array...
I am Facing the following Problems...
*
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
If I alert the value of checkedvalue It given undefined
If I have console.log the final variable console.log(array); It given the
["on"] in the console.log if the value is checked.
I didn't get the actual value.My code is given below. I don't know what is the mistake I did. Anyone could you please help me.
Thanks in Advance
<input type="Submit" Value="add" onclick="searchinput()">
--------------
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue=document.querySelectorAll('input[type=checkbox]:checked');
alert(checkedvalue.value);
for (var i = 0; i < checkedvalue.length; i++) {
array.push(checkedvalue[i].value);
console.log(array);
}
}, false);
}
one of the problems you are facing is that
document.querySelectorAll('input[type=checkbox]:checked');
returns a NodeList and value is not a property on an NodeList object. That is why you are seeing "undefined" in your alert.
Changing as little of your code as possible, I think this should work:
function searchinput()
{
var li=document.createElement("li");
//creating checkbox
var label=document.createElement('label');
label.className="lab_style";
li.appendChild(label);
var check=document.createElement('input');
check.type="checkbox";
check.name="check_bo";
li.appendChild(check);
check.addEventListener('click', function() {
var array=[];
var checkedvalue = document.querySelectorAll('input[type=checkbox]:checked');
for (var i = 0; i < checkedvalue.length; i++) {
if(checkedvalue[i].checked) {
array.push(checkedvalue[i].value);
}
}
}, false);
}
If you have a form with a bunch of checkboxes and once the form is submitted you want to have the values of all the checkboxes which are checked stored in an array then you can do it like this.
const checkboxes = document.querySelectorAll("input[type=checkbox]");
const form = document.querySelector("form");
const arr = [];
form.addEventListener("submit", (e) => {
e.preventDefault()
checkboxes.forEach(chbox => {
if (chbox.checked) {
arr.push(chbox.value)
}
})
console.log(arr)
})
<form>
<label>Apple:
<input type="checkbox" value="apple" name="test"></label>
<label>Mango:
<input type="checkbox" value="mango" name="test"></label>
<label>Banana:
<input type="checkbox" value="banana" name="test"></label>
<label>Grape:
<input type="checkbox" value="grape" name="test"></label>
<button type="submit">Submit</button>
</form>

How do you make javascript(including function with array and return) write in div on button click without going to another page

I have had a lot of problems with this problem. When I console.log(sum); I get the answer I am looking for, but when I try to output the answer from a button click and an input field it does not work. I changed felt3.innerHTML=addnumber(ttt); to document.write(addnumber(ttt)); which made it work, but it is sending it to another page, which is something I do not want. How I can make this work:
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>
and:
var number = document.getElementById("number");
var felt3 = document.getElementById("tall3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
felt3.innerHTML=addnumber(ttt);
}
If I understand your question correctly, then the solution here is to update the argument that you are passing to getElementById("tall3"), rewriting it to document.getElementById("felt3");.
Doing this will cause your script to aquire the reference to the div element with id felt3. When your onclick event handler is executed, the result of addnumber() will be assigned to the innerHTML of the valid felt3 DOM reference as required:
var number = document.getElementById("number");
// Update this line to use "felt3"
var felt3 = document.getElementById("felt3");
var form3 = document.getElementById("form3");
var button3 = document.getElementById("button3");
var sum=0;
function addnumber(x){
var array = [];
array.push(x);
for (var i = 0; i < array.length; i++) {
sum=sum+array[i];
}
return sum;
}
button3.onclick=function(){
var ttt=Number(number.value);
// Seeing that felt3 is now a valid reference to
// a DOM node, the innerHTML of div with id felt3
// will update when this click event is executed
felt3.innerHTML=addnumber(ttt);
}
<form id="form3">
Tall:<input type="number" id="number"><br>
<input type="button" id="button3" value="plusse"><br>
</form>
<div id="felt3"></div>

Updating Values in HTML output based on changing input

I currently have a set of fields and radio buttons that take in some user input. Here is an example:
<div id="age">
<input type="number" name="age1" value=60>
</div>
I am displaying all the inputted values and want the display to change when the user modifies the input. This is my attempt:
var inputElements = document.querySelectorAll('input');
for(var i = 0, len = inputElements.length ; i < len ; i++) {
inputElements[i].addEventListener('input', updateDisplay());
}
function updateDisplay () {
console.log("test");
var age = document.querySelector('input[name="age1"]').value;
document.getElementById("ageComparison").innerHTML = age;
}
I know that the program enters the method since the "test" message is printed to the console; however, I don't see any change in display according to changes in input. Would appreciate any help.
While creating the eventlistener, you're just calling updateDisplay. Remove the ().
Also, you did not put '#ageComparison' element in your code.
html:
<div id="age">
<input type="number" name="age1" value=60>
</div>
<div id="ageComparison">
</div>
js:
var inputElements = document.querySelectorAll('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].addEventListener('input', updateDisplay);
}
function updateDisplay() {
console.log("test");
var age = document.querySelector('input[name=age1]').value;
document.getElementById("ageComparison").innerHTML = age;
}
Example: https://jsfiddle.net/m6r871t6/
Try avoiding the inner double quotes
var age = document.querySelector('input[name=age1]').value;
try using
inputElements[i].addEventListener('change', updateDisplay())

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

Categories