0

I have a strange behaviour with my js code. I do a JsFiddle here : http://jsfiddle.net/wf8G6/2/

I want to update the "option selected" of a select when I check a particular checkbox...

Actually I have to click 3 times to trigger the event...

I check the checkbox => nothing happens I uncheck the checkox => nothing happens I check the checkbox => it works ...

Here is my HTML

<fieldset class="attribute_fieldset" rel="">
    <input class="left cb_group_5" type="checkbox" value="group_5" /> 

    <select name="group_5" id="group_5" class="attribute_select hidden">
        <option value="23" selected="selected" title="non">non</option>
        <option value="24" title="oui">oui</option>
    </select>
</fieldset>

Here is my JS

//if we check a checkbox, we trigger a click on the select below
$('.attribute_fieldset input[type=checkbox]').change(function () {
    var target = '#' + $(this).val();
    $(target + ' option').removeAttr('selected');
    if (this.checked) {
        $(target + ' option[title="oui"]').attr('selected', 'selected');
    } else {
        $(target + ' option[title="non"]').attr('selected', 'selected');
    }
    $(target).trigger('change');
});

What I do wrong ? Please, help me community =)

karthikr
  • 97,368
  • 26
  • 197
  • 188
Raphaël
  • 1,141
  • 3
  • 18
  • 32

1 Answers1

1

If i get you right you want your drop down to change depending on if you have clicked the checkbox.

In your code you have the line

$(target + ' option').removeAttr('selected');

Im not sure why you are removing the attribute selected from all your options, if you remove it your code works fine

$('.attribute_fieldset input[type=checkbox]').change(function(){

    var target = '#'+$(this).val();


    if(this.checked)
    {
        $(target+' option[title="oui"]').attr('selected','selected');
    }
    else
    {
        $(target+' option[title="non"]').attr('selected','selected');
    }


});

http://jsfiddle.net/wf8G6/3/

Also on a side note its better to not keep referencing you elements in the way you are, a more efficient way is like this

$('.attribute_fieldset input[type=checkbox]').change(function(){

    var target = $('#'+$(this).val());


    if(this.checked)
    {
        $('option[title="oui"]',target).attr('selected','selected');

    }
    else
    {
        $('option[title="non"]',target).attr('selected','selected');
    }


});
Dominic Green
  • 10,142
  • 4
  • 30
  • 34