簡體   English   中英

如何從選擇框中獲取值?

[英]How can I get a value from the select box?

我想通過使用 JQuery 從所選框中獲取所選選項的值,但它不起作用。

我已經嘗試了一百萬種方法來做到這一點。 嘗試獲取其文本,嘗試從多種方式獲取值。 要知道我的 jquery 變量中有什么。

 $(document).ready(function () { //First thing I tried var category = $('#category').val(); alert(Category); //Second thing I tried var category = $('#category').filter(":selected").val(); alert(Category); //Third thing I tried var category = $('#category').find(":selected").text(); alert(Category); //Fourth thing I tried var category = $('#category').find(":selected").val(); alert(Category); //Fourth thing I tried var category = document.getElementById('category').value; alert(Category); //Now directly taking the value of selected option by id alert($("#category :selected").attr('value')); //These are the code snippets I tried at different times so don't //think that I did this all a time which can obviously throw some //exception. });
 <select class="form-control" id="cateogry" name="category"> <option value="0" disabled selected>Choose Project Category</option> <option value="active">Active Project</option> <option value="drafted">Drafted Project</option> </select>

我在上面給出的所有選項並一一嘗試了所有選項並發出警報以查看它得到了什么,並且警報表示未定義。 我能做什么?

html代碼



<select class="form-control" id="cateogry" name="category">
     <option value="0" disabled selected>Choose Project Category</option>
     <option value="active">Active Project</option>
     <option value="drafted">Drafted Project</option>
</select>

jQuery 代碼

  $('#cateogry').change(function (){

    let value=$(this).val();
    alert(value);

   });

獲取選擇的選項

$( "#cateogry option:selected" ).val();

你的警報有類別(第一個字母大寫),你的變量是類別(沒有大寫,你能確認拼寫錯誤嗎?也許你正在顯示一個不存在的變量,你的一個嘗試正在工作

暫無
暫無

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

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