0

Here in this code, when I am displaying array in a form. I need to iterate over array, so that I can perform my code operation. My problem is jquery is only fetching first element. Can someone suggest what need to be done here, so that I can access all the elements.

<?php foreach($packs as $item) { ?>                                                 
  <br/>
  <label> Fee: </label>  
  <input type="text" id="price" name="price" value=<?php echo $item ?> />
  <input type="text" id="discount" placeholder="discount" name="discount"  value="10%" />
  <br/>                                                 
<?php } ?>  
jQuery(function($) {          
  $('#price').change(function() {
    alert($(this).val());
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 4
    You're repeating the same `id` on multiple elements as they're created in your loop. This is invalid as they *have* to be unique. Use a `class` instead. – Rory McCrossan Apr 30 '20 at 13:17
  • "have to be" => "should be" – Taplar Apr 30 '20 at 13:27
  • 1
    @Taplar not sure what you mean. The `id` cannot be repeated. It has to be unique. – Rory McCrossan Apr 30 '20 at 13:32
  • Thanks for answer. In my code, I need to iterate the array, and find the sum of product of price and discount. Can you suggest me what should i do, as both are input type. – Rakesh Singh Apr 30 '20 at 13:32
  • @RoryMcCrossan Give `$('[id="price"]')` or `$("#price, #price")` a whirl and see if your opinion on that matter changes. Ids **should** be unique, but technically there are work arounds. To say something *must* be something, infers there is no alternative. – Taplar Apr 30 '20 at 13:35
  • 1
    Just because there's a hacky workaround doesn't mean you should do it. The HTML spec says no duplicates, then there should be no duplicates. – Rory McCrossan Apr 30 '20 at 13:38
  • I'm not saying you should. I'm pointing out a technicality of your statement being inaccurate. Regardless of if something should be done or not, I believe it is always worth while to be aware of the possibilities, and how they affect how "true" the things we say are. – Taplar Apr 30 '20 at 13:40
  • I'll have to agree to disagree on that one :) – Rory McCrossan Apr 30 '20 at 13:47

0 Answers0