[英]HTML5 required attribute trigger action with jQuery
我正在開發原型,我想在提交后觸發操作,但前提是必須填寫必填字段。
我有這個代碼
<button type="submit" onclick="doSomething()" class="btn btn-primary">Register</button>
還有使用HTML 5中“ required”屬性在表單上輸入的內容,例如
<input type="text" class="form-control" placeholder="Name" required>
我只想在輸入已填充的情況下觸發onclick操作。 我想我可以通過檢查輸入是否使用jQuery填充來做到這一點,我想知道是否有更簡單的方法
好吧,我實際上已經找到了解決方案,如果有人遇到同樣的問題,這就是我的解決方法。
我沒有在按鈕標簽上使用“ onclick”,而是在我的表單標簽中使用doSomething函數添加了一個“ onsubmit”(我不知道存在此線索)事件,如下所示:
<form onsubmit="doSomething()">
僅當所需的輸入已填充時才調用該函數,如此簡單。
感謝那些試圖幫助的人
嘗試使用oninput
事件
function doSomething() { console.log("do stuff") } document.querySelector("input").oninput = function() { this.nextElementSibling.click() }
<input type="text" class="form-control" placeholder="Name" required> <button type="submit" onclick="doSomething()" class="btn btn-primary">Register</button>
好吧,您可以隨時使用此https://jsfiddle.net/2Lzo9vfc/26/
的HTML
<button type="submit" class="btn btn-primary">Register</button>
<input type="text" class="form-control" placeholder="Name" required>
JS
$('button').click(function() {
var content = $('input').val();
if(content != '') {
alert(content);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.