[英]Enabling a button based on selected values
一般警告,我有超級垃圾代碼。 話雖如此,我從一開始就禁用了按鈕,以減少提交表單時發生的人為錯誤。 當填充三個特定字段時,我需要啟用它。 但是,這些字段之一是html中的標頭標記,用於顯示秒表。 然后,jQuery函數將輸出作為文本抓取,並將其存儲到名為userInfo的對象中。 當ID任務,源和輸出不為空白/ =“ 00:00:00”時,我想啟用我的提交按鈕。
我在不同的地方嘗試了多個if語句來檢查輸入值的有效性。 但是,對於最新的if語句,當默認值為“ disabled”時,它將啟用按鈕
<div class ='row'>
<div class="input-field col s6">
<input type="text" id="task" class="autocomplete" placeholder ='Task' required>
<div class="input-field col s6">
<select id = 'source'>
<option value="" diasable selected></option>
<option value="some source">source1</option>
<option value="other source">source2</option>
</select>
<label>source1 or source2</label>
</div>
<h2 id = 'output'><b>0:00:00:00</b></h2>
<button id="start"class="waves-effect waves-light btn">start<i class="material-icons right">timer</i></button>
<button id="stop"class="waves-effect waves-light btn">stop<i class="material-icons right">timer_off</i></button>
<button id ="btn" class="btn waves-effect waves-light #26a69a" type="submit" name="action" disabled>Track It!
<i class="material-icons right">access_time</i>
</button>
我需要任務,源和輸出的文本值的輸出不為空/“ 00:00:00”才能啟用按鈕。
這是一些JavaScript
M.toast({html: 'Record Submitted'})
var userInfo = {};
userInfo.task= document.getElementById('task').value;
userInfo.source= document.getElementById('source').value;
userInfo.timeSpent= $("#output").text();
userInfo.units= $("#count").text();
google.script.run.userClicked(userInfo);
document.getElementById('task').value='';
var source = document.getElementById('source');
source.selectedIndex = 0;
M.FormSelect.init(source);
}
var h1 = document.getElementById('output'),
start = document.getElementById('start'),
stop = document.getElementById('stop'),
//clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
嘗試使用“更改”事件偵聽器,並測試是否應在每次更改時啟用或禁用按鈕。
document.addEventListener("change", validate);
// I need the output for task,source,and the text value for output to not be blank/"00:00:00" for the button to be enabled.
function validate() {
const ready = $("#task").val() && $("#source").val() && $("#output").text() !== "00:00:00";
$("#btn").prop("disabled", ! ready);
}
通讀,我相信您想根據select#source
的值將button#btn
disabled
屬性更改為enabled
。 您可以使用下面的示例代碼來實現
// 1st: get select#source and button#btn using their ID
var source = document.getElementById('source');
var button= document.getElementById('btn');
// 2nd : capture source value on change using JS Event Listener
source.addEventListener("change", function() {
if(source.value == "some source") {
// 3rd : remove disabled attribute and set enabled attribute
button.removeAttribute("disabled");
button.setAttribute("enabled", "");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.