How to get button value using Javascript

后端 未结 2 1056
南笙
南笙 2021-01-25 07:23

I am trying to figure out how to get the value of a button using JavaScript. There are several buttons generated using a while statement in php code, so the name an

相关标签:
2条回答
  • 2021-01-25 07:44

    try something like

    <script type="text/javascript">
      function getVal(value)
      {
    
       alert(value);
      }
     </script>
     <input type="button" value="Add" onclick="getVal(this.value)">
    
    0 讨论(0)
  • 2021-01-25 07:48

    Note that using the same id for more than one element is invalid html, though most (all?) browsers tend not to make a fuss about it and they'll still display the page quite happily. That's why when you tried to use document.getElementById("details") it always gave you the first button with that id - how would the browser know which one you meant?

    Having said that, if you pass this in the function call on click:

    onClick=\"MCNdetails(this)\"
    

    ...that will give the function a direct reference to the particular button that was clicked. So then:

    function MCNdetails(btn) {
        var buttonValue = btn.value;
    
        // etc
    }
    

    In which case your buttons don't really need ids at all. But if you do keep the ids you should find a way to make them unique (e.g., append a sequence number to the end of each).

    0 讨论(0)
提交回复
热议问题