Maria Khan Maria Khan - 6 months ago 14
jQuery Question

Jquery find() not working with two ids one having the substring of the other

I have HTML code like this

<div id="city-parrent">
<input id="london" type="checkbox" value="London" name="c_city_2">
<input id="london_r" type="checkbox" value="London" name="c_city_r_2">
</div>


When I want to select the first check box with

var object_found = $("#city-parrent").find("#london");
alert(object_found.val());


it gives an undefined alert

When I select the second one with the same code it does not give the undefined alert

var object_found = $("#city-parrent").find("#london_r");
alert(object_found.val());


Normally this code is fine but I have this code in a for loop where this issue arises. Here is the for loop
[See the for loop]]1

Prs Prs
Answer

Loop through the array and check if the element exist or not. This will prevent you from getting error. No need to .find() for id just use normal selector $('#id') because id will be only one there, else you will get the first one.

var array_cont = ['london', 'london_r']
array_cont.map(function(ac) {
    $elem = $('#' + ac);
    if ($elem.length) {
        alert($elem.val());
        $elem.attr('checked', true);
    }
})

var array_cont = ['london', 'london_r']
array_cont.map(function(ac) {
  $elem = $('#' + ac);
  if ($elem.length) {
    alert($elem.val());
    $elem.attr('checked', true);
  }
})
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="city-parrent">
  <input id="london" type="checkbox" value="London" name="c_city_2">
  <input id="london_r" type="checkbox" value="London2" name="c_city_r_2">
</div>