如果按下按钮,则发送表单
Send in form if button pressed
我的表单中有两个按钮(JS 正在监听,因此我可以在表单中显示某些字段)。
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" name="Distance" id="one_way_button">Distance & Time</button>
<button type="button" class="btn btn-default" name="Distance" id="stored_button">Stored Address</button>
</div>
我想以 post 数据的形式实际发送哪个按钮被按下。如果重要的话,我们在 rails 上使用 ruby。不确定我需要做什么来更改我的 html 以实际发送按下的按钮。
您可以在提交前将按钮名称存储在隐藏输入中
function fnSubmitForm(obj)
{
document.getElementById("ButtonName").value = obj.value
document.getElementById("myForm").submit();
}
点击调用上面的函数
<div class="btn-group" role="group" aria-label="...">
<input type="hidden" id="ButtonName" name="ButtonName" value="" />
<input type="button" class="btn btn-default" name="Distance" id="one_way_button" onclick="fnSubmitForm(this)" value="Distance & Time" />
<input type="button" class="btn btn-default" name="Distance" id="stored_button" onclick="fnSubmitForm(this)" value="Stored Address" />
</div>
您可以简单地使用 event.target
(https://developer.mozilla.org/en-US/docs/Web/API/Event/target) 属性 来知道点击了哪个按钮。
var parent = document.querySelector('.btn-group'); //assuming div has no id
parent.addEventListener('click', function(evt) {
if(evt.target.id === 'one_way_button') {
// do something
} else {
// do other thing
}
}, true);
我的表单中有两个按钮(JS 正在监听,因此我可以在表单中显示某些字段)。
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default" name="Distance" id="one_way_button">Distance & Time</button>
<button type="button" class="btn btn-default" name="Distance" id="stored_button">Stored Address</button>
</div>
我想以 post 数据的形式实际发送哪个按钮被按下。如果重要的话,我们在 rails 上使用 ruby。不确定我需要做什么来更改我的 html 以实际发送按下的按钮。
您可以在提交前将按钮名称存储在隐藏输入中
function fnSubmitForm(obj)
{
document.getElementById("ButtonName").value = obj.value
document.getElementById("myForm").submit();
}
点击调用上面的函数
<div class="btn-group" role="group" aria-label="...">
<input type="hidden" id="ButtonName" name="ButtonName" value="" />
<input type="button" class="btn btn-default" name="Distance" id="one_way_button" onclick="fnSubmitForm(this)" value="Distance & Time" />
<input type="button" class="btn btn-default" name="Distance" id="stored_button" onclick="fnSubmitForm(this)" value="Stored Address" />
</div>
您可以简单地使用 event.target
(https://developer.mozilla.org/en-US/docs/Web/API/Event/target) 属性 来知道点击了哪个按钮。
var parent = document.querySelector('.btn-group'); //assuming div has no id
parent.addEventListener('click', function(evt) {
if(evt.target.id === 'one_way_button') {
// do something
} else {
// do other thing
}
}, true);