Home > Software engineering >  how to call id with value <?php echo $ ?> in javascript
how to call id with value <?php echo $ ?> in javascript

Time:04-01

i have div with id like this

<div id='alert<?php echo $row['no']?>'>
<b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
</div>

and i need to call that id in javascript,

i try like this but the value not right

$("#alert<?php echo $row['no'] ?>").hide();

how to fix it

thankyou

CodePudding user response:

You need to include jQuery CDN

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<script>
   $("#alert<?php echo $row['no'] ?>").hide();
</script>

CodePudding user response:

I'm assuming that you have something like this:

foreach($result as $row){
  ?>
  <div id='alert<?php echo $row['no']?>'>
    <b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
  </div>
  <script>$("#alert<?php echo $row['no'] ?>").hide();</script>
  <?php
}

Otherwise if the script-tag is outside the loop then it wount work. Another solution would be to make a function let say hideAlert(div) and do something like this:

<?php

foreach($result as $row){
  ?>
  <div onl oad="hideAlert(this)">
    <b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
  </div>
  <?php
}
?>

<script>
  function hideAlert(div){
    div.hide();
  }
</script>

if you need the id to reference to it later you could just change the code like this:

foreach($result as $row){
  ?>
  <div onl oad="hideAlert(<?php echo $row['no']; ?>)">
    <b style='font-size:12px; color: red'>*DUPLICATE ID CUSTOMER</b>
  </div>
  <?php
}
?>

<script>
  function hideAlert(id){
    $(`#alert${id}`).hide();
  }
</script>

Keep in mind that I'm not an expert on jQuery soo I'm not really sure if this works but i hope it helps :)

  • Related