views:

63

answers:

2

Hello! I need to select a specific item of a combobox in my page when i click in a button. I am using php and javascript code in my page.

Actually i am calling a javascript function at the "onclick" of the button. But i still dont get the right command to do this.

example:

<select id="TEST">
<option> a</option>
<option> b</option>
<option> c</option>
</select>

i want to show the item b when i click in the button.

+6  A: 
<select id="select1">
    ...
</select>
<button onclick="chooseItem('select1', 1)">
<script type="text/javascript">
    function chooseItem(id, index){
        var selectElement = document.getElementById(id);
        selectElement.selectedIndex = index;
    }
</script>

or with jQuery:

<select id="select1">
    ...
</select>
<button id="button1">
<script type="text/javascript">
   $(document).ready(function(){
       $("#button1").click(function(e){
           $("#select1").each(function(){
               this.selectedIndex = 1;
           });
       });
   });

});

Roland Bouman
This is more for Paulo; if you haven't checked out jQuery, you really need to. It can help you with things such as this and simplify your Javascript drastically: http://jquery.com/
Topher Fangio
that's it, thanks!
Paulo
Personally, I think the jQuery solutions is more complicated for this particular case. However, if you are dealing with multiple items, you can write it very concisely with jQuery.
Roland Bouman
The non-jQuery solution is superior in almost every conceivable way, although I'd have the `<script>` element before the button to guarantee the function is available when the user clicks the button.
Tim Down
Tim, that's an excellent point - ideally the `<script>` should be before the button. That said, in my real-world pages I prefer to do all the plumbing after the page has loaded, and I choose whatever method is considered proper for whatever js framework is used.
Roland Bouman
+1  A: 

use selectedIndex property.

rizidoro