简体   繁体   中英

Move the selected attribute in a select menu using jQuery

I have three product pages. Let's identify them as Hot Chocolate, Mocha Coffee, Espresso

Each page has a form at the bottom, with an identical select menu:

<form>
    <select class="ProductType">
        <option selected>(Please choose)</option>
        <option>Hot Chocolate</option>
        <option>Mocha Coffee</option> 
        <option>Espresso</option>
    </select>
</form>

There's also a surrounding div that contains a unique class value that identifies the page/product. For example:

<div class="hot-chocolate"> ... </div>

I can edit that outside div but I can't manually alter anything within the form tag.

Is it possible to use jQuery to move the selected attribute dynamically to the option that matches the page currently being viewed (ie. that in some way matches the class name of the surrounding div, even when the option value is a phrase with spaces)?

The following assumes you want to select the option with value "Hot Chocolate". Note the class name is case sensitive (must match the case of the option value)

Html (note id attribute added to the <div>

<div id="selection" class="Hot-Chocolate"> ... </div>
....
<form>
  <select class="ProductType">
    <option selected>(Please choose)</option>
    <option>Hot Chocolate</option>
    <option>Mocha Coffee</option> 
    <option>Espresso</option>
  </select>
</form>

Script

var selection = $('#selection').attr('class').replace('-', ' ');
$('.ProductType').val(selection);

Refer Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM