1

I have 5 modals each one with a unique id.

<div class="modal fade" id="<?php echo "game-modal-" . $fetch['id'] ?>" tabindex="-1" role="dialog" aria-labelledby="Game Modal" aria-hidden="true">

In the modals I have a hidden input that echo's the id.

<input type="hidden" name="" value="<?php echo $fetch['id']; ?>" class="game-id">

When I unhide the inputs it displays the correct id depending on which modal is being displayed. I then have a cancel button in the modal that when clicked should display the id. But it doesnt display the correct id just the first one. Why would it send js the wrong id when it is in a unique modal and whats the best approach to this problem?

$('.cancel-button').click(function(){ var gameId = $(".game-id").val(); alert(gameId); });

<button class="btn btn-outline-light btn-sm cancel-button" type="submit">Cancel</button>

awild
  • 49
  • 2
  • 9
  • `var gameId = $(".game-id").val();` That's not constrained to anything specific; it's just finding the first instance of `class="game-id"`, instead of the one you actually want. – Tim Lewis Aug 20 '18 at 22:18
  • That's just it! I'm having trouble on getting the specific input. – awild Aug 20 '18 at 22:27
  • Maybe this will be helpful: https://stackoverflow.com/questions/20357017/jquery-find-input-field-closest-to-button – Don't Panic Aug 20 '18 at 22:30
  • Why not give your cancel button a data attribute like `data-gameId=""` and then change the line `var gameId = $(".game-id").val();` to `var gameId = $(this).attr('data-gameId');`. If you have no other form elements to take care of, this would be my approach. – Yolo Aug 20 '18 at 22:36
  • @Yolo Thank you so much! That worked! – awild Aug 20 '18 at 23:11

0 Answers0