简体   繁体   中英

JQuery data-attribute is undefined on change of a select

I try to create options and after set data of jQuery object dynamically in a select with this mode but not work.

This is my HTML code for print shops options and give it a data-attribute called "data-last-sync-shop"

<select id="shopSelect" 
        onchange="$('#lastSync').text($(this).data('lastSyncShop'));" 
        name="shop_select">

    <option value=""></option>

    <?php foreach ($shops as $code => $info) { ?>
        <option value="<?= $code ?>" 
                data-last-sync-shop="<?= $info['last_sync'] ?>">
            <?= $info['description'] ?>
        </option>
    <?php } ?>
</select>
<span id="lastSync">-</span>

If i debug the onchange event of select the data-attribute is undefined but if I inspect the HTML code generated by PHP the data-attribute of the options are correctly populate. Why? Where is my wrong? Thanks for answers.

I add console.log() as here:

<select id="shopSelect" 
        onchange="console.log($(this).data('lastSyncShop'));" <!-- undefined --> 
        name="filtro[codice_shop_select]">

您需要定位:selected option元素。

 $(this).find('option:selected').data('lastSyncShop')

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