change the contain of select box in jquery

141 views Asked by At

I have 2 select boxes like:

<select id="bu_id">
  <option value="1">India</option>
  <option value="2">US</option>
  <option value="3">UK</option>
</select>

and

<select id="role_id">
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
   <option value="4">Four</option> 
</select>

Now the 2nd select box's text of the option tag should be changed according to user's selection of 1st select box. e.g. if user changes US option, then the second select box shou-ld be looking like:

<select id="role_id">
   <option value="1">One</option>
   <option value="2">Two dollar</option>
   <option value="3">Three</option>
   <option value="4">Four dollar</option>
</select>

I have written my code like:

if($('#bu_id option:selected').text() == 'India'){
    $('#role_id option:contains("Two")').text('Two dollar');
    $('#role_id option:contains("Four")').text('Four dollar');
}

But it is working in firefox, not in chrome.Could you please help me to solve this issue?

Thanks in advance.

1

There are 1 answers

0
Mark S On

I don't see why it won't work on chrome. Usually in a <select> the first <option> is the default. Since in your markup your first <option> is 'India' the code will be executed. See this jsfiddle.

Are you doing this on document ready()? I'm thinking you should wrap this on change() event. Because I can't seem to get the idea why you are only changing the two option (option 2 and 4) and why India's currency is dollars.


The markup and script below is just a proposal. I don't know if this is what you are looking to do or not but just to give you an idea.

<select id="bu_id">
  <option value="Rupee">India</option>
  <option value="Dollar">US</option>
  <option value="Pound">UK</option>
</select>

<select id="role_id">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option> 
</select>

jQuery:

$('#bu_id').change(function(){
    var val = $(this).val();

    $('#role_id option').each(function(){
        var text = $(this).text();       
        text = text.split(' ')[0];

        if($(this).is(':first-child')){
            text = text+' '+val
        }else{
            text = text+' '+val+'s'
        }

        $(this).text(text)        
    });

}).trigger('change');

Check this jsfiddle.