kate tango kate tango - 5 months ago 6
jQuery Question

javascript - manipulate dropdownlist with another dropdown

im new in programming and javascript noob so i need you guys help.

i have 2 drop drown list and i am trying to manipulate one drop down list using another dropdown list through the help of javascript. both drop down list consists of time in hrs, start time and end time.

the dropdown list looks like this

<!-- start time -->
<div id="start">
<p>Start time</p>
<select name="select1" id="select1" >
<option value="8:00">8:00</option>
<option value="8:30">8:30</option>
<option value="9:00">9:00</option>
<option value="9:30">9:30</option>


</select>
</div>


<!--end time -->
<div id="end">
<p>End time</p>
<select name="select2" id="select2">
<option value="8:30">8:30</option>
<option value="9:00">9:00</option>
<option value="9:30">9:30</option>
<option value="10:00">10:00</option>
</select>
</div>


what i am trying to accomplish is to make sure the end time doesn't start before the start time, and also the start time to end time is a limit of 2 hours. is there anyway of doing this using javascript?? no matter how much i search i can't seem to find the solution in the internet. thankyou

Answer

Quick snippet, mark the added leading 0 to the value to make the time strings comparable.

$('#select1').on('change', function() {
  if($(this).val() > $('#select2').val())
    $('#select2').val($(this).val());
  $('#select2 option').each(function() {
    if($(this).attr('value') < $('#select1').val())
      {
        $(this).hide();
        }
    else
      $(this).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="start">
        <p>Start time</p>
        <select name="select1" id="select1" >
            <option value="08:00">8:00</option>
            <option value="08:30">8:30</option>
            <option value="09:00">9:00</option>
             <option value="09:30">9:30</option>


        </select>
    </div>


            <!--end time -->
    <div id="end">
        <p>End time</p>
        <select name="select2" id="select2">
            <option value="08:30">8:30</option>
            <option value="09:00">9:00</option>
            <option value="09:30">9:30</option>
            <option value="10:00">10:00</option>
         </select>
    </div>

Comments