简体   繁体   中英

Javascript: How to get innerHTML of clicked button

Built a tip calculator but want to shorten the code by getting the innerHTML of the button that is being clicked.

Total Bill: <input id="bill" type="text">
<button type="button" onclick="tip15()">15</button>
<button type="button" onclick="tip18()">18</button>  
<button type="button" onclick="tip20()">20</button>
<div id="tip">You owe...</div>


function tip15(){
var totalBill = document.getElementById("bill").value;
var totalTip = document.onclick.innerHTML
var tip = totalBill * 0.15;
document.getElementById("tip").innerHTML = "&#36;" +tip
}

Problem with this method is that I have to write out three versions of the function to correspond with the tip amount. I want to create one function that grabs the innerHTML of the button being clicked and uses that value in the function. I want it to look something like this

function tip(){
var totalBill = document.getElementById("bill").value;
**var totalTip = GET INNERHTML OF CLICKED BUTTON**
var tip = totalBill * ("." + totalTip);
document.getElementById("tip").innerHTML = "&#36;" +tip
}

That way I can run the same function on the different buttons.

Change like this:Pass value to tip function.

<button id="15" type="button" onclick="tip(15)">15</button>
<button id="18" type="button" onclick="tip(18)">18</button>  
<button id="20" type="button" onclick="tip(20)">20</button>

function tip(tip_value)
{
  /*use here tip_value as you wish you can use if condition to check the value here*/ 
  var totalBill = document.getElementById("bill").value;
  var totalTip = tip_value;
  var tip = totalBill * ("." + totalTip);
  document.getElementById("tip").innerHTML = "&#36;" +tip;
}

Pass this.innerHTML as an argument to your tip function.

So your tip function should look like this:

function tip(totalTip) {
  var totalBill = document.getElementById("bill").value;
  var tip = totalBill * ("." + totalTip);
  document.getElementById("tip").innerHTML = "&#36;" +tip
}

Therefore, if you have a button element that looks like this:

<button type="button" onclick="tip(this.innerHTML)">15</button>

The tip function will be called as tip(15) .

Use HTML5 data attributes.

 <button type="button" data-tip="15" onclick="getTip(this)">15</button>

The parameter this that you're passing to the function refers to the button that is being clicked. Then you get the value of the attribute like this:

function tip(button){
   var tip= button.getAttribute("data-tip");
   ...
}

I leave the rest for you.

I'll write up a quick solution, then explain why I did it that way.

PROPOSED SOLUTION

Part 1, the HTML

<div id="tip-wrapper">
        <label for="bill">Total bill:</label>
        <input name="bill" id="bill" type="text">
        <br/>

        <label for="tipratio">Tip ratio:</label>
        <button name="tipratio" value="15" type="button">15%</button>
        <button name="tipratio" value="18" type="button">18%</button>  
        <button name="tipratio" value="20" type="button">20%</button>

        <div id="final-value">You owe...</div>
 </div>

Part 2, the JavaScript

var parent = document.getElementById('tip-wrapper'),
    buttons = parent.getElementsByTagName('button'),
    max = buttons.length,
    i;

// function that handles stuff
function calculate (e) {
    var bill = document.getElementById('bill'),
        tipRatio = e.target.value;


    document.getElementById('final-value').textContent = bill.value * (1+tipRatio/100);
}

// append event listeners to each button
for(i = 0; i < max; i++) {
    buttons[i].addEventListener('click', calculate, true);
}

EXPLANATIONS

About the HTML, not "much" has changed. The only thing being I'm using something that is a little more standards compliant. I've added a wrapper element, this is just to isolate some DOM traversal instead of going through the whole document object to do your lookups (this will speed up your script). Your buttons use "value" attribute, which is best. Since you can display button text one way, but use a proper value (see I added % characters). Other than that, I mostly added proper identifiers and labels.

The JavaScript, this is where i'll go a little more in detail, I'll go step by step:

  1. The first thing you want to do in a script is set the variables you'll need (and fetch the DOM elements you'll be using. This is what I've done on the first 4 lines of code.
  2. Create a generic function that will handle your calculations and update your elements, no matter their numeric value. The feature I used here is adding a parameter (e) to your function, because EVENTS in javascript attach an EVENT OBJECT to your callback function (in this case calculate(); ). The EVENT OBJECT actually has a bunch of useful properties, of which I use: target : this is the element that triggered the event (ie one of your buttons)

All we have to do is grab the target's value ( e.target.value ) and use that in the math that returns the final bill.

  1. Using addEventListener. It's generally agreed on that you should keep your JavaScript outside of your HTML, so using the old event methods (onclick="") is discouraged. The addEventListener() method isn't too complicated, without going into detail it works as follows:
    • htmlObject.addEventListener('event type', 'callback function', 'bubbles true/false');

All I did was loop through all your buttons and append the event lsitener.

Closing notes

With this script, you can now add any "buttons" you want, the script will take them all into account and adapt accordingly. Just make sure to set their "value".

As I was writing this up a few people gave some quick answers. I can't comment yet (low reputation) so I'll leave my comments here.

  1. Some of the proposed answers tell you to use innerHTML to fetch the tip value. This is wrong, you are using form fields and should use element.value that's what it is made for.

  2. Some have even dared to say use the HTML5 data-* attributes. sure, you could. But why would you? HTML and the DOM already provide every necessary tool to accomplish your task WITHOUT the need to polute your HTML with unnecessary attributes. the value="" attribute is meant to be used in forms, it should be used over data-* attribute for field values.

  3. As a general note innerHTML is meant to get HTML, not necessarily text or values. There are other methods to get the values you are seeking. In the case of form elements, it's element.value , in the case of most other HTML elements, it's element.textContent .

Hope these explanations help

 function tip(o) { var input = document.querySelector("input[id='bill']"); var total = input.value * o.innerHTML; document.querySelector("#tip").innerHTML = "&#36;" + total; } 
 Total Bill: <input id="bill" type="text"> <button type="button" onclick="tip(this)">15</button> <button type="button" onclick="tip(this)">18</button> <button type="button" onclick="tip(this)">20</button> <div id="tip">You owe...</div> 

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