[英]Change (immediatly) submit button text if any form input change [JS]
如果任何表單輸入發生更改,如何立即更改提交按鈕文本?
//This applies to whole form $('#test').change(function() { $("#send").prop("value","Change"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="test"> <input id="Input1" value="Input1" /> <input id="Input2" value="Input2" /> <input type="submit" id="send" value="Send" /> </form>
此處,光標離開輸入后 ,按鈕文本發生更改。
實時示例: http : //jsfiddle.net/rgg3A/56/
使用input
事件
使用:input Selector
,選擇所有input, textarea, select and button
元素
$('#test').find(':input').on('input', function() { document.getElementById('send').value = this.value; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form id="test"> <input id="Input1" value="Input1"> <input id="Input2" value="Input2"> <input type="submit" id="send" value="Send"> </form>
您需要將偵聽器放在輸入本身上,在這種情況下,將其附加到onKeyDown
事件:
$('input').on("keydown", function() {
send.value = "Change";
});
需要最少更改的解決方案是使用keyup
事件。 即
$('#test').keyup(function() {
send.value = "Change";
});
這樣,在#test
父級中輸入任何輸入字段都會觸發該事件。
$('input').on("keydown", function() { $('#send').val(this.value); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="test"> <input id="Input1" value="Input1"> <input id="Input2" value="Input2"> <input type="submit" id="send" value="Send"> </form>
由於您最初的問題沒有直接提及JQuery,而是將其用作選擇器,因此這個問題讓我垂涎不已,無法尋求合適的JavaScript答案。
因此,此答案與其他示例相同,但僅使用普通的JavaScript。 就像其他答案一樣,使用input
事件。
document.getElementById('test').addEventListener('input', function(e) { document.getElementById('send').value = e.target.value; });
<form id="test"> <input id="Input1" value="Input1"> <input id="Input2" value="Input2"> <input type="submit" id="send" value="Send"> </form>
此處的區別在於,它正在偵聽form元素上的冒泡事件,僅注冊一次事件監聽器(而不是將同一事件監聽器應用於多個元素),並使用Event.target
屬性確定修改了哪個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.