Alex Alex - 2 months ago 6
jQuery Question

Passing form input to jQuery as a variable (to prompt a value)

I have a form where users type in start time and end time of an event (for example in the format HH:mm, like 16:45).

<form action="time.php" method="POST">
<input type="text" name="start" /></td>
<input type="text" name="end" /></td>
<input type="submit" name="submit" value="submit" />
</form>


I would like to prompt automatically a value for end time which depends on the value typed in as start time.
Let's say I want to prompt a value (variable
$endTime
) which is 100 minutes later than start time.

I am trying using jquery:

<script>
$(document).ready(function(){
$('input[name="start"]').change(function() {
$('input[name="end"]').val("<?php echo $endTime ;?>");
});
});
</script>


The problem with the script above is that
input[name="start"]
should be stored as a variable, in order to calculate $endTime accordingly.
Maybe you have a piece of advice.

Answer

You can set the end input using jquery itself without using a variable.

<script>
$(document).ready(function(){
    $('input[name="start"]').change(function() {
        $('input[name="end"]').val(computeEndTime($('input[name="start"]').val()));
    });
function computeEndTime(start){
    var hourstart = start.substr(0, start.indexOf(':'));
    var minutestart = start.substr(start.indexOf(":") + 1);
    var total = hourstart * 60 + minutestart + 100;

    var minutes = total%60;
    var hours = (total - minutes) / 60;
    return hours + ":" + minutes;
}
});
</script>