filemonczyk filemonczyk - 1 month ago 5
Javascript Question

Trying to insert values to elements generated automatically

Im trying to insert values to elements which id's are generated automatically:

this code works:

<input type="tekst" id="<?php echo $item->getId();?>">
<script>
document.getElementById("<?php echo $item->getId();?>").value =1
</script>


but I dont want to have static value of 1, I'd like to have the value generated automatically so I'm trying to do something like this:

<script>
document.getElementById("<?php echo $item->getId();?>").value =<?php getVotesValue($item->getId());?>
</script>


but this wont work,

function getVotesValue($gifId){
global $db;
(line 115)$dislikes = $db->query("SELECT COUNT(*) as dislikes FROM gif_dislikes WHERE gif_id='$gifId'"); //line 115

$resultArray = $dislikes->fetch_assoc();
$dislikesAmount = $resultArray['dislikes'];
echo $dislikesAmount;
}

Answer

You aren't echoing getVotesValue, so nothing is assigned to your JavaScript variable.

<script>
    document.getElementById("<?php echo $item->getId();?>").value =<?php echo getVotesValue($item->getId());?>
</script>

However, there's no need for any JavaScript here. Try:

<input type="tekst" id="<?php echo $item->getId();?>" value="<?php echo getVotesValue($item->getId());?>">