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.
Related
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;
}
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>
I would like to know how could I create many <input type=text /> tags with a loop in JS.
I need that loop to be linked to a first input (type=number), which tell to the loops how many input text to create.
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input[type=text]");
newForm.id = "form"+i
document.body.appendChild(newForm);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="submit" value="Envoyer" id="ok" onclick="getP()">
</form>
Direct answer to your question:
<script type="text/javascript">
function getP() {
var nbP = +document.getElementById("nombreP").value;
var inputContainer = document.getElementById("inutContainer");
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.setAttribute("type", "text");
newForm.setAttribute("id", "form"+i);
inputContainer.appendChild(newForm);
inputContainer.appendChild(document.createElement("br"));
}
}
</script>
<form>
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok" onclick="getP()">
<div id="inutContainer">
</div>
</form>
BUT: this is good question to learn about Javascript and HTML, but bad to create powerfull UI. To implement modern UI in JS/HTML i am strongly recommend to learn more abou next technologies:
https://reactjs.org/ or https://angular.io/ or https://vuejs.org/
I hope it helps:
document.querySelector('#ok').addEventListener('click', getP)
function getP(event) {
let inputsQtt = document.querySelector('input[type=number]').value
for (let i = 0; i < inputsQtt; i++) {
let input = document.createElement("input");
document.body.appendChild(input);
}
}
<form method="get">
<input type="number" name="nombrePlat" id="nombreP">
<input type="button" value="Envoyer" id="ok">
</form>
There are few problems with your code
First: syntax error, you are missing 1 curly bracket } to close function.
And second and more important as you click on button it causes to submit form and refreshes the page.To solve this you just need to change type of button from submit to button.
And also you can not use "input[type=text]" to create element.You can just create an element with following code
function getP () {
var nbP = Number(document.getElementById("nombreP").value);
for (var i = 0; i < nbP; i++) {
var newForm = document.createElement("input");
newForm.id = "form"+i;
newForm.setAttribute("type","text");
document.body.appendChild(newForm);
}
}
Here's a slightly different approach, that involves adding a wrapper container within your form.
function updateForm() {
var parent = document.getElementById('inputs'),
count = document.getElementById('inputCount').value || 0;
parent.innerHTML = '';
for (let i = 0; i < count; i++) {
parent.innerHTML += `<input placeholder="text input ${i+1}" name="form${i+1}" id="form${i+1}" /><br>`;
}
}
<form method="get" name="inputForm">
<input min="0" type="number" name="inputCount" id="inputCount">
<div id="inputs">
<!-- container for dynamic inputs -->
</div>
</form>
<!-- Notice inputs can also be associated to form with `form` attribute -->
<input form="inputForm" type="submit" value="Make" id="ok" onclick="updateForm()">
I have HTML code with some JS as follows:
<form>
Object: <input type="text" name="object">
<br>
brand: <input type="text" name="brand">
<br>
<br>
color: <input type="text" name="color">
<br>
<input type="submit" value="Submit"onclick="doTest()">
</form>
<h3>Results</h3>
formValues.object = <span id="object"></span><br>
formValues.brand = <span id="brand"></span><br>
formValues.color = <span id="color"></span><br>
<script id="jsbin-javascript">
var formValues = {};
function inputObj(formNR, defaultValues) {
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
formValues[inputs[i].name] = defaultValues[i];
if(inputs[i].type === 'text') {
inputs[i].value = defaultValues[i];
document.getElementById(inputs[i].name).innerHTML = defaultValues[i];
}
inputs[i].addEventListener('keyup', function() {
formValues[this.name] = this.value;
document.getElementById(this.name).innerHTML = this.value;
}, false);
}
}
var defValues =['','',''];
inputObj(document.forms[0], defValues);
</script>
When the user inputs some text, this text becomes a variable. E.g there is a variable called "formValues.object". Then I want to take the value of this variable and write it onto a google sheet using the following code
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(" ");
}
The problem is that since the data I want to enter is a variable I do not know what I have to put between the .setValue brackets in order for the data the variable stores to appear in cell I2 of the google sheet when the submit button is pressed (I have already figured out how to link the submit button with the function).
If your value is an object and you want to put it into a single cell you will need to convert the variable to a string.
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('I2').setValue(JSON.stringify(MyVariable));
}
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())