简体   繁体   中英

Cant access value from the HTML dataset

I am using Dataset to get some different values when doing drag and drop from one div to another. but I am not able to access the additional attributes such as data-customerId when I call the Javascript function.

HTML with PHP dynamic data:

<fieldset id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
    <legend style="color:cadetblue; border:white; width:auto; font:bold">Vacant parking spots</legend>
    <?php $counter = 0; foreach ($sql_get_vacant_spots_results_ as $row) { ?>
        <div id="<?php echo $counter; ?>" data-customerid="<?php echo $arr_users[0]['customer_id']; ?>" data-y="<?php echo $row['spot_no'] ?>" data-z="<?php echo $row['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" ondragstart="drag(event)" width="88" height="31">
            <labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $row['spot_no'] . ' Gate: ' . $row['parking_gate_id'] ?></label>
        </div>
    <?php $counter++; } ?>
</fieldset>

<fieldset id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
    <legend style="color:cadetblue; border:white; width:auto; font:bold">Current parking spots of the customer</legend>
    <?php $count = 0; foreach ($arr_users as $user) { ?>
        <div id="<?php echo $count ?>" data-customerid="<?php echo $user['customer_id'] ?>" data-y="<?php echo $user['spot_id'] ?>" data-z="<?php echo $user['location_id'] ?>" style="float: left; width: 120px;height: 80px;padding: 10px;border-radius: 20px;margin: 10px;background-color: cadetblue;" draggable="true" width="88" height="31">
            <labled style="color: white; font:bold; font-size:large;"><?php echo 'Spot: ' . $user['spot_id'] . ' Gate: ' .  $user['gate_id'] ?></label>
        </div>
    <?php $count++; } ?>
</fieldset>

And here is the Javascript:

   function drop(ev) {
        const el = document.querySelector('#' +ev.dataTransfer.getData("text")); //prints: Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#33' is not a valid selector.
        console.log('drop', el.dataset.customerid);
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));
    }

Fixed by accessing the id like this:

const el = document.querySelector("[id=" + "\'" + ev.dataTransfer.getData("text") + "\'" + "]");

EDIT:

Html element id:

id="count_id<?php echo $counter; ?>"

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