/    Sign up×
Community /Pin to ProfileBookmark

How to pull a value from a <select> control

I would like to pull the displayed value from a select control, here is an example:

<select id=”test” name=”test” size=”1″>
<option value=”1″>Yes</option>
<option value=”0″>No</option>
</select>

I’d like Javascript to grab the Yes or No of the select, not the 1 or 0.

So, for simplicity, lets use an alert:

alert(document.getElementById(“test”).value)

That produces the alert box with 1, I’d like it to alert saying Yes.

How do I do that?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@DanInMASep 22.2011 — I beleive this will work:

alert(document.getElementById("test").selected.value)
Copy linkTweet thisAlerts:
@xelawhoSep 23.2011 — I have only ever got it working like this (or a minor variation):

[CODE]
var sel=document.getElementById('test');
alert(sel.options[sel.selectedIndex].text);
[/CODE]


but surely there are other ways...
Copy linkTweet thisAlerts:
@KorSep 23.2011 — I would like to pull the displayed [COLOR="Red"]value[/COLOR] from a select control,

[..]

That produces the alert box with 1, I'd like it to alert saying [COLOR="Red"]Yes[/COLOR].
[/QUOTE]

That is not the selected [I]value[/I], that is the selected option's [I]text[/I]. Use the solution provided by [B]xelawho[/B].

I beleive this will work:

alert(document.getElementById("test").selected.value)
[/quote]

[B]DanInMA[/B], are you sure that your solution is written in JavaScript? :rolleyes: Never heard about a property called [B]selected[/B] applied upon a [B]select[/B] element. Neither about a property [B]value[/B] applied upon a property [B]selected[/B]. ?
Copy linkTweet thisAlerts:
@dzirkelbauthorSep 23.2011 — I have only ever got it working like this (or a minor variation):

[CODE]
var sel=document.getElementById('test');
alert(sel.options[sel.selectedIndex].text);
[/CODE]


but surely there are other ways...[/QUOTE]


Thanks, worked like a charm ?
×

Success!

Help @dzirkelb spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...