On button click get values of many input fields with the same class and paste it inside different input fields with the same class using javascript

Viewed 136

Based on a previous question of mine here i have three input fields with the same css class price-input and i want after clicking on the button with the id set-price-btn to fill them with the input value displayed at the bottom of each input field using pure JavaScript.

The problem is that everytime i click the button, the variable videosize returns undefined. What I am doing wrong ?

var setpricebtn = document.getElementById("set-price-btn");

setpricebtn.addEventListener("click", () => {

var priceinputs = document.querySelectorAll("price-input");
var videosize = document.querySelectorAll("video-file-size").value;

for (var i = 0; i < videosize.value; i++) {
  var savedprice = videosize[i].value;
  priceinputs[i].value = savedprice;
}

  });
.toolbar {
width:100%;
overflow:hidden;
margin-bottom:30px;
}

.btn {
width:auto;
display:inline-block;
padding:10px;
text-align:center;
background:#e8e8e8;
cursor:pointer;
border-radius:4px;
font-weight:bold;
font-size:12px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="toolbar">
<div class="btn btn-primary" id="set-price-btn"> Set price to all fields </div>
</div>

<div class="row">

<div class="col-3 item">
<input name="price" placeholder="Enter price" class="price-input" value="" min="0" type="number">
<input name="uf" class="video-file-size" value="155" type="text">
</div>

<div class="col-3 item">
<input name="price" placeholder="Enter price" class="price-input" value="" min="0" type="number">
<input name="uf" class="video-file-size" value="185" type="text">
</div>

<div class="col-3 item">
<input name="price" placeholder="Enter price" class="price-input" value="" min="0" type="number">
<input name="uf" class="video-file-size" value="314" type="text">

</div>




</div>

2 Answers

Few things to remember:

This is how you query based on classes when using querySelector. You have to use a ..

videosize will be a live collection of HTML Nodes.



var priceinputs = document.querySelectorAll(".price-input"); 
var videosize = document.querySelectorAll(".video-file-size");

for (var i = 0; i < videosize.length; i++) {
  var savedprice = videosize[i].value;
  priceinputs[i].value = savedprice;
}

  });

You cannot do var videosize = document.querySelectorAll("video-file-size").value because document.querySelectorAll("video-file-size") returns a NodeList. See docs.

And either you use document.querySelectorAll(".video-file-size") or document.getElementsByClassName('video-file-size').

Related