I have this javascript and php/html code below:
<script>
var examInput = document.getElementById('newAssessment').value;
var dateInput = document.getElementById('newDate').value;
var timeInput = document.getElementById('newTime').value;
function showConfirm(){
var confirmMsg=confirm("Are you sure you want to update the following:" + "\n" + "Exam: " + examInput + "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);
if (confirmMsg==true)
{
submitform();
}
}
</script>
….
<?php
$editsession = "<form action=".htmlentities($_SERVER['PHP_SELF'])." method='post' id='updateForm'>
<p><strong>New Assessment's Date/Start Time:</strong></p>
<table>
<tr>
<th>Assessment:</th>
<td><input type='text' id='newAssessment' name='Assessmentnew' readonly='readonly' value='' /> </td>
</tr>
<tr>
<th>Date:</th>
<td><input type='text' id='newDate' name='Datenew' readonly='readonly' value='' /> </td>
</tr>
<tr>
<th>Start Time:</th>
<td><input type='text' id='newTime' name='Timenew' readonly='readonly' value=''/><span class='timepicker_button_trigger'><img src='Images/clock.gif' alt='Choose Time' /></span> </td>
</tr>
</table>
<div id='datetimeAlert'></div>
</form>
";
echo $editsession;
?>
The problem is that in the confirmation box, it is not displaying the name of the exam, the date and time which are all displayed in the textboxes in the php/html.
For example it should display:
Are you sure you want to update the following:
Exam: DFRER
Date: 20-02-2013
Time: 16:00
Instead it displays:
Are you sure you want to update the following:
Exam: undefined
Date: undefined
Time: undefined
Why is this?
<script>tags execute as soon as they are encountered in the markup. We assume your<script>tag occurs before the HTML it references in itsgetElementById()calls.Since the three lines that set the variables occur outside any function they and are executed immediately, before the DOM is loaded, the respective DOM elements don’t yet exist and the variables become
undefined. Just move them into the function. This has the added benefit of the values being up to date any subsequent time you call the function.