Home > Software design >  How can I transfer an argument from html file to jQuery
How can I transfer an argument from html file to jQuery

Time:08-17

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(){

    })
})

CodePudding user response:

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

CodePudding user response:

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)" >37</button>

  • Related