簡體   English   中英

如何使用jquery基於選擇標簽的輸出向輸入標簽動態添加REQUIRED屬性?

[英]how to dynamically add REQUIRED attribute to input tags based on output of select tag using jquery?

我有一個帶有兩個選項“新建”和“編輯”的select標簽

當某人選擇“新”選項時,該表單中的所有input標簽都應標記為必需,而當某人選擇“編輯”時,應僅將其中一些標記為必需。

<select name="todo" id="todo" required> 
    <option value="">---</option>
    <option value="new">Add</option>
    <option value="edit">Edit</option>
</select>

現在我嘗試了一些功能,但它們似乎不起作用

<script>
var todo = $('#todo option:selected').text();
if (todo == "new") {
    $('#Name').attr('required',true);
} else if (todo == "edit") {
    //code
}
</script>

<script>
function req() {
    var selectBox = document.getElementById('todo');
    var userInput = selectBox.options[selectBox.selectedIndex].value;
    if (userInput == 'new') {
        $('#Name').attr('required',true);
    } else if (todo == "edit") {
        //code
    }
}
</script>

where
<select name="todo" id="todo" onchange="return req();" required></select>

只是為了確定它是否有效,我在if條件中放入了alert()方法,但從未觸發過該警報。

PS。 輸入標簽之一是

<input type="text" id="Name" name="Name">

謝謝您的寶貴時間...

編輯

正如@Maximillian Laumeister在第二個片段中指出的那樣,出現了一個錯字錯誤(我在這里已經糾正了)。 (對不起)

在您的腳本中,您有一個錯字並引發控制台錯誤:

function req() {
    var selectBox = document.getElementById('todo');
    var userInput = selectBox.options[selectbox.selectedIndex].value;
    if (userInput == 'new') {
        $('#Name').attr('required',true);
    } else if (todo == "edit") {
        //code
    }
}

它說的地方

selectBox.options[selectbox.selectedIndex].value

selectBox需要這樣的大寫:

selectBox.options[selectBox.selectedIndex].value

這項更改似乎對我有用。


另外,正如您所問的那樣,您的第一個腳本不起作用,因為當選擇更改時,它必須綁定運行,就像第一個腳本一樣。 另外,您需要使用jQuery的val而不是text來獲取option標簽的值。 這是第二個腳本的工作版本:

$("#todo").change(function () {
    var todo = $('#todo option:selected').val();
    if (todo == "new") {
        $('#Name').attr('required',true);
    } else if (todo == "edit") {
        //code
    }
});

嘗試這個:

$("select").change(function(){
   if($(this).val() === "new")
       $("#Name").attr("required","required");
   });

您使用的option文本為“ Add”,但在if語句中將其與字符串“ new”進行了比較。 這就是您的代碼無法按預期工作的原因。

這應該使您輕松起來。 每當做出其他選擇時,onchange都會檢測到。 然后根據選擇的選項,執行不同的說明。

 jQuery(document).ready(function(){ jQuery('#todo').on('change', function(event){ alert(this.value); if(this.value === 'edit'){ } else if(this.value === 'new'){ } }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <select name="todo" id="todo" required> <option value="">---</option> <option value="new">Add</option> <option value="edit">Edit</option> </select> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM