简体   繁体   中英

How can I change span text based on the button clicked?

I want to change the amount shown on the html page after user clicks on them. There are 2 buttons and upon clicking each button, it should direct them to a new html and the amount should change accordingly. I know this isn't really the method to do it but I am unsure how else can I do it. Currently, I am only able to append all the amount.

<button onclick="myFunction1()" type="submit" id="one">BUY</button>
<button onclick="myFunction2()" type="submit" id="two">BUY</button>
function myFunction1() {
    window.location='pay.html';
};

function myFunction2() {
    window.location = 'pay.html';
};
 <span class="title" id="total"></span>
 <span class="title" id="total2"></span>
(function () {
    "use strict";

    $().ready(function () {

    })
    myFunction1()

    function myFunction1() {
        var totalamt = '$100';
        $('#total').html("<span style='float:right'>" + "Total:" + 
        totalamt + "</span>");
    }

})();

(function () {
    "use strict";

    $().ready(function () {

    })
    myFunction2()

    function myFunction2() {
        var totalamt2 = '$300';
        $('#total2').html("<span>" + "Total:" + totalamt2 + 
        "</span>");
    }
})();

Want to achieve the results of: eg by clicking the first button, redirects user to pay.html and show $100. By clicking the second button, redirects to the same html(pay.html), show $300. Please help thanks a lot.

you can give id to span and then set the text to 300 or 100

 <span id="price">$100</span>
   <scrit>
   document.getElementById("price").innerHTML = "$300";  
</script>

Send GET request to pay.html with params:

window.location='pay.html?amount=100';

Access params through JS:

var url= new URL(document.location).searchParams;
var amount=url.get("amount");
var totalamt = '$'+ amount;
$('#total').html("<span style='float:right'>" + "Total:" + totalamt + "</span>");

yourhtml.html :

<button onclick="myFunction1()" type="submit" id="one">BUY</button>
<button onclick="myFunction2()" type="submit" id="two">BUY</button>
function myFunction1() {
    window.location='pay.html?amount=100';
};

function myFunction2() {
    window.location = 'pay.html?amount=300';
};

pay.html :

 <span class="title" id="total"></span>
var url = new URL(document.location).searchParams;//Getting search params
var amount = url.get("amount"); //Getting value of amount from parameters
var totalamt = '$'+ amount;
$('#total').html("<span style='float:right'>" + "Total:" + totalamt + "</span>");

This will also work without Real app.

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