Creating dynamic button ID and sending the ID to a javascript function. Javascript function is not accepting

Trying to add dynamic id for button as

  echo "<input type='button' id='$butid' class='btn btn-info' data-target='#prodetails' onclick='show($butid)' value='Details'>";

in javascript function ive written

   <script>
           function show(x)
           {

               document.getElementById("prodetails").innerHTML=x;
           }
   </script>

Not able to recieve the value passed in the function call. Value passed is varchar getting output as [object HTMLInputElement]

Upvotes: 0

Views: 378

Answers (2)

Pranav Deshpande
Pranav Deshpande

Reputation: 164

<input type='button' id=<?= $yourId ?> class='btn btn-info' data-target=<?= $dataYouWantToSend ?> onclick=show(this) value='Details'>


<script>
           function show(x)
           {

               x.innerHTML=x.data-target;  //data-target is equal to the data you want to send to function this will add innerHTML = your dynamic data 
               console.log(x.id); //here you will get your dynamic id

           }
   </script>

Modify your code as shown above , and It will work for sure , see you can not write html code in php "echo" , instead you should go for where you want php code in HTML

Second thing suppose you want to send data to function then assign your data to the new attribute like you have written data-target

and pass the function "This" , this means the current element , in your case its button

Then access your data and id by " . " operator for e.g. x.id

I hope it will help you :)

Remember : <?php echo "HII" ; ?> can be written as <?= "Hii" ?>

Upvotes: 1

nAviD
nAviD

Reputation: 3281

If you really want to get Id of element, based on what I guess about what you want to do you have to surround it with quotation marks (fix this part): onclick='"show($butid)"' .

Upvotes: 0

Related Questions