简体   繁体   English

jquery获取选定的选项值给出未定义

[英]jquery get selected option value giving undefined

I am trying to get selected option value from post format Wordpress dashboard.我正在尝试从帖子格式 Wordpress 仪表板中获取选定的选项值。 But when I am trying to get option value in alert also in the console, it is giving me undefined.但是,当我试图在控制台中也在警报中获取选项值时,它给了我未定义的信息。 Is there anywhere I am doing wrong?有什么地方我做错了吗?

(function ($){
    "use strict";

    $(document).ready(function () {

        var conceptName = $('#post-format-selector-0 ').find("option:selected").val();

        var values = $('#post-format-selector-0 :selected').val();

        alert(conceptName);

        console.log(values);

    });
})(jQuery);

在此处输入图片说明

screenshot1截图1

在此处输入图片说明

screenshot2截图2

在此处输入图片说明

Just use the children() function and pass your selector只需使用children()函数并传递您的selector

var conceptName = $('#post-format-selector-0 ').children("option:selected").val();

take a lock at this script锁定这个脚本

(function ($){
"use strict";

$(document).ready(function () {
       alert( "val:" + $('#post-format-selector-0 ').val());
       alert( "find:" + $('#post-format-selector-0 ').find("option:selected").val());
       alert( "children:" + $('#post-format-selector-0 ').children("option:selected").val());
});
})(jQuery);

To get value of selected option获取所选选项的值

var conceptName = $('#post-format-selector-0 option:selected').val();

To get text of selected option获取所选选项的文本

var conceptName = $('#post-format-selector-0 option:selected').text();

You can just use .val() on the select element:您可以在select元素上使用.val()

 $(function() { $('button').on('click', function() { $('pre').html($('#demo').val()); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="demo"> <option value="foo">Foo</option> <option value="bar">Bar</option> </select> <button>Get value</button> <pre></pre>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM