简体   繁体   中英

How to get value of input button click?

I am new to javascript so sorry if this isn't technical.

I have an html

 <button type="button" id="btnlocation" value="chicken">Click me</button>

So i am trying to pass the string value "chicken" into the button click function

$('#btnlocation').click(function (value) {

  alert(value);  // This should output chicken 


}

But instead it outputs [Object],[Object] so how do i get the value or convert it into string?

thank you

The first argument in callback refers to event object . For getting the value either use this.value or $(thid).val() where this refers to the dom object of clicked element.

$('#btnlocation').click(function () {
  alert(this.value);
  // or
  alert($(this).val());  
})

 $('#btnlocation').click(function() { console.log(this.value); // or console.log($(this).val()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" id="btnlocation" value="chicken">Click me</button> 

you should use this

$('#btnlocation').click(function () {

  alert($(this).val());  // This should output chicken 


});

for getting the value use $(this).val() for getting the id of the button use $(this).attr("id")

  $('#btnlocation').click(function () {


      alert($(this).val()); // this is used get the value

      alert( $(this).attr("id")); // this is used to get the id of the button

    });

try this

$(document).ready(function(){
    $('#btnlocation').click(function(){
        alert($('#btnlocation').val());
    });
});

It is ideal to pass the event it self to the on event method. From that event you can get whatever value you want of that element.

You can change you JavaScript as below to do so:

$('#btnlocation').click(function (e) {

 alert(e.target.value);  // This should output chicken 


});

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