2 Replies - 783 Views - Last Post: 26 November 2012 - 12:46 PM

#1 drayarms  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 178
  • Joined: 18-May 11

How to change the value of a select menu onchange

Posted 26 November 2012 - 02:53 AM

I thought this was going to be a simple problem but it stumped me. Basically what I want to do is alert the id value of the option that is currently being displayed from a select menu. So if I select English, I want "en" to be alerted and if I select Spanish I want "es" alerted. So far with what I have, only "es" gets alerted regardless of which option I select. I guess it is because, the first child of the select menu is automatically chosen according to the code. So how do I make this work the way I want?
I also tried

$("option").change(function(){
alert($(this).attr("id"));
});

but it didn't work




<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
  $("select").change(function(){
    alert($(this).children().attr("id"));
  });
});
</script>
</head>
<body>

<form>

<select id = "lang">

<option id = "es" value = "es">Spanish</option>
<option id = "en" value = "en">English</option>

</select>

</form>

</body>
</html>





Is This A Good Question/Topic? 0
  • +

Replies To: How to change the value of a select menu onchange

#2 Kruithne  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 99
  • View blog
  • Posts: 442
  • Joined: 28-July 09

Re: How to change the value of a select menu onchange

Posted 26 November 2012 - 07:22 AM

Hello there,

What you want to be doing is getting the value of the select, which can be gained using the jQuery function .val().
$(document).ready(function(){
  $("select").change(function(){
    alert($(this).val());
  });
});

The .children() function is returning all of the children to the select, which means all of them, not just the one that been selected.
Was This Post Helpful? 1
  • +
  • -

#3 drayarms  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 178
  • Joined: 18-May 11

Re: How to change the value of a select menu onchange

Posted 26 November 2012 - 12:46 PM

@Kruithne, thanks, that worked.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1