简体   繁体   中英

how to take two buttons diffrent value by calling function in javascript

 function getValue(){ var v = document.getElementById("btn2").value; document.getElementById("display").value += v; } 
  <input type ="text" id = "display" value = "" ></input> <tr> <td> <input type = "button" id = "btn2" value="7" onclick="getValue(this)" ></input> </td> <td> <input type = "button" id = "btn2" value="8" onclick="getValue(this)" ></input> </td> </tr> 

I just want to different value by clicking 8 or 7 button. but every time i got 7 as result what can i do please help.. and more i want to pass "this" in getValue(this) so that by clicking that button get the all information that buttton. plz help me thanks

Your IDs, in dom should be unique. jQuery is returning only the first element when calling $('#idstring'); as document.getElementById('#idstring') also does.

In this case, you could use className.

You also pass a parameter to the function, but you don't use it.

I edited this snippet to show how to bind this to the function before calling it. Like this, you can use 'this' if it's your thing.

 function getValue(el) { document.getElementById("display").value = el.value; } function getValue2() { document.getElementById("display").value = this.value; } 
 <input type="text" id="display" value=""></input> <tr> <td> <input type="button" class="btn2" value="7" onclick="getValue(this)"></input> </td> <td> <input type="button" class="btn2" value="8" onclick="getValue2.bind(this)()"></input> </td> </tr> 

  1. Make sure your ids are unique.

  2. Make use of the argument ( this ) that you are passing.

 function getValue(button){ var v = document.getElementById(button.id).value; document.getElementById("display").value += v; } 
  <input type ="text" id = "display" value = "" ></input> <tr> <td> <input type = "button" id = "btn1" value="7" onclick="getValue(this)" ></input> </td> <td> <input type = "button" id = "btn2" value="8" onclick="getValue(this)" ></input> </td> </tr> 

I see you already have answers to your question. However a cleared way might be to use classes.

$(".my_buttons").click(function(){
    $("#display").val($(this).val());
});

<input type="text" id="display" />
<input type="button" class="my_buttons" value="7" />
<input type="button" class="my_buttons" value="8" />

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