0

I have a php script that creates a number of inputs whose ID's are in an array. I am trying to check the value in the clicked one but it fails due to the selector being an array, I think. The code I'm using is below. The amt var is undefined. If I change the code to not use arrays, it works. Is there a way to access an ID that is an array element? Here is my jsfiddle.

$(".map-price").keyup(function(event) {
  var id = event.target.id;
  var amt = $("#" + id).val();
  console.log(id + ' ' + amt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <input type="input" name="map_price[1]" id="products_map_price[1]" class="map-price">
</div>
<div>
  <input type="input" name="map_price[2]" id="products_map_price[2]" class="map-price">
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
user3052443
  • 758
  • 1
  • 7
  • 22
  • 2
    Do yourself and all of us a favor and use console logs, not alerts. :) – isherwood Jan 25 '22 at 14:54
  • An ID attribute value is _always_ a string. The only question is whether special characters like brackets break your script. – isherwood Jan 25 '22 at 14:55
  • 1
    Why use jQuery at all to get the value? It's already part of the `target`. `event.target.value`. – Ivar Jan 25 '22 at 14:55
  • 1
    The square brakets are used for attribute selectors.... Like `$("input[type='text']")` – Louys Patrice Bessette Jan 25 '22 at 14:56
  • 1
    Does this answer your question? [Find DOM element by ID when ID contains square brackets?](https://stackoverflow.com/questions/1239095/find-dom-element-by-id-when-id-contains-square-brackets) – isherwood Jan 25 '22 at 14:57

1 Answers1

2

You can pass the whole element into jquery:

$(".map-price").keyup(function(event) {
  var amt = $(event.target).val();
  console.log(event.target.id + ' ' + amt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <input type="input" name="map_price[1]" id="products_map_price[1]" class="map-price">
</div>
<div>
  <input type="input" name="map_price[2]" id="products_map_price[2]" class="map-price">
</div>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
skara9
  • 4,042
  • 1
  • 6
  • 21