PHP concatenation $i in jQuery-ThrowExceptions

Exception or error:

Bit of a strange one, I have a webpage that iterates through a set number of times using while ($i <= 21):. During this iteration I have a dropdown in each which displays some values I pulled from a database, at this point that specific value doesn’t matter but the id of each dropdown uses the value of $i. For example:

<select name="dropdown<?php echo $i; ?>" id="dropdown<?php echo $i; ?>">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

What I am then wanting to do is take the value selected from that dropdown and place in another field that also has the id corresponding to the iteration number, for example:

<textarea name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>"></textarea>

I am using the following code for the jQuery to get the value from the dropdown and put it into the textarea:

<script>
  $("#dropdown<?php echo $i ?>").on("change",function(){
      //Getting Value
      var selValue = $("#dropdown<?php echo $i ?>").val();
      //Setting Value
      $("#textfield<?php echo $i ?>").val(selValue);
  });  
</script>

However it doesnt seem to like the use of <?php echo $i ?> part as if i replace that with for example 2 or 3 then it works for that iteration.

I have tried setting the variable in PHP like: $textfield= 'textfield'.$i; and the using this as a whole in jQuery like this: $("#<?php echo $textfield ?>").val(selValue); but it doesnt like that either. Interstining if I change it to $textfield= 'textfield'.'2'; or $textfield= 'textfield2'; it works. Seems like it doesnt like my use of $i, is it the PHP concatenation that it doesnt like?

Anyone experienced this or know of a fix?

How to solve:

Huge fixes are required in your code but will explain the solution in minimal coding.

use array in name,dont use id,use class and data attribute to store the loop value as follows

<select name="dropdown[]" class="dropdown" data-id="<?php echo $i; ?>">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

<textarea name="textfield[]" class="textfield<?php echo $i; ?>"></textarea>

now in script single piece of code is enough to perform your operation with the help of class dropdown and dynamic class textfield

 <script>
 $(".dropdown").on("change",function(){
     //Getting Value
     var selValue = $(this).val();
     var dynamic_id =  $(this).data('id');
     //Setting Value
     $(".textfield"+dynamic_id).val(selValue);
 });  
 </script>

Leave a Reply

Your email address will not be published. Required fields are marked *