skip to Main Content

I want to transfer the argument 7 from the html file

<button id="buttonseven" onclick="buttonClick(7)">7</button>

and how could I receive this argument in jQuery ?

$(document).ready(function(){
    $('#buttonseven').click(function(){

    })
})

2

Answers


  1. you can save 7 in button attribute data-* form ,like code below:

    <button id="buttonseven" data-value="7">click here</button>
    

    so, from jQuery, you can do this:

    $(document).ready(function(){
        $('#buttonseven').click(function(){
           let value = $(this).data('value')
           console.log(value)
        })
    })
    

    you can read jquery data() function here

    Login or Signup to reply.
  2. I used this post get the value of "onclick" with jQuery? to get the value of your onclick function and this post Get Substring between two characters using javascript to get the value between ( and ).

    But the solution of user1702660 is more simple than this one i think 🙂

    $("#buttonseven, .test").click(function() {
      var OnClickVal = $(this).get(0).attributes.onclick.nodeValue;
      var mySubString = OnClickVal.substring(OnClickVal.indexOf("(") + 1, OnClickVal.lastIndexOf(")"));
      console.log(mySubString);
    });
    
    function buttonClick(id) {
      // do something
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="buttonseven" onclick="buttonClick(7)">7</button><br>
    <button onclick="buttonClick(37)" class="test">37</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search