Retrieve Button value with jQuery

后端 未结 9 1750
一个人的身影
一个人的身影 2020-11-27 14:08

A simple one, I\'m trying to retrieve the value attribute of a button when its been pressed using jQuery, here\'s what I have:



        
相关标签:
9条回答
  • 2020-11-27 14:47

    I know this was posted a while ago, but in case anyone is searching for an answer and really wants to use a button element instead of an input element...

    You can not use .attr('value') or .val() with a button in IE. IE reports both the .val() and .attr("value") as being the text label (content) of the button element instead of the actual value of the value attribute.

    You can work around it by temporarily removing the button's label:

    var getButtonValue = function($button) {
        var label = $button.text(); 
        $button.text('');
        var buttonValue = $button.val();
        $button.text(label);
        return buttonValue;
    }
    

    There are a few other quirks with buttons in IE. I have posted a fix for the two most common issues here.

    0 讨论(0)
  • 2020-11-27 14:47

    Give the buttons a value attribute and then retrieve the values using this:

    $("button").click(function(){
      var value=$(this).attr("value");
    });
    
    0 讨论(0)
  • 2020-11-27 15:00
     <!DOCTYPE html>
     <html>
     <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
     </script>
     <script>
     $(document).ready(function(){
       $("#hide").click(function(){
        $("p").toggle();
    
        var x = $("#hide").text();
    
          if(x=="Hide"){
          $("button").html("show");
    
          }
         else 
         {
         $("button").html("Hide");
    
          }
    
           });
    
       });
    
      </script>
      </head>
      <body>
    
     <p>If you click on the "Hide" button, I will disappear.</p>
    
     <button id="hide">Hide</button>
    
    
    
     </body>
     </html>
    
    0 讨论(0)
提交回复
热议问题