当某人单击“提交”按钮时,我希望它调用当前在“ paymentMethod”选项组框中选择的函数。
例如,如果我选择了“比特币”选项,它将调用bitcoin()函数,并且该按钮将如下所示:
<button onclick='bitcoin()' class='btn btn-primary'>Submit</button>
我的代码:
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">Paypal</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">Amazon, PSN, Steam, Battle.Net, G2A, ETC</option>
</optgroup>
</select>
<button onclick='//I want this to be whatever is selected in paymentMethod option group' class='btn btn-primary'>Submit</button>
我尝试了以下JS代码:
<script>
$(document).ready(function(){
$('#paymentMethod').on('change', function() {
if ( this.value == 'Paypal')
//.....................^.......
{
var paymentEr = 'Paypal()';
}
else if (this.value == 'Giftcard')
{
var paymentEr = 'Giftcard()';
} else {
var paymentEr = 'Paypal()';
}
});
});
document.write("<button onclick=' + paymentEr + "' class="btn btn-primary">Submit</button>");
</script>
答案 0 :(得分:2)
我将使一个处理所有情况的处理程序(而不是更改onClick处理程序本身)(或者,如果您想使用单独的函数来组织代码,只需在相关的条件块中按如下所示调用这些函数):< / p>
function handleForm() {
const selected = document.getElementById("paymentMethod").value;
if (selected === 'Bitcoin') {
//handle bitcoin
}
else if (selected === 'Paypal') {
//handle Paypal
}
else if (selected === 'Giftcard') {
//handle GiftCard
}
}
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">
Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC
</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">
Paypal
</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">
Amazon, PSN, Steam, Battle.Net, G2A, ETC
</option>
</optgroup>
</select>
<button onclick='handleForm()' class='btn btn-primary'>Submit</button>
答案 1 :(得分:0)
在按钮click
上,它会检查select元素中的选定值,您可以避免在html代码中内嵌javascript。请检查我的答案。
function init(){
let el = document.getElementById("paymentMethod");
let sbmBtn = document.getElementById("submitBtn");
sbmBtn.addEventListener('click',getSelectedValue);
function getSelectedValue(){
let selectedVal = el.options[el.selectedIndex].value;
if (selectedVal == 'Paypal'){
//var paymentEr = 'Paypal()';
alert(selectedVal);
}else if (selectedVal == 'Giftcard'){
//var paymentEr = 'Giftcard()';
alert(selectedVal);
} else {
//var paymentEr = 'Paypal()';
alert(selectedVal);
}
}
}
//DOM has been loaded
addEventListener('load',init);
<select class="form-control select2" id='paymentMethod'>
<optgroup label="Crypto">
<option value="Bitcoin">Bitcoin, Etherum, Litecoin, DogeCoin, Ripple, ETC</option>
</optgroup>
<optgroup label="Paypal">
<option value="Paypal">Paypal</option>
</optgroup>
<optgroup label="Giftcard">
<option value="Giftcard">Amazon, PSN, Steam, Battle.Net, G2A, ETC</option>
</optgroup>
</select>
<button id="submitBtn" class="btn btn-primary">Click</button>