How to use JQuery to set the value of 2 html form select elements depending on the value of another
Posted
by Chris Stevenson
on Stack Overflow
See other posts from Stack Overflow
or by Chris Stevenson
Published on 2010-03-18T16:49:10Z
Indexed on
2010/03/18
16:51 UTC
Read the original article
Hit count: 456
My Javascript and JQuery skills are poor at best and this is **
I have the following three elements in a form :
<select name="event_time_start_hours">
<option value="blank" disabled="disabled">Hours</option>
<option value="blank" disabled="disabled"> </option>
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
<option value="05">5</option>
<option value="06">6</option>
<option value="07">7</option>
<option value="08">8</option>
<option value="09">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="midnight">Midnight</option>
<option value="midday">Midday</option>
</select>
<select name="event_time_start_minutes">
<option value="blank" disabled="disabled">Minutes</option>
<option value="blank" disabled="disabled"> </option>
<option value="00">00</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
</select>
<select name="event_time_start_ampm">
<option value="blank" disabled="disabled">AM / PM</option>
<option value="blank" disabled="disabled"> </option>
<option value="am">AM</option>
<option value="pm">PM</option>
</select>
Quite simply, when either 'midnight' or 'midday' is selected in "event_time_start_hours", I want the values of "event_time_start_minutes" and "event_time_start_ampm" to change to "00" and "am" respectively.
My VERY poor piece of Javascript says this so far :
$(document).ready(function() {
$('#event_time_start_hours').change(function() {
if($('#event_time_start_hours').val('midnight')) {
$('#event_time_start_minutes').val('00');
}
});
});
... and whilst I'm not terribly surprised it doesn't work, I'm at a loss as to what to do next.
I want to do this purely for visual reasons for the user as when the form submits I ignore the "minutes" and "am/pm". I'm trying to decide whether it would be best to change the selected values, change the selected values and then disable the element or hide them altogether. However, without any success in getting anything to happen at all I haven't been able to try the different approaches to see what feels right.
I've ruled out the obvious things like a duplicate element ID or simply not linking to JQuery.
Thank you.
© Stack Overflow or respective owner