简体   繁体   中英

jQuery selector fails when ID contains square brackets

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM