0

In my code, I have an add function when user click on it. it will capture the user input value from the text and show. any idea how can I do it using javascript

var split = ['S','M', 'L'];
for (var i = 0; i < split.length; i++) {
  var t = document.getElementById('text-box');
  t.innerHTML += 'Size <input value=' + split[i] + ' type="text">Description<input type="text" name="vrow" id="price">'
}
function add(){
//get the description value

}
<div id="text-box">
</div>
<button onclick="add()">ADD</button>
RIyal
  • 35
  • 1
  • 5
  • It's not clear what you're asking. How can an input field hold multiple values? And what does the add() function do? And if it's just displaying values, why call it add() and not show(). Are you trying to confuse your future self (or colleagues)??? – Ted Nov 24 '20 at 05:56

3 Answers3

0

(Using Vanilla/plain JavaScript)

First add id attribute to field, like

First Name: <input type="text" name="f_name" id="f_name_id">

Then

document.getElementById("f_name_id").value

Make sure each field have a unique id.

Atul Bhosale
  • 396
  • 5
  • 13
0

If you wanna take the value of all inputs of description, can use a class, to get all and iterate

 var split = ['S','M', 'L'];
for (var i = 0; i < split.length; i++) {
  var t = document.getElementById('text-box');
  t.innerHTML += 'Size <input value=' + split[i] + ' type="text">Description<input type="text" class="description-input" name="vrow" id="price">' 
}
function add(){

  const inputs=document.querySelectorAll('.description-input')
  inputs.forEach((input,index)=>{
    
    alert(`value of ${index} description is ${input.value}`)
    
  })
  
}
0

Here is a quick way to get all the values in a form as long as you give each input a "name" it will create a JS object for you.

This way you don't have to call each individual input value. It will also work no matter how many divs or formating elements you have in the form as well.

<form id="myForm">
    <input name="firstname">
    <input name="lastname">
    <input type="submit" value="Submit">
</form>
<script>
    document.querySelector("#myForm").addEventListener('submit',function(event){
        event.preventDefault();
        var obj = {};
        event.target.querySelectorAll('input','select','textarea')
            .forEach((v)=>{
                if(v.type !== 'sumbit' && v.name){
                    obj[v.name] = v.value
                }
            });
        console.log(obj);
        /* obj
            {
                firstname: "",  
                lastname: "",
            }
        */
    })
</script>
Dillon Burnett
  • 473
  • 4
  • 11