简体   繁体   中英

how to pass the variable in jquery click event function

I want to Pass the variable with click event in jquery

var get=3; 
$('#edit').click(function(event){
alert('You are getting:' + get);
}

please help me

html

<input type='submit' name='action' id='edit' />

You have to initialize click even once document is loaded. Also you have syntax error in your code.

Try this one:

$(document).ready(function() {
    var get=3;
    $('#edit').click(function(event){
        alert('You are getting:' + get);
    });
});

 <!DOCTYPE html> <html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var get=3; $('#edit').click(function(event){ alert('You are getting:' + get); }); }); </script> </head> <body> <input type='submit' name='action' id='edit' /> </body> </html> 

You forgot the closing paranthesis.

Your javascript code should look like:

var get=3; 
$('#edit').click(function(event){
  alert('You are getting:' + get);
});

HTML button

<button id='my_button' type='button' data-id='1' data-values='1' value='6' data-whatever='20'>My button</button>

Jquery

$('#my_button').bind('click', function() {
    var value = $(this)val();
    var whatever = $(this).data('whatever');
    var id = $(this).data('id');
    var values = $(this).data('values');
    console.log(value);
    console.log(whatever);
    console.log(id);
    console.log(values);

});
  1. Open Firefox > Inspect Element > Console Tab.
  2. Load the codes
  3. Click the button
  4. See response

Initiate everything after document is ready.

$(document).ready(function() {
    var get = 3; 
    $('#edit').click(function(event){
        alert('You are getting:' + get);
    });
});

also don't use event handlers until you need it.

try:

$(document).ready(function() {
    var get=3; 
    $('#edit').on('click', function(event){
        alert('You are getting:' + get);
   }
});

html:

<input type="button" id="edit" />

You can do it like this:

$(document).ready(function() {
    var get = 3;
    $("#edit" ).bind("click", { key: get }, function(event){
        // event.data.key will have value of get
    });
});

Can you try like this,

<script type="text/javascript">
  function test(ev) {
    var id = $(ev).attr('id');
    alert(id);
  }
</script>


<input id="btn" type="button" value="click" OnClick="test(this);" />

try this.

html:

<input type="button" id="edit"><br/>

jquery:

$(document).ready(function(){   
    var get = 3;  
    $("#edit").on('click',function(){ 
        alert("Value is: " + get); 
        //parameter value
    }); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM