简体   繁体   中英

PHP / javascript — pass select option data/attributes to function with inline onchange

How would I pass the selected option from this select:

<select name="" id="" onchange="return selectType(// the selected option)">
    <?php foreach ($options as $key => $option) { ?>
      <option
        class=""
        data-optionname="<?= $option["name"] ?>"
        data-patterns="<?= join(",", $option["Pattern"]) ?>"
      >
          <?= $option["name"] ?></option>
    <?php } ?>
</select>

To this function:

<script>
function selectType(option) {
  patterns = $(option).data("patterns").split(",");
  patterns.push(".zip");
  currtype = $(option).data("optionname");
}
</script>

You have this:

<select name="" id="" onchange="return selectType(this)">
    <?php foreach ($options as $key => $option) { ?>
      <option href="#"
        class=""
        data-optionname="<?= $option["name"] ?>"
        data-patterns="<?= join(",", $option["Pattern"]) ?>"
      >
          <?= $option["name"] ?></option>
    <?php } ?>
</select>

And your JS:

<script>
function selectType(option) {
    alert(option.value);
}
</script>

There is your selected element.

If you need to get the data attribute you can use:

$(option).find("option:selected").data("optionname");

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