jQuery检索并设置html select元素的选定选项值 [英] jQuery to retrieve and set selected option value of html select element

查看:110
本文介绍了jQuery检索并设置html select元素的选定选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery检索和设置选择元素(下拉列表)的选定值.

I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery.

对于检索,我尝试了$("#myId").find(':selected').val()$("#myId").val(),但是都返回未定义.

for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined.

任何对此问题的见解将不胜感激.

Any insight into this problem would be much appreciated.

推荐答案

目前您所拥有的方式是正确的.选择的ID可能与您所说的不符,或者dom中存在一些问题.

The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.

在W3c的此处中检查元素的ID并检查标记是否有效.

Check the Id of the element and also check your markup validates at here at W3c.

没有有效的dom,jQuery无法与选择器一起正常工作.

Without a valid dom jQuery cannot work correctly with the selectors.

如果ID正确且您的dom进行了验证,则适用以下条件:

If the id's are correct and your dom validates then the following applies:

要读取选择选项值

$('#selectId').val();

设置选择选项值

$('#selectId').val('newValue');

阅读所选文本

$('#selectId>option:selected').text();

这篇关于jQuery检索并设置html select元素的选定选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆