简体   繁体   中英

how to properly echo onclick='function($var)'

When I echo this table :

echo "<table class='aTable'  border='1'>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Telefono</th>
<th>Fecha</th>
<th>Ver Orden</th>
</tr>";

while($row = $gsent->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['IdOrder'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Apellido'] . "</td>";
echo "<td>" . $row['Phone'] . "</td>";
echo "<td>" . $row['TimeStamp'] . "</td>";
echo "<td>" ."<input type='submit' name='ID' value='VER' onclick='showOrder({$row['IdOrder']})'>"."</td>";
echo "</tr>";
}
echo "</table>";

I want the last column to show a button which triggers a Javascript function

    <script>
        function showOrder(IdOrder){
            jQuery('#list-data').val(IdOrder);
            document.getElementById("formOrder").submit();
            console.log('PHP:  ' + IdOrder );

            var delayMillis = 500;
            setTimeout(function() {
              window.location.href = 'ask.php';
               }, delayMillis);
}
</script>

Everything works fine when the button $row['IdOrder'] contains a number, eg 1521 or 00254 but when it has a hexadecimal number it wont work or behaves in a strange way eg on ADAC in chrome console this error shows up:

Uncaught ReferenceError: ADAC is not defined at HTMLInputElement.onclick

Or if the Hex is 39E3 the function runs but I get this number in the function 39000 which I dont know why but is correct because in google if I put 39E3 to decimal I get that number but I dont want the 39E3 to convert itself to 39000 so my guess is that the variable $row['IdOrder'] is beeing Treated different if its start with a number or with a letter, I want $row['IdOrder'] always be treated like a text to avoid this weird conversions if its possible or maybe, do I have to take another path?

If your IdOrder is not a number-only value, you have to wrap it with quotes, to become a string:

"<input type='submit' name='ID' value='VER' onclick='showOrder(\"{$row['IdOrder']}\")'>"

It should print something like:

<input type='submit' name='ID' value='VER' onclick='showOrder("myId")'>

So the compiler won't try to guess that ADAC is an object instead of a string.

Replace

{$row['IdOrder']}

with

\"{$row['IdOrder']}\"

to make it a string.

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