user1301037 user1301037 - 1 month ago 7
Javascript Question

Javascript / Jquery - Extract the id from a ChildElement

I'm a pretty new to Jquery so I can't figured out why that is not working.

I'm trying to extract the id from a ChildElement.

Html:

<div class="merchant_working_hours_close_time">
<select id="merchant_working_hours_attributes_1476029504945_close_time">
<option value="">close</option>
<option value="00:00:00">0h00</option>
<option value="00:30:00">0h30</option>
<option value="01:00:00">1h00</option>
<option value="01:30:00">1h30</option>
<option value="02:00:00">2h00</option>
<option value="02:30:00">2h30</option>
<option value="03:00:00">3h00</option>
</select>
</div>




The Javascript

var close_time_id = document.getElementsByClassName("merchant_working_hours_close_time").firstElementChild.attr('id');
$('.variable').html(close_time_id);


What i'm doing wrong to return the "merchant_working_hours_attributes_1476029504945_close_time" id from select tag?

Answer

Use jquery selectors and the .children() property and make sure you enclose it in a document ready. Note that I am triggering the function off a click (you might want to do it off a change or other action) and also I am console.logging it for display purposes.

$(document).ready(function(){
  $('.merchant_working_hours_close_time').click(function(){
var close_time_id =$(this).children(0).attr('id');
console.log(close_time_id); //gives merchant_working_hours_attributes_1476029504945_close_time
$('.variable').text('The id of the child element is: ' + close_time_id);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="merchant_working_hours_close_time">
  <select id="merchant_working_hours_attributes_1476029504945_close_time">
    <option value="">close</option>
    <option value="00:00:00">0h00</option>
    <option value="00:30:00">0h30</option>
    <option value="01:00:00">1h00</option>
    <option value="01:30:00">1h30</option>
    <option value="02:00:00">2h00</option>
    <option value="02:30:00">2h30</option>
    <option value="03:00:00">3h00</option>
  </select>
 <span class='variable'></span>
</div>

Comments