1

For some reason, attribute value is not changing. I have a limited knowledge of JavaScript. Any help would be appreciated.

function change(amount) {
  document.getElementsByName("sold_amount").value = amount;
}
<input type="hidden" name="sold_amount">

<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sold amount
        <span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a href='#' onclick="change(10000)">10000</a></li>
    <li><a href='#' onclick="change(20000)">20000</a></li>
    <li><a href='#' onclick="change(30000)">30000</a></li>
  </ul>
j08691
  • 204,283
  • 31
  • 260
  • 272
Ken Graham
  • 39
  • 7

2 Answers2

3

When you use getElementsByName, notice the elementS; its plural. This means the function returns a NodeList collection (similar to an array). You should use document.getElementsByName("sold_amount")[0].value=amount;.

You still don't see it as type="hidden", but its there. You can use your developer tools to inspect the input to see the change.

j08691
  • 204,283
  • 31
  • 260
  • 272
Pim
  • 850
  • 7
  • 17
0

Try this:

  <input type="text" id="sold_amount" name="sold_amount">
  <script>
  function change(amount)
  {
    document.getElementById("sold_amount").value=amount;
  }
  </script>
  <div class="dropdown">
     <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sold amount
      <span class="caret"></span></button>
      <ul class="dropdown-menu">
       <li><a href='#' onclick="change(10000)">10000</a></li>
       <li><a href='#' onclick="change(20000)">20000</a></li>
       <li><a href='#' onclick="change(30000)">30000</a></li>
     </ul>

https://jsfiddle.net/igasparetto/g0j6342r/

I think you will need to make other changes to your code. Have a look at event delegation and, perhaps, rely on jQuery as you are using CSSBoostrap.

igasparetto
  • 1,086
  • 1
  • 12
  • 28
  • 1
    I have a basic knowledge of javascript as of now. Will surely check jsfiddle. Thanks. – Ken Graham Sep 25 '17 at 14:00
  • That is fine, you need to start somewhere. I don't get why people keep down-voting junior developers questions. Things are difficult at first. – igasparetto Sep 25 '17 at 14:33