Question: Change <select> id on click in jQuery

Question

Change <select> id on click in jQuery

Answers 1
Added at 2016-12-30 15:12
Tags
Question

There is a select option in search form and it has an id (e.g. main_cat).

Now I want that when I click on a link('a'), the id of select should be changed with second_cat.

Note Give me solution with nesting div classes on jsFiddle, because main_cat id also used in another section on same page

Here is my sample code:

<div class="widget widget_vehicle_search">
    <div class="search-form-widget">

        <form id="wp-advanced-search" name="wp-advanced-search" class="wp-advanced-search" method="" action="">
            <div id="wpas-main_cat" class="wpas-main_cat wpas-generic-field  wpas-field">
                <div class="label-container">
                    <label for="main_cat">Select A Manufacturer:<i class="icon-help-circled-1 tooltip"></i></label>
                </div>

                <select id="main_cat" name="main_cat">
                    <option value="any">Any Manufacturer</option>
                </select>

            </div>
        </form>
    </div>

</div>

When Click on a link main_cat id changed with second_cat

Hope you understand my question

Answers to

Change &lt;select&gt; id on click in jQuery

nr: #1 dodano: 2016-12-30 15:12

I'm not sure if that what you mean, but you could attach click event to anchor then on click change the id attribute of the select by the new one :

$('a').on('click', function(){
    $('#main_cat').prop('id', 'second_cat');
})

Hope this helps.

$('a').on('click', function(e){
  e.preventDefault();
  
  console.log('Before : '+$('select').prop('id'));
  
  $('#main_cat').prop('id', 'second_cat');
  
  console.log('After : '+$('select').prop('id'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget widget_vehicle_search">
  <div class="search-form-widget">

    <form id="wp-advanced-search" name="wp-advanced-search" class="wp-advanced-search" method="" action="">
      <div id="wpas-main_cat" class="wpas-main_cat wpas-generic-field  wpas-field">
        <div class="label-container">
          <label for="main_cat">Select A Manufacturer:<i class="icon-help-circled-1 tooltip"></i></label>
        </div>

        <select id="main_cat" name="main_cat">
          <option value="any">Any Manufacturer</option>
        </select>

      </div>
    </form>
  </div>
</div>

<br>
<a href='#'>change select id</select>

Source Show
◀ Wstecz