views:

45

answers:

3

I am looking for a way to change the option value from a select tag when users click on a link.

For example I have a select option html:

<select> <option value="0">Please Select</option> 
<option value="1">red</option> 
<option value="2">white</option> 
</select>

And I have 2 links <a href="#" title="red" class="preview_link">red</a> <a href="#" title="white">white</a> When user clicks red the option will switch to red and white will switch to white. I am using the following code but it is not working.

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
        jQuery(this).parent('p').children("select :selected").text(title);
 });

Any suggestions?

+3  A: 

Your way will set the option's text to the title attribute. Try:

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
    jQuery(this).parent('p').find("select option").filter(function() {
        return $(this).text() == title;
    }).attr('selected', 'selected');
 });

See filter.

karim79
I tried it but nothing changes.
Rick
Are you selecting the `select` correctly? Try `alert(jQuery(this).parent('p').find("select option").length);` within your event handler.
karim79
I ran that it comes back with 9...
Rick
So that's working. My last thought is, in your post, the markup for one of your options is missing a double quote on the value attribute: `<option value=2">` should be `<option value="2">`. Try fixing that? Also, I noticed that you are using `children`, which I edited to `find` in my answer (but I'm not sure that makes any difference).
karim79
on that's just a typo here... in the code its correct...
Rick
@Rick: In your code example you've the `class="preview_link"` set in only the first link. This should be on all links. Karim's code by the way works fine. [Here's a live demo](http://jsfiddle.net/yr2Ne/).
BalusC
yes it is on all links...just missed typed it here...Let me dig further to see what is going on...Thanks guys for all the help!
Rick
@BalusC - thanks for that :)
karim79
A: 

Hmm, you're going about this wrong: Instead of changing the text of the selected option you need to loop over the <option/> elements and select the appropriate one, something like this:

$("select option").each(function() { 
    if($(this).text() == "red")) {
        this.selected = true; 
    }
});

Edit: There might be a select() function in jQuery. If that's the case then use that over the DOM property.

Brad Heller
you might be on to something...but i tried it and nothing changes...
Rick
A: 

This?

$("select #some-option").attr("selected", "selected");

Or this?

$("select").val(index);
tjko