Javascript value from field shows up as [object Te

2019-09-07 09:01发布

Using jQuery 1.6.2

HTML that I'm operating on

<select id="langId">
    <option value="0">Argentina - Spanish</option>
    <option value="1">Brazil - Brazil English</option>
</select>

I need to get the string of the selected value (ie: "Brazil - Brazil English")

What I am currently using:

var langVal = $('#langId option[value="' + $('#langId').val() + '"]').contents();

This works to a point. It gives me something like ["Brazil - Brazil English"] which I can access at langVal[0]

If I do console.log(langVal[0]) then I get what I am looking for "Brazil - Brazil English", but if I do something like console.log(("The value is: " + langVal[0])); then what I see is The value is: [object Text]

I have no idea what is causing this [object Text] to show up instead of my value. I've tried the toString() method, but it doesn't help.

The end goal is to get the text value of the selected object into a cookie. The numerical value attribute on the option elements must remain the same.

2条回答
戒情不戒烟
2楼-- · 2019-09-07 09:46

Instead of using $('#langId option[value="' + $('#langId').val() + '"]').contents() you want to use $('#langId option[value="' + $('#langId').val() + '"]').html() or $('#langId option[value="' + $('#langId').val() + '"]').text()

The contents function actually creates a new jQuery object -- not the text value you want.

查看更多
走好不送
3楼-- · 2019-09-07 09:47
$("#langId option:selected").text()

That will get you the text of the currently selected option in your select list.

查看更多
登录 后发表回答