submit event is firing without checking validation or showing confirmation - javascript

My page is submitting straight away without checking for validation or displaying the alert. I believe the submit is firing early but is my issue that I have multiple forms?
My question is how can I get the submit to work as it should do where it checks the validation and if that is successful, display the confirmation?
I have had to post my whole code so that you can see the order of the code, because the order of the code maybe my downfall:
<script type="text/javascript">
$(document).ready(function () {
$('#sessionsDrop').change(function () {
$('#targetdiv').hide();
if ($(this).val() !== '') {
var text = $(this).find('option:selected').text();
var split = text.split(' - ');
$('#currentId').val($(this).find('option:selected').val());
$('#currentAssessment').val(split[0]);
$('#currentDate').val(split[1]);
$('#currentTime').val(split[2]);
} else {
$('#currentAssessment,#currentDate,#currentTime,#currentId').val('');
}
});
});
function validation(e) {
var isDataValid = true;
var moduleTextO = document.getElementById("modulesDrop");
var errModuleMsgO = document.getElementById("moduleAlert");
if (moduleTextO.value == "") {
$('#targetdiv').hide();
$('#assessmentForm').hide();
$('#choiceForm').hide();
$('#submitchoicebtn').hide();
errModuleMsgO.innerHTML = "Please Select a Module";
isDataValid = false;
} else {
errModuleMsgO.innerHTML = "";
}
if (isDataValid === false) {
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation(); //VERY important
}
e.returnValue = false;
e.cancelBubble = true;
}
return isDataValid;
}
function choicevalidation() {
var isDataValid = true;
var currentAssesO = document.getElementById("currentAssessment");
var currentAssesMsgO = document.getElementById("currentAlert");
currentAssesMsgO.innerHTML = "";
if (currentAssesO.value == "") {
$('#targetdiv').hide();
currentAssesMsgO.innerHTML = "Please Select an Assessment to edit from the Assessment Drop Down Menu";
isDataValid = false;
} else {
currentAssesMsgO.innerHTML = "";
}
return isDataValid;
}
function showConfirm() {
var examInput = document.getElementById('curentAssessment').value;
var dateInput = document.getElementById('currentDate').value;
var timeInput = document.getElementById('currentTime').value;
if (choicevalidation()) {
var confirmMsg = confirm("Are you sure you want to take the following Assessment:" + "\n" + "Exam: " + examInput + "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);
if (confirmMsg == true) {
submitform();
}
}
}
$('#choiceForm').on('submit', showConfirm);
</script>
<h1>TAKE AN ASSESSMENT</h1> //FORM 1
<form action="assessmentchoice.php" method="post" onsubmit="return validation(event);">
<table>
<tr>
<th>Module:
<select name="modules" id="modulesDrop">
<option value="">Please Select</option>
<option value="CHI2513_Systems Strategy_1">CHI2513 - Systems Strategy</option>
<option value="CHT2220_Interactive Systems_4">CHT2220 - Interactive Systems</option>
</select>
</th>
</tr>
</table>
<p>
<input id="moduleSubmit" type="submit" value="Submit Module" name="moduleSubmit"
/>
</p>
<div id="moduleAlert"></div>
<div id="targetdiv"></div>
</form>//FORM 2
<div id='lt-container'>
<form action='assessmentchoice.php' method='post' id='assessmentForm'>
<p id='warnings'></p>
<p><strong>Selected Module:</strong> CHI2513 - Systems Strategy
<input type='hidden'
value='1'>
</p>
<p><strong>Assessments:</strong>
<select name="session" id="sessionsDrop">
<option value="">Please Select</option>
<option value='28'>LDREW - 09-01-2013 - 09:00</option>
<option value='29'>BQNYF - 10-01-2013 - 10:00</option>
<option value='22' disabled>WDFRK - 17-01-2013 - 09:00</option>
<option value='26' disabled>POKUB1 - 25-01-2013 - 15:00</option>
</select>
</p>
</form>
</div>
<div id='rt-container'>//FORM 3 (This is where when submitted it should show confirmation)
<form
id='choiceForm' action='assessment.php' method='post'>
<p><strong>Chosen Assessment:</strong>
</p>
<table>
<tr>
<th></th>
<td>
<input type='hidden' id='currentId' name='Idcurrent' readonly='readonly'
value='' />
</td>
</tr>
<tr>
<th>Assessment:</th>
<td>
<input type='text' id='currentAssessment' name='Assessmentcurrent' readonly='readonly'
value='' />
</td>
</tr>
<tr>
<th>Date:</th>
<td>
<input type='text' id='currentDate' name='Datecurrent' readonly='readonly'
value='' />
</td>
</tr>
<tr>
<th>Start Time:</th>
<td>
<input type='text' id='currentTime' name='Timecurrent' readonly='readonly'
value='' />
</td>
</tr>
</table>
<div id='currentAlert'></div>
<p id='submitchoicebtn'>
<button id='choiceSubmit'>Choose Assessment</button>
</p>
</form>

here is a DEMO
try to change following line:
function showConfirm() { /* your existing code */ }
into
function showConfirm(e) {
e.preventDefault();
/* your existing code */
return false;
}
Have you already tried this:
function showConfirm(e) {
e.preventDefault();
var examInput = document.getElementById('curentAssessment').value;
var dateInput = document.getElementById('currentDate').value;
var timeInput = document.getElementById('currentTime').value;
if (choicevalidation()) {
return confirm("Are you sure you want to take the following Assessment:" + "\n" + "Exam: " + examInput + "\n" + "Date: " + dateInput + "\n" + "Time: " + timeInput);
}
return false;
}
$('#choiceSubmit').on('click', function(e) {
if (showConfirm(e)) {
$('#choiceForm').submit();
}
});

Your forms aren't nested so it shouldn't be because there are multiple.
Try removing all of the code in your validation function so that it only returns false:
function validation(e) {
return false;
}
If this works, you'll know the problem lies within your JavaScript and not the HTML. From there you can add back more and more of the function until you discover which part is causing the issue.

i think this line if ($(this).val() !== '') { should be like this if ($(this).val() != '') {
also as stated in another answers add this: e.preventDefault();

I would use the following code
$('#choiceSubmit').click(function(e) {
e.preventDefault();
var x = 0;
if (showConfirm(e)) {
$('#choiceForm').submit();
}
});
Have you used firebug or inspector (chrome/ie) and stepped through the javascript? In the above case, i'd add a breakpoint at the e.preventDefault() method. If it hits this, then the issue is within the javascript. if not then the javascript is not even bound to the submit button.

Related

Can two or more conditional statements placed inside a function in javascript?

I am newbie in JavaScript. Can't find answer for this. I am not sure whether it is relevant.
I have a registration form with 2 fields.On submit, it should be validated. Here in my code, first written if condition only works. If the first if statement is commented, second if condition works.
HTML CODE :
<body>
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
</body>
JS:
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
In JSFiddle, it gives a error like
{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x56b3ed0>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x5c03510>, 'help_text': '', 'name': 'js_wrap'}"}
I donno what this error means!
You have to rewrite your validation code a bit.
Check demo - Demo:
Your problems:
function returns before gender is checked;
you cannot check multiple checkboxes this way: if(gender.checked)
Below is the working code
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form();">Submit</button>
</form>
</div>
When the function hits a return line, it leaves (ie returns from) the function and doesn't execute anything else in that function.
What people usually do is have a variable called valid or something similar that defaults to true. Then they have if statements that check only for things that would make the form invalid. If one of those if statements gets tripped, it handles the issue (eg telling the user that they need to fill in their gender) and sets valid to false. At the end, and only at the end, it returns valid. This way, if anything is making the form invalid, the function will return invalid, but nothing bad will happen if more than one if statement gets tripped because you can set valid to be false as many times as you want without causing any issues.
You can do it in this way.
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
var boolValidateName = validateName(name);
var boolValidateGnder = validateGnder(name);
if(boolValidateName && boolValidateGnder){
//if both are validate
}else{
//if either of or both not validate
}
}
var validateName = function (name){
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
}
var validateGender = function(gender){
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
Your return statement is not placed very well.
You can break your business login into function and call it.So,every return statement get an equal chance to run.
getElementsByName will return nodelist. You will have to iterate it to get the checked value.
Also note, return ends the current function and returns execution flow to the calling function hence any line of code after execution of return will not be executed.
Do not forget to empty('') the error messages.
Try this:
function validate_form() {
var name = document.getElementById("id1").value;
var gender = document.getElementsByName("gender");
document.getElementById("label1").innerHTML = '';
document.getElementById("label2").innerHTML = '';
var genValue = '';
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genValue = gender[i].value;
}
}
if (!name) {
document.getElementById("label1").innerHTML = "Enter Name";
return false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
return false;
} else if (!genValue) {
document.getElementById("label2").innerHTML = "Check gender";
return false;
}
return true;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td>
<label>Enter Full Name :</label>
</td>
<td>
<input type="text" id="id1" name="username" placeholder="minimum 6 charactors">
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label1"></label>
</td>
</tr>
<tr>
<td>
<label>Gender :</label>
</td>
<td>
<input type="radio" name="gender" value="female">
<label>Female</label>
<input type="radio" name="gender" value="male">
<label>Male</label>
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label2"></label>
</td>
</tr>
</table>
<br/>
<button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
Fiddle here
When your first block of if..else statements returns, it returns for the whole function and the if for gender never even runs. remove:
else
{
return true;
}

Hide element based on value of other elements

I am trying to hide a table based on the value of two fields, so that if field2 is equal to field1 the table is hidden.
JSfiddle
HTML:
<form>
Expected Number of Items: <input type="text" value="14" name="totalItems" id="totalItems">
<p>
Number of Items Entered: <input type="text" value="14" name="enteredItems" id="enteredItems">
</form>
<p>
<table border="1" style="width:100%" id="hideThis">
<tr>
<td>This should be hidden when "totalItems" equals "enteredItems"</td>
</tr>
</table>
JS:
function toggleClass(eid, myclass){
var theEle = document.getElementById(eid);
var eClass = theEle.className;
if(eClass.indexOf(myclass) >= 0){
theEle.className = eClass.replace(myclass, "");
}else{
theEle.className += "" +myclass;
}
}
See the comments in the code.
// Function to hide/show the table based on the values of inputs
function toggleTable() {
// Hides the table if the values of both input are same
$('#hideThis').toggle($('#totalItems').val() !== $('#enteredItems').val());
}
$(document).ready(function() {
// Bind the keyup event on both the inputs, call the function on event
$('#totalItems, #enteredItems').on('keyup', toggleTable).trigger('keyup');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>Expected Number of Items:
<input type="text" value="14" name="totalItems" id="totalItems">
<p>Number of Items Entered:
<input type="text" value="14" name="enteredItems" id="enteredItems">
</form>
<p>
<table border="1" style="width:100%" id="hideThis">
<tr>
<td>This should be hidden when "totalItems" equals "enteredItems"</td>
</tr>
</table>
jsfiddle Demo
$(document).ready( function() {
$('#totalItems, #enteredItems').keyup(function(){
if( $('#totalItems').val() == $('#enteredItems').val() ){
$('#hideThis').hide();
}else{
$('#hideThis').show();
}
});
});
If you need to check also at page load:
function checkFields(){
if( $('#totalItems').val() == $('#enteredItems').val() ){
$('#hideThis').hide();
}else{
$('#hideThis').show();
}
}
$(document).ready( function() {
$('#totalItems, #enteredItems').keyup(function(){
checkFields();
});
checkFields();
});
Plain JavaScript implementation:
function checkFields(){
if( document.getElementById('totalItems').value == document.getElementById('enteredItems').value ){
document.getElementById('hideThis').style.display = 'none';
}else{
document.getElementById('hideThis').style.display = 'inline-block';
}
}
document.getElementById('totalItems').addEventListener('keyup', function (){
checkFields();
}, false);
document.getElementById('enteredItems').addEventListener('keyup', function (){
checkFields();
}, false);
checkFields();
Here is the new JSFiddle
$(document).ready(function () {
var webpart_ID = 'hideThis';
var FieldA_id = 'totalItems';
var FieldB_id = 'enteredItems';
if ($('#' + FieldA_id).val() === $('#' + FieldB_id).val())
$('#' + webpart_ID).hide();
else
$('#' + webpart_ID).show();
});
This works.
You can bind a keyup events for both the text boxes, from where you can call a function to check if both the values are same..
compare();
$("#totalItems,#enteredItems").keyup(function() {
compare();
});
function compare() {
if ($("#totalItems").val() == $("#enteredItems").val()) {
$("#hideThis").hide();
} else {
$("#hideThis").show();
}
}
Fiddle

Dynamically Created Div Change Drop Down options

// function to add set of elements
var ed = 1;
function new_server() {
ed++;
var newDiv = $('#server div:first').clone();
newDiv.attr('id', ed);
var delLink = '<a class="btn btn-danger" style="text-align:right;margin-right:65px" href="javascript:deled(' + ed + ')" > Delete server ' + ed + ' </a>';
newDiv.find('tr:first th').text('Server ' + ed);
newDiv.find('select:first').attr('id', 'cat' + ed);
newDiv.append(delLink);
$('#server').append(newDiv);
newDiv.find('input:text').val('');
web = new Array('CF9', 'CF10', 'CF11', 'ASP.NET', 'PHP', 'CMS', 'JAVA');
db = new Array('MSSQL Express', 'MSSQL Web', 'MSSQL Standard', 'MYSQL');
app = new Array('IMIS', 'TERMINAL', 'AD');
populateSelect();
$(function() {
$('#cat' + ed).change(function() {
populateSelect();
});
});
function populateSelect() {
cat = $('#cat' + ed).val();
$('#item').html('');
if (cat == 'Web') {
web.forEach(function(t) {
$('#item').append('<option>' + t + '</option>');
});
}
if (cat == 'DB') {
db.forEach(function(t) {
$('#item').append('<option>' + t + '</option>');
});
}
if (cat == 'App') {
app.forEach(function(t) {
$('#item').append('<option>' + t + '</option>');
});
}
}
alert(ed);
}
// function to delete the newly added set of elements
function deled(eleId) {
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('server');
parentEle.removeChild(ele);
//ed--;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="server">
<div id="1">
<table border="3">
<tbody>
<tr>
<th colspan="4" style="background-color:#b0c4de;">Server 1</th>
</tr>
<br>
<tr>
<td>Technology
<br>
<select name="tech[]" id="cat1">
<option value="">Select</option>
<option value="Web">Web</option>
<option value="DB">DB</option>
<option value="App">App</option>
<option value="O">Other</option>
</select>
<br>
<select id="item" name="techtype[]">
</select>
<br>
</td>
<td>CPU?
<input type="text" name="cpu[]">
<br>
</td>
<td>Memory?
<input type="text" name="memory[]">
<br>
</td>
<td>Disk Space?
<input type="text" name="space[]">
<br>
</td>
</tr>
<br><a class="btn btn-info" href="javascript:new_server()"> Add New Server </a>
<br>
</tbody>
</table>
</div>
</div>
I have a form as follows:
On page load I cannot update any of the select items.
If i add a new server It will then allow me to change the selects from the first,
If i create a third same result.
I think what is happening is my id's for the select are not changing an im not sure why, I put a JS alert at the bottom to verify that 'ed' is changing as it loops.
End result Im looking for it to be able to change the values of the select from the first and then when another server is added be able to change those select values with out changing any others and so on.
ANy help would be great.
You are using a counter to dynamically create ID's for your servers, so they look like $("#"+cat+counter).
Probleme is you also use your counter to impact lists in populateSelect(), that means you only modify list content of your last created server.
Here is a demo of what I understand of your projet, and a solution that I can give you.
Most changes are about this :
$(function () {
$(document).on("change", '.cat', function () {
populateSelect($(this).val, $(this).attr("id"));
});
});
And this :
function populateSelect(listValue, listID) {
var serverItem = $("#" + listID).closest(".tableServer").find('.item')
cat = $("#" + listID).val();
serverItem.html('');
...
You can see that I changed id="item" for class="item" (this way, cloned servers won't duplicat id="item").
I moved your arrays on top of your code to be reachable from every function
I also moved your populateSelect function and $(function() { outside the new_server() function
I added newDiv.find('.item').html(''); into new_server() function to not clone previously selected option.
I added class="tableServer" to table wrapper in order to dynamically target them in populateSelect()

Javascript confirm()

I have a submit button something like this:
<button class="btn " type="submit" form="test" name="test" value="test" onClick="return onSave()">Save</button>
I have this javascript code in onSave() function
function onSave(){
var dropdownCounter = 0;
var textareaCounter = 0;
$('tr[class="test"]').each(function(){
var textarea = $(this).find('textarea');
var dropdown = $(this).find('select');
dropdown.filter(function(){
if($.trim($(this).val()).length == 0 || $(this).val() == 'nothing_selected'){
dropdownCounter++;
}
});
textarea.filter(function(){
if($.trim($(this).val()).length == 0){
textareaCounter++;
}
});
});
if( ( dropdownCounter + textareaCounter ) % 5 != 0) {
confirm("test"); // this one is not working
return false;
}
return true;
}
The button should fail if it meets the condition in the if statement but I also need to have a prompt there, but it seems that return method() on the onClick doesn't trigger the confirm(). What approach should i do to fix this?
Update:
<c:forEach var="test" value="${test}">
<table>
<tr class='test'>
<td><textarea class="no-resize" id="comments"></textarea></td>
<td><select class="select"> ... </select> </td>
<td><textarea class="no-resize" id="reason"></textarea></td>
<td><textarea class="no-resize" id="description"></textarea></td>
</tr>
</table>
</c:forEach>
The structure of the table
use else part of the if condition
if( ( dropdownCounter + textareaCounter ) % 5 != 0) {
confirm("test"); // this one is not working
return false;
}else{
return true;
}
Your onclick handler in your HTML does not need a return value.
<button class="btn " type="submit" form="test" name="test" value="test" onClick="onSave()">Save</button>

I Want Pop Up Window To Appear If No Validation Errors

I have a button known as "Prepare Questions". Now when I click on this button, this button does two things, using the validaton() function it validates the form so that if there is an error in the form (empty textbox and radio button not selected) then it displays the suitable error messages on the page. But also the button uses the "openSessionPopup" function so that it opens up a pop up window which states the word "Session".
The problem is that when I click on the button it does both functions, so it displays validation errors if there is some and also opens up the pop up window.
What I want to do is that the pop up window should only be displayed after there are no validation errors. But I can't seem to get this to work, does anyone else know how to do this.
Below is my code:
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
function validation() {
var btnRadioO = document.getElementsByName("sessionNo");
var isbtnRadioChecked = false;;
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errMsgO = document.getElementById("radioAlert");
var errDateTimeMsgO = document.getElementById("dateTimeAlert");
var errDateMsgO = document.getElementById("dateAlert");
var errTimeMsgO = document.getElementById("timeAlert");
for(i=0; i < btnRadioO.length; i++){
if(btnRadioO[i].checked){
isbtnRadioChecked = true;
}
}
if(!isbtnRadioChecked) {
errMsgO.innerHTML = "Please Select the Number of Sessions you Require";
} else {
errMsgO.innerHTML = "";
}
if (dateTextO.value == ''){
errDateMsgO.innerHTML = "Please Select a Date";
}else{
errDateMsgO.innerHTML = "";
}
if (timeTextO.value == ''){
errTimeMsgO.innerHTML = "Please Select a Time";
}else{
errTimeMsgO.innerHTML = "";
}
}
function openSessionPopup (session) {
window.open(session,
'window',
'width=500,height=500,scrollbars=yes,status=no');
}
</script>
</head>
<body>
<form action="create_session.php" method="post">
<table>
<tr>
<th>Number of Sessions :</th>
<td class="sessionNo"><input type="radio" name="sessionNo" value="1" />1</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="2" />2</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="3" />3</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="4" />4</td>
<td class="sessionNo"><input type="radio" name="sessionNo" value="5" />5</td>
</tr>
</table>
<div id="radioAlert"></div>
<p><input type="text" id="datepicker" >
<br/><span id="dateAlert"></span></p>
<p><input type="text" id="timepicker" >
<br/><span id="dateTimeAlert"></span><span id="timeAlert"></span></p>
<p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="validation();openSessionPopup(this.href); return false" /></p>
</form>
</body>
First you should move your event handlers out of your html markup.
Next you should bind an event handler to that click event.
After that you should modify your validation method to return true or false to denote if it passed validation or not.
Last you should use that validation result in a conditional wrapping your showpopup method invocation.
Something like
function myClickHandler(){
if(validation()){
showSessionPopup();
}
}
for your handler and this how how you would bind it
document.getElementsByName("prequestion")[0].addEventListener('click', myClickHandler);
Finally you would modify your validation method like so
function validation() {
var result = true;
var btnRadioO = document.getElementsByName("sessionNo");
var isbtnRadioChecked = false;;
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errMsgO = document.getElementById("radioAlert");
var errDateTimeMsgO = document.getElementById("dateTimeAlert");
var errDateMsgO = document.getElementById("dateAlert");
var errTimeMsgO = document.getElementById("timeAlert");
for(i=0; i < btnRadioO.length; i++){
if(btnRadioO[i].checked){
isbtnRadioChecked = true;
}
}
if(!isbtnRadioChecked) {
errMsgO.innerHTML = "Please Select the Number of Sessions you Require";
result = false;
} else {
errMsgO.innerHTML = "";
}
if (dateTextO.value == ''){
result = false;
errDateMsgO.innerHTML = "Please Select a Date";
}else{
errDateMsgO.innerHTML = "";
}
if (timeTextO.value == ''){
errTimeMsgO.innerHTML = "Please Select a Time";
result = false;
}else{
errTimeMsgO.innerHTML = "";
}
return result;
}
This will make your validation() method return false if you have errors.

Categories