I have multiple buttons I would like to increment a value in different corresponding inputs. I am able to get all the buttons working but they only effect the first input. I realize I can write out three different functions for each button but I know there is a way to utilize one function. Thank you for any help in advance!
Here is code for reference:
let submit = document.querySelectorAll(".submit");
let num = document.querySelector(".num");
submit.forEach((btn)=>{
btn.addEventListener("click", increment);
});
let value = 0;
function increment(){
value +=1;
num.value = value;
}
<div class="container">
<div class="main">
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
</div>
</div>
Select the next sibling and select the input.
const submit = document.querySelectorAll(".submit");
submit.forEach((btn) => {
btn.addEventListener("click", increment);
});
function increment() {
const inp = this.nextElementSibling.querySelector("input");
inp.value = Number(inp.value) + 1;
}
<div class="container">
<div class="main">
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
</div>
</div>
That's how i would do it - basically in your "submit" buttons you create attribute (in this case "for" (see EDIT)) that will point to id of input to be incremented. This gives you full flexibility, no matter what html you have.
EDIT
Better use custom attribute, for example data-for, button doesn't have for attribute, as pointed in the comments below
let submit = document.querySelectorAll(".submit");
submit.forEach((btn)=>{
btn.addEventListener("click", increment);
});
function increment(ev){
let targetInputId = ev.target.getAttribute("data-for");
let targetInput = document.getElementById(targetInputId);
targetInput.value = parseInt(targetInput.value) + 1;
}
<div class="container">
<div class="main">
<button data-for="num1" class="submit">Submit</button>
<div class="withinDiv"><input id="num1" type="number" class="num" value="0"></input> </div>
<button data-for="num2" class="submit">Submit</button>
<div class="withinDiv"><input id="num2" type="number" class="num" value="0"></input> </div>
<button data-for="num3" class="submit">Submit</button>
<div class="withinDiv"><input id="num3" type="number" class="num" value="0"></input> </div>
</div>
</div>
Related
Can anyone explain why the "onclick" part won't fire?
function displayHello() {
let helloName = document.getElementByID('helloNameInput').value;
// prints out the variable, to the button >>
document.getElementByID("helloNameOutput").textContent = helloName
}
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input type="text" class="form-control" name="helloNameInput" id="helloNameInput" placeholder="Enter a name" />
</div>
<!--Name output-->
<p class="lead" id="helloNameOutput"> </p>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello()">Display Hello!</button>
<button class="btn btn-danger" id="clearButton" onclick="clearName()">Clear</button>
</div>
PS:
I'm just learning JS, so, I'm not too familiar with a lot of stuff yet. (We just finished the HTML stuff last semester)
not getElementByID. use getElementById.
function displayHello() {
let helloName = document.getElementById('helloNameInput').value;
// prints out the variable, to the button >>
document.getElementById("helloNameOutput").textContent = helloName
}
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input type="text" class="form-control" name="helloNameInput" id="helloNameInput" placeholder="Enter a name" />
</div>
<!--Name output-->
<p class="lead" id="helloNameOutput"> </p>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello()">Display Hello!</button>
<button class="btn btn-danger" id="clearButton" onclick="clearName()">Clear</button>
</div>
It does work, you just had a typo with getElementByID, it should be getElementById
function displayHello() {
let helloName = document.getElementById('helloNameInput').value;
// prints out the variable, to the button >>
document.getElementById("helloNameOutput").textContent = helloName
}
<!--Name input-->
<div class="mb-3">
<label for="helloNameInput" class="form-label">Name:</label>
<input type="text" class="form-control" name="helloNameInput" id="helloNameInput" placeholder="Enter a name" />
</div>
<!--Name output-->
<p class="lead" id="helloNameOutput"> </p>
<!--Display Hello! & Reset buttons-->
<div>
<button class="btn btn-primary" id="displayHelloButton" onclick="displayHello()">Display Hello!</button>
<button class="btn btn-danger" id="clearButton" onclick="clearName()">Clear</button>
</div>
In case others run into this same issue, I've uploaded a screenshot of the "git change log", that has all the corrections to the above, so that it worked as intended. ^_^
I've created a clone function on html file. But there's a weird error in code. when I put two ending 'div' in same line, the JavaScript code just work fine. but when I beautify html code or put the last ending tag in another line, the JavaScript just doesn't work. please look at the commented line
<body>
<div class="container">
<div class="col-2 m-3 bg-primary" id="show">working</div>
<button id="bt" class="btn btn-outline-primary ml-4 mt-2" onclick="hide()">remove</button>
<div id="error" class="text-danger ml-3"></div>
<div id="myList" style="list-style-type:none;" class="mt-3">
<div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Recipient's username"
aria-label="Recipient's username" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon2"
onclick="removeIt()">X</button>
</div>
</div>
</div></div> <!-- this line is causing issue -->
<button onclick="addElement()" class="btn btn-outline-primary ml-4 mt-2">Add</button>
<div class="form-check">
<label class="form-check-label" for="numbers">
Number Of Row
</label>
<input type="number" class="form-input" name="" id="numbers" value="1">
</div>
<button onclick="passNumber()" class="btn btn-primary btn-lg" >Go</button>
</div>
<script>
let error = document.getElementById('error');
function passNumber(){
let numbers = document.getElementById('numbers').value;
for(let i = 1; i <= numbers; i++){
addElement();
}
}
function hide() {
document.getElementById('show').style.display = 'none';
}
function addElement() {
error.innerHTML = '';
let item = document.getElementById('myList').lastChild;
let cln = item.cloneNode(true);
document.getElementById('myList').appendChild(cln);
}
function removeIt() {
let list = document.getElementById('myList');
if(list.childNodes.length == 2){
error.innerHTML=`you cant delete the last input box`;
}else{
let length = list.childNodes.length;
list.removeChild(list.childNodes[length-1]);
}
}
</script>
this code works fine. but when I change the code into below lines, then the JavaScript just don't work at all -
<body>
<div class="container">
<div class="col-2 m-3 bg-primary" id="show">working</div>
<button id="bt" class="btn btn-outline-primary ml-4 mt-2" onclick="hide()">remove</button>
<div id="error" class="text-danger ml-3"></div>
<div id="myList" style="list-style-type:none;" class="mt-3">
<div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Recipient's username"
aria-label="Recipient's username" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon2"
onclick="removeIt()">X</button>
</div>
</div>
</div>
</div> <!-- this line is causing issue -->
<button onclick="addElement()" class="btn btn-outline-primary ml-4 mt-2">Add</button>
<div class="form-check">
<label class="form-check-label" for="numbers">
Number Of Row
</label>
<input type="number" class="form-input" name="" id="numbers" value="1">
</div>
<button onclick="passNumber()" class="btn btn-primary btn-lg" >Go</button>
</div>
<script>
let error = document.getElementById('error');
function passNumber(){
let numbers = document.getElementById('numbers').value;
for(let i = 1; i <= numbers; i++){
addElement();
}
}
function hide() {
document.getElementById('show').style.display = 'none';
}
function addElement() {
error.innerHTML = '';
let item = document.getElementById('myList').lastChild;
let cln = item.cloneNode(true);
document.getElementById('myList').appendChild(cln);
}
function removeIt() {
let list = document.getElementById('myList');
if(list.childNodes.length == 2){
error.innerHTML=`you cant delete the last input box`;
}else{
let length = list.childNodes.length;
list.removeChild(list.childNodes[length-1]);
}
}
</script>
lastChild is the last child node of any kind, including text nodes. By moving the closing </div> tag, you're adding a text node.
You could use lastElementChild instead to get only the last element in the list.
Here's a simplified example:
console.log(document.getElementById("container1").childNodes.length); // 2
console.log(document.getElementById("container2").childNodes.length); // 3
<div id="container1">
<div>x</div></div>
<div id="container2">
<div>x</div>
</div>
Side note: Your HTML is invalid. div elements cannot be direct children of ul elements. ul elements are expected to contain li elements as their only direct (element) children.
I got a problem I need to fill two fields in a form with diffrent values and I would like to do that with an button onClick function.
I genererat buttons and the output looks like this:
<button class="btn btn-primary" type="button" onclick="fillsquare(test, 1)">1</button>
<button class="btn btn-primary" type="button" onclick="fillsquare(test2, 3)">1</button>
Now I want to fill my form with the values
the first value I want to be placed in the first field id="areaname_fill" and the secound value should fill the field id="squarename_fill".
Just to clarify, If I click on the first button
id="areaname_fill" should set the value to "Test" AND
id="squarename_fill" should set the value to 1.
<div class="form-group">
<label>fyll i område</label>
<input type="text" name="areaname_fill" id="areaname_fill" class="form-control" value="" />
</div>
<div class="form-group">
<label>fyll i rutans nummer</label>
<input type="text" name="squarename_fill" id="squarename_fill" class="form-control" value="" />
</div>
I came up with this JS but I can't get it to work, any ides?
function fillsquare(area,square)
{
var area = area;
var square = square;
document.getElementById(areaname_fill).value = area;
document.getElementById(squarename_fill).value = square;
}
You can achieve it in this way
document.getElementById("areaname_fill").value=area;
document.getElementById("squarename_fill").value=square;
And here
<button class="btn btn-primary" type="button" onclick="fillsquare('test', 1)">1</button>
<button class="btn btn-primary" type="button" onclick="fillsquare('test2', 3)">1</button>
function fillsquare(area,square)
{
document.getElementById("areaname_fill").value = area;
document.getElementById("squarename_fill").value = square;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>fyll i område</label>
<input type="text" name="areaname_fill" id="areaname_fill" class="form-control" value="">
</div>
<div class="form-group">
<label>fyll i rutans nummer</label>
<input type="text" name="squarename_fill" id="squarename_fill" class="form-control" value="">
</div>
<button class="btn btn-primary" type="button" onclick="fillsquare('test', 1)">1</button>
<button class="btn btn-primary" type="button" onclick="fillsquare('test2', 3)">1</button>
It's generally recommended that you avoid using inline javascript like onClick="foo"
If possible, you should change your markup to to include the values in the button markup and then add a click event listener to extract and the data and use it in the form. Here's an example of that.
const buttons = document.querySelectorAll("button");
const areaField = document.getElementById("areaname_fill");
const squareField = document.getElementById("squarename_fill");
buttons.forEach(button => {
button.addEventListener("click", () => {
areaField.value = button.dataset.area;
squareField.value = button.dataset.square;
});
});
<div class="form-group">
<label>fyll i område</label>
<input
type="text"
name="areaname_fill"
id="areaname_fill"
class="form-control"
value=""
>
</div>
<div class="form-group">
<label>fyll i rutans nummer</label>
<input
type="text"
name="squarename_fill"
id="squarename_fill"
class="form-control"
value=""
>
</div>
<button class="btn btn-primary" type="button" data-area="test" data-square="1">
First button
</button>
<button class="btn btn-primary" type="button" data-area="test2" data-square="3">
Second button
</button>
Try the below code. The quotes are missing in onclick and in the document.getElementById as the test and test2 are string, and the document.getElementById expects a string argument (the element id).
function fillsquare(area, square) {
var area = area;
var square = square;
document.getElementById("areaname_fill").value = area;
document.getElementById("squarename_fill").value = square;
}
<body>
<button
class="btn btn-primary"
type="button"
onclick="fillsquare('test', 1)"
>
1
</button>
<button
class="btn btn-primary"
type="button"
onclick="fillsquare('test2', 3)"
>
1
</button>
<div class="form-group">
<label>fyll i område</label>
<input
type="text"
name="areaname_fill"
id="areaname_fill"
class="form-control"
value=""
/>
</div>
<div class="form-group">
<label>fyll i rutans nummer</label>
<input
type="text"
name="squarename_fill"
id="squarename_fill"
class="form-control"
value=""
/>
</div>
document.getElementById("areaname_fill").value=area;
document.getElementById("squarename_fill").value=square;
You should Add double quotes to fix it.
<div class="row" align="center">
<input type="hidden" name="index" id="index" value="0">
<div class="tag">
<div class="tag with-color">
<div>
<label id="label"></label>
</div>
</div>
<div>
<input type="submit" name="next" class="btn btn-primary" value="NEXT" onclick="nextValue()"/>
</div>
</div>
</div>
<script type="text/javascript">
function getValue() {
var index = document.getElementById("index").value;
return "${wordList[index+1].word}";
}
function nextValue() {
document.getElementById("label").innerHTML = getValue();
}
window.onload = function(){
document.getElementById("label").innerHTML = "${wordList[0].word}";
}
I have a button and I want to show attribute of list model when I click button.
But I can't use "${wordList[index].word}". How can I fix it?
how can i take the parameter(number) on a bootstrap input element when i click on the button??
<form>
<div class="form-group">
<div class ="col-md-6 input-group">
<span class="input-group-addon">Larghezza</span>
<div id="myNumber"> <input type="number" class="form-control" id="focusedInput" placeholder="Inserisci qui..." > </div>
</div>
</div>
</form>
<button type="button" onclick="myFunction()" class="btn btn-default">Calcola</button>
my js code... Then i use the number for some math operation
function myFunction() {
var x = document.getElementById("myNumber").value;
You are reading value property of div element while it is a property of the input.
Use id of input and it will work.
function myFunction() {
var x = document.getElementById("focusedInput").value;
console.log(x);
}
<form>
<div class="form-group">
<div class ="col-md-6 input-group">
<span class="input-group-addon">Larghezza</span>
<div id="myNumber">
<input type="number" class="form-control" id="focusedInput" placeholder="Inserisci qui..." >
</div>
</div>
</div>
</form>
<button type="button" onclick="myFunction()" class="btn btn-default">Calcola</button>
var x = document.getElementById("focusedInput").value;
You need to reference the input element, not its container.