簡體   English   中英

如何獲得嵌入在選擇選項中的輸入文本的值?

[英]How to get the value of input text embedded in select option?

在我的html模板中,我在<select>標記中有一組選項。 一個特定的選項允許您在輸入文本字段中輸入自定義類別名稱。

現在,一旦單擊“提交”按鈕,便無法在輸入字段中獲取值(如果在其中輸入了值)。

這是HTML <select><input>字段:

 {% for index in list %}

   <select name="browser" id="select_id{{index}}" onchange="if(this.options[this.selectedIndex].value=='customOption'){toggleField(this,this.nextSibling); this.selectedIndex='0';}">

     <option value="0">---- select ----</option>
     <option value="customOption">[enter your own custom category]</option>
     <option value="Chrome">Chrome</option>
     <option value="Firefox">Firefox</option>
     <option value="Internet Explorer">Internet Explorer</option>

     <input name="browser" id="input_id{{index}}" type="text" disabled="disabled" onblur="if(this.value==''){toggleField(this,this.previousSibling);}">

    </select>

    <!-- SUBMIT BUTTON TO INVOKE add_category() javascript method -->

    <button type="button" onclick="add_category('select_id{{index}}', 'input_id{{index}}');">SUBMIT</button>

 {% endfor %}                                   

add_category() ,我只想在屏幕上顯示選擇/鍵入的類別值作為警報消息。

function add_category(select_id, input_id){
        if($("#"+select_id).val()=='0')
        {
            alert("Please select a valid category");
        }
        else if($("#"+select_id).val()=='customOption')
        {
            var i = $("#"+input_id).val();
            alert("INPUT CATEGORY: ", i);
        }
        else
        {
            var s = $("#"+select_id).val();
            alert("SELECTED CATEGORY: ", s);        
        }
    }

但是,在輸入或所選類別值中不返回任何值。

您可以使用以下代碼段檢索select的值,這將對您有所幫助。

var mySelect = $('select[name=browser');
var conceptName = mySelect.find(":selected").text();
console.log(conceptName)

可執行代碼段位於下面的代碼筆URL https://codepen.io/redhatvicky/pen/RdzEGW中

function add_category(select_id, input_id){
        if($("#"+select_id+"").val()=='0')
        {
            alert("Please select a valid category");
        }
        else if($("#"+select_id+"").val()=='customOption')
        {
            var i = $("#"+input_id+"").val();
            alert("INPUT CATEGORY: ,"+i);
        }
        else
        {
            var s = $("#"+select_id+"").val();
            alert("SELECTED CATEGORY: ,"+ s);        
        }
    }



    });

這甚至不是有效的html,Chrome會將輸入呈現在select之外。

將輸入放置在選擇之外。

 <select> <option>Select</option> <input type="text"> </select> 

如Andrian所說,select內的輸入不是有效的html。 您必須使用內部輸入創建自定義下拉列表,而不是使用默認的select而是使用ul,li這樣的元素。

暫無
暫無

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

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