dot
dot

Reputation: 15670

using jquery to set value of a select box

I am trying to set the value of a select box using jquery.Here's the code I have:

$(function() {
     $("#contact_types").val($("#contact_type_description").val());
});

I don't get any error messages but the value of the select box is not set correctly. When I debug in the console in Chrome, this is what I get:

> $("#contact_type_description").val()
> "Office"


> $("#contact_types").html()
> "<option value="6">Home</option><option value="4">Mobile</option><option value="5">Office</option>"

Can you tell me what I'm doing wrong?

Upvotes: 0

Views: 117

Answers (2)

Mister Epic
Mister Epic

Reputation: 16743

You need to set the select option's selected property to true, this should probably be in some control's change or keypress event handler:

$('#contacttypes option').each(function(){
   if($(this).text() == SOME_VALUE_YOU_GET_FROM_SOMEWHERE)
    $(this).prop('selected', true);    
}); 

Upvotes: 0

gdoron
gdoron

Reputation: 150273

There is no <option> with the value office, this is what val is looking for, the value, not the innerHTML.

You can use this:

var theValue = $("#contact_type_description").val();
$('#contact_types option').filer(function(){
    return this.innerHTML === theValue;
}).prop('selected', true);

Upvotes: 1

Related Questions