I'm trying to use the input from a form to create the details for a metamask transaction, taking form address and etherem amount then calling them with metamask. The metamask code works when hardcoded with address and amount. not sure where I'm going wrong.
run npx serve because metamask can be tricky.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>
<input onclick="fill_amount" id="amount" type="number" placeholder="eth">
<input onclick="fill_address" id="address" placeholder="address">
<button class="pay-button">Pay</button>
<div id="status"></div>
</div>
<script type="text/javascript">
window.addEventListener('load', async () => {
if (window.ethereum) {
window.web3 = new Web3(ethereum);
try {
await ethereum.enable();
initPayButton()
} catch (err) {
$('#status').html('User denied account access', err)
}
} else if (window.web3) {
window.web3 = new Web3(web3.currentProvider)
initPayButton()
} else {
$('#status').html('No Metamask (or other Web3 Provider) installed')
}
})
const initPayButton = () => {
$('.pay-button').click(() => {
// paymentAddress is where funds will be send to
var paymentAddress = document.getElementById("address").innerHTML
var amountEth = document.getElementById("amount").innerHTML
web3.eth.sendTransaction({
to: paymentAddress,
value: web3.toWei(amountEth, 'ether')
}, (err, transactionId) => {
if (err) {
console.log('Payment failed', err)
$('#status').html('Payment failed')
} else {
console.log('Payment successful', transactionId)
$('#status').html('Payment successful')
}
})
})
}
function fill_amount() {
var amountEth = document.getElementById("amount").innerHTML
}
function fill_address() {
var paymentAddress = document.getElementById("address").innerHTML
}
</script>
</body>
</html>
inside your fill_amount & fill_address functions you’re using the same variable of payment address. I believe inside the fill_amount function the variable should be amountEth not paymentAddress.