-2

How do I get the value of option 3 in select name period with jQuery?

In Javascript, I use document.form.period.value to access the value when button is clicked

<form name="form">
<select name="link">
  <option value="1">$1000</option>
  <option value="2">$2000</option>
  <option value="3">$3000</option>
  <option value="4">$4000</option>
  <option value="5">$5000</option>
</select>
<input type="button" onclick="alert(document.form.link.value)" value="alert">

<select name="period">
  <option value="1">1 day</option>
  <option value="2">2 day</option>
  <option value="3">3 day</option>
  <option value="4">4 day</option>
  <option value="5">5 day</option>
</select>
<input type="button" onclick="alert(document.form.period.value)" value="alert">
</form>
Dale A. Almaraz
  • 183
  • 1
  • 1
  • 12

1 Answers1

3

I am ashamed to answer this question, but:

$('select[name="period"] > option:nth-child(3)') // get the third option element
$('[name="period"]').val() // get the value of the selected option
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Oh my... Why? Why not `val`? – Yury Tarabanko Aug 01 '14 at 18:15
  • 3
    "I am ashamed to answer this question" is the best part of this answer. It doesn't do what the OP wants. He wants to access the selected value not just the 3rd one. –  Aug 01 '14 at 18:15
  • 1
    OP didn't say that it will be the selected option – Paul S. Aug 01 '14 at 18:16
  • 1
    + 1 This is almost bang on, just missing the val(). Can't believe it was down voted so fast – sheavens Aug 01 '14 at 18:17
  • 1
    @YuryTarabanko if you use `.val` it will return the value of the selected element. This guy wants to get the value of the third option, not the value of the selected option. – Marco Bonelli Aug 01 '14 at 18:18
  • @MarcoBonelli the question is poorly phrased, since the OP specifically said he returns the value of the `period` element (i.e. the selected option) and _not_ that of the "third option element". – Alnitak Aug 01 '14 at 18:19
  • 1
    @MarcoBonelli according to `document.form.period.value` it is that what OP wants :) – Yury Tarabanko Aug 01 '14 at 18:19
  • The answer gets the third option. The question was how do I get the value of the third option. Why the question was asked in the first place I don't know – sheavens Aug 01 '14 at 18:19
  • "How do I get the value of option 3 in select name period with jQuery?" what else does this mean if it doesn't mean "i want the value of option 3 in select period"???? – Marco Bonelli Aug 01 '14 at 18:21
  • 1
    Can't believe you got down voted Marco :( – sheavens Aug 01 '14 at 18:24
  • 1
    I'm a bit confused lol, idk why people should vote me down or vote down this question. Everyone has been a newbie, me too. So if the OP doesn't know how to do it why shouldn't we answer him? – Marco Bonelli Aug 01 '14 at 18:28