Belgin Fish
Belgin Fish

Reputation: 19857

JQuery Not Changing Select Box Option

I have the following jquery code to change my selected select box option.

   $(function () {

      var prev_id = -1;          
      $('.color_opt').click(function() { 
        if (prev_id != -1)
        {
          $("#"+prev_id).removeClass('opt_sel');
        }
        var current_id = $(this).attr('id');
        var current_color = $(this).data('color');
        $("#product-select-option-0[value=" + current_color +"]").prop("selected","selected") ;
        $("#product-select[value=" + current_id +"]").prop("selected","selected") ;

        $(this).addClass('opt_sel');
        prev_id = current_id;
      });


    });

This is my html

<div id="original_selector" class="select clearfix">
            <div class="selector-wrapper">
                <label>Color</label>
                <select id="product-select-option-0" data-option="option1" class="single-option-selector">
                    <option value="Red">Red</option>
                    <option value="Blue">Blue</option>
                    <option value="Orange">Orange</option>
                </select>
            </div>
            <select id="product-select" name="id" style="display:none">
              <option value="849558613">Red - $29.99</option>            
              <option value="849558617">Blue - $24.99</option>             
              <option value="849558621">Orange - $29.99</option>             
            </select>
        </div>

Everything seems to be executing fine, as the selected class is changing onclick although the value of the select box is not changing for either boxes. The current_id and current_color are being passed just fine as I've checked through an alert.

Any ideas as to why my select box options are not changing?

Upvotes: 0

Views: 792

Answers (2)

Lav
Lav

Reputation: 1896

Dont worry about setting 'selected' attribute instead you can just select the values using following

$("#product-select-option-0").val(current_color);
$("#product-select").val(current_id);

Upvotes: 1

fracz
fracz

Reputation: 21278

Don't use prop to select the desired value. Use val() instead.

$(function () {
  var prev_id = -1;          
  $('.color_opt').click(function() { 
    if (prev_id != -1)
    {
      $("#"+prev_id).removeClass('opt_sel');
    }
    var current_id = $(this).attr('id');
    var current_color = $(this).data('color');
    $("#product-select-option-0").val(current_color);
    $("#product-select").val(current_id);

    $(this).addClass('opt_sel');
    prev_id = current_id;
  });
});

When you use prop, multiple options might gain the selected attribute. What the browser will show as the selected value is unpredictable then.

Upvotes: 1

Related Questions