I am trying to do some arithmetic on values entered into a form using select option values. For some reason, I am getting undefined in the console instead of the result value.
function sum() {
const Start = Number(document.getElementById('Start1').value);
const End = Number(document.getElementById('End1').value);
const select = document.querySelector('select');
const choice = select.value;
let result;
select.addEventListener('change', setValue);
function setValue() {
if (choice === 'AM->PM') {
result = (12 - Start) (End);
}
console.log(result);
document.getElementById('txtresult').value = result;
}
}
<div id="box1">
<label for="Starting">Date:</label>
<input type="date" id="Date" name="Date"><br>
<label for="Starting">Start Time:</label>
<input type="text" id="Start1" placeholder="Start Time" name="Start_Time">
<!--Input #1-->
<br>
<label for="End Time">End Time:</label>
<input type="text" id="End1" placeholder="End Time" name="End_Time" onkeyup="sum()">
<!--Input #2-->
<select id="AM/PM">
<option value="">--AM/PM--</option>
<option value="AM">AM->AM</option>
<option value="AM">AM->PM</option>
<option value="AM">PM->AM</option>
<option value="AM">PM->PM</option>
</select><br>
<label for="result">Hrs Worked:</label>
<input type="text" id="txtresult" placeholder="Result"></p><br>
</div>
Please let me know what I am doing wrong.
CodePudding user response:
In your HTML, you have all of the <option>
s defined with value="AM"
except for the first (for which the value is empty). Because of this, your if
within setValue
:
if (choice==='AM->PM' ){
result = (12-Start) (End);
}
will never evaluate to true
and will therefore never set result
to a value; it will remain undefined
because you initialize it with let result;
.
I would also like to point out that you are declaring const choice = select.value;
in the sum
function, but are not changing its value within the callback on change
of the <select>
. In effect, the value of choice
will always be whatever the selected value is when sum
is executed, and will not change when setValue
is executed upon the user changing the select
box.
Try changing your setValue
function to this:
function setValue(){
choice = select.value;
if (choice==='AM->PM' ){
result = (12-Start) (End);
}
console.log(result);
document.getElementById('txtresult').value = result;
}
and your HTML option
s to this:
<option value="">--AM/PM--</option>
<option value="AM->AM">AM->AM</option>
<option value="AM->PM">AM->PM</option>
<option value="PM->AM">PM->AM</option>
<option value="PM->PM">PM->PM</option>