[英]How can I get a value from the select box?
I want to get the value of the selected option from the selected box by using JQuery but it ain't working.我想通过使用 JQuery 从所选框中获取所选选项的值,但它不起作用。
I have tried a million ways to do it.我已经尝试了一百万种方法来做到这一点。 Trying to get its text instead, tried to get the value from multiple ways.尝试获取其文本,尝试从多种方式获取值。 To know what is coming in my jquery variable.要知道我的 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>
All the options I have given above and tried all of them one by one and put an alert to see what is it getting and the alert said undefined.我在上面给出的所有选项并一一尝试了所有选项并发出警报以查看它得到了什么,并且警报表示未定义。 What can I do?我能做什么?
Html code 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 code jQuery 代码
$('#cateogry').change(function (){
let value=$(this).val();
alert(value);
});
Get for option selected获取选择的选项
$( "#cateogry option:selected" ).val();
你的警报有类别(第一个字母大写),你的变量是类别(没有大写,你能确认拼写错误吗?也许你正在显示一个不存在的变量,你的一个尝试正在工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.