Home > Back-end >  jQuery selector fails when ID contains square brackets
jQuery selector fails when ID contains square brackets

Time:01-26

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]" >
</div>
<div>
  <input type="input" name="map_price[2]" id="products_map_price[2]" >
</div>

CodePudding user response:

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]" >
</div>
<div>
  <input type="input" name="map_price[2]" id="products_map_price[2]" >
</div>

  •  Tags:  
  • Related