Home > Software design >  How to get array value in html using JavaScript?
How to get array value in html using JavaScript?

Time:02-05

Html:

<section id="secProducts" >
        <div id="CART_TEMPLATE" style="display:none">
              <figure>
                <img src="images/1.jpg" alt="img02"  height="80" width="80" />
                     <figcaption>
                         <p>Product Name:</p>
                          <p ></p>
                          <label for="quant">Enter Quantity:</label>
                     <input type="number" id="quant" name="quant[]" min="1" > 
                   </figcaption>
             </figure>
         /* Try to get Value of input from name="quant[]" .But Unable to get document.getElementsByName("quant[0]").value; ? */
      </div>
  </section>

JavaScript:

function socialSharing()
{
    alert("Hi:");
    var fun1=document.getElementsByName("quant[0]").value;
    alert(fun1);
    var fun2=document.getElementsByName("quant[1]").value;
    alert(fun2);
    alert(bar2);    
}

In Html, there is an array of Product Details. It displays all products. But I'm trying to get quantity details with var fun1=document.getElementsByName("quant[0]").value; which returns undefined.

CodePudding user response:

You can access the value of the input elements using the following code:

var fun1 = document.getElementsByName("quant[0]")[0].value;
var fun2 = document.getElementsByName("quant[1]")[0].value;

CodePudding user response:

Here is a small reproduction for the problem: Codepen Demo

The main point as described in other answers, is that getElementsByName() can return multiple elements, compared to getElementById()

// instead of this
var fun1 = document.getElementsByName("quant[0]").value;

// get the first element of the returned result and get this value
var fun1 = document.getElementsByName("quant[0]")[0].value;

function socialSharing()
{
    var fun1=document.getElementsByName("quant[0]")[0].value;
    document.getElementById("results").innerHTML  = "Detected quantity "   fun1   "<br>";
}
<section id="secProducts" >
  <div id="CART_TEMPLATE" >
    <figure>
      <img src="images/1.jpg" alt="img02"  height="80" width="80" />
      <figcaption>
        <p>Product Name:</p>
        <p ></p>
        <label for="quant">Enter Quantity:</label>
        <input type="number" id="quant" name="quant[0]" min="1" onkeyup="socialSharing()">
      </figcaption>
    </figure>
  </div>
</section>
  
<div id="results"></div>

In order to show that the code above works, I have added a new div, where each key press handled by the onkeyup event of the input field, will write down the current value of the input field

  • Related