![](/img/trans.png)
[英]How do I use jQuery/JavaScript to detect multiple sets of radio button changes and change a separate form input?
[英]JavaScript / jQuery - Recognize Type of Form Input (i.e. radio button, text input, dropdown)
我正在嘗試讓我的JS識別頁面上可見的表單輸入類型。 我正在做一個測驗,當您按下“下一步”按鈕時,只要回答了上一個問題,它將顯示下一個問題。 如果不是,它將顯示一個警報。 我正在嘗試讓JS識別問題的輸入類型,以便它可以查看是否未選中單選按鈕,如果該問題是單選按鈕問題。 但是到目前為止,它已經將所有問題識別為文本和廣播問題。 我不知道我在做什么錯。 我已經為此工作了幾個小時。
這是JS小提琴: http : //bitly.com/1qy5TiX
這是代碼:
$("button").click(function() {
if ($("input:visible [type=text]") || $("select") ) {
console.log("this is text or select");
}
if ($("input:visible :radio")) {
console.log("this is radio");
}
showNext();
}); // end button click function
我為您編寫了一個非常基本的驗證功能,因為您一次只能看到一個問題。 您可能還希望研究驗證庫,但這應該可以使您走上正確的軌道:
function isValid() {
var $form = $('form:visible'),
$input = $form.find('input'),
$select = $form.find('select');
var type = $input.length ? 'input' : ($select.length ? 'select' : 'error');
if (type == 'error') {
alert('invalid input type found');
return false;
}
if ($form.find('input[type="radio"]').length) {
return $form.find('input[type="radio"]:checked').length;
}
var inputVal = $form.find(type).val();
return inputVal !== null && inputVal.length;
}
您可以像這樣檢查表格是否有效:
$("button").click(function () {
console.log('form is valid: ' + isValid());
if (!isValid()) {
alert("Please enter a response.");
} else {
...
另外,您可能希望將'form:visible'
替換為更具體的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.