Cancellation of confirm() still submits - javascript

Cancellation of confirm() doesn't prevent submission. Even if I click cancel, it still submits.
How can I cancel the submission?
<form>
<div class="actions d-flex justify-content-center">
<button class="btn btn-success" onclick="return warning(this.form)">Submit</button>
</div>
</form>
<script type="text/javascript">
function warning(form) {
if (window.focus) self.focus();
var tmp = 100;
for (i = 0; i < tmp; i++) {
var sel = document.getElementById("student_answer_role" + (i + 1));
var val = sel.options[sel.selectedIndex].value;
if (val == "") {
return confirm("You didn't answer all questions.");
}
}
}
</script>

Your code will fail if there are less questions than 100 and all questions are answered. If you only have until student_answer_role10 then testing student_answer_role11 will cause an error which will exit the validation code and cause the submission of the form
Here is a better way
window.addEventListener("load", function() {
document.getElementById("studentForm").addEventListener("submit", function(e) {
let text = [];
[...document.querySelectorAll("select[id^=student_answer_role]")].forEach((sel, i) => {
const val = sel.options[sel.selectedIndex].value;
if (val == "") {
text.push("You didn't answer question #" + (i + 1)); // can be used for ANY error
}
})
if (text.length > 0) {
if (!confirm(text.join("\n") + "\nContinue?")) {
e.preventDefault(); // stop submission
}
}
})
})
<form id="studentForm">
<select id="student_answer_role1">
<option value="">Please select</option>
<option value="1">One</option>
</select>
<select id="student_answer_role2">
<option value="">Please select</option>
<option value="2">Two</option>
</select>
<div class="actions d-flex justify-content-center">
<button class="btn btn-success">Submit</button>
</div>
</form>

Related

how to fix adding input not being double when selecting?

I'm stuck append double, I know the problem is that when I select the first I choose dynamic, when I change the second it selects static when I add the option button, why does the input become double?. how to fix append input not double. but if I first choose static and don't choose anything else, then not problem.
$(document).on('change', '#select-input-view', function(e) {
e.preventDefault()
let select = $(this).find(':selected').attr('data-input')
arr_select = select.split("-")
if (arr_select[1] == 'static') {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = ``
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="static-option-${arr_select[2]}" class="mb-3">
<button id="add-option-select-view-${arr_select[2]}" class="btn btn-primary">add option</button>
<button id="remove-option-select-view-${arr_select[2]}" class="btn btn-danger">remove option</button>
<div id="view-option-${arr_select[2]}" class="mt-3">
</div>
</div>
`
var num_option_insert = $('.data-div-option').length;
$(document).on('click', '#add-option-select-view-' + arr_select[2], function(e) {
e.preventDefault()
thisid = this.id
arr_id = thisid.split("-")
num_option_insert += 1
option = `
<div id="option-div-view-${num_option_insert}-${arr_id[4]}" data-div-option="${num_option_insert}" class="col-md-3">
<label class="form-label">select option ${num_option_insert}</label>
<input name="123" type="text" class="form-control" required>
</div>
`
view_option = document.getElementById('view-option-' + arr_id[4])
$(view_option).append(option)
})
// delete fields
$(document).on('click', '#remove-option-select-view-' + arr_select[2], function(e) {
e.preventDefault()
thisid = this.id
arr_id = thisid.split("-")
console.log(arr_id)
var row = $('#option-div-view-' + num_option_insert + '-' + arr_id[4]);
row.remove();
num_option_insert -= 1
})
} else {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = ``
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="dynamic-option-1" class="mb-3">
<div class="mb-3">
<label class="form-label">Select Data Dynamic</label>
<select name="select-dynamic" class="form-select" required>
<option selected disabled>Select data dynamic</option>
<?php foreach ($table_database as $data) {
$table = $data->Tables_in_db_builder;
$arr = explode("_", $table);
if ($arr[0] != 'sys') {
?>
<option><?= $data->Tables_in_db_builder ?></option>
<?php }
} ?>
</select>
</div>
</div>`
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-input-view" name="input-type" class="form-select">
<option>text</option>
<option>number</option>
<option>textarea</option>
<option data-input="select-static-1">select static</option>
<option data-input="select-dynamic-1">select dynamic</option>
<option>float</option>
<option>date</option>
</select>
<div id="select-id-input-view-1">
</div>
Use event delegation so you only create listeners for the add-option and remove-option buttons once, not every time you add a new set of buttons.
Also, this line was wrong:
var num_option_insert = $('.data-div-option').length;
You have no data-div-option class, you have attributes like data-div-option="${num_option_insert}". The correct selector to match these elements is [data-div-option].
$(document).on('click', '.add-option-select-view', function(e) {
e.preventDefault()
var num_option_insert = $('[data-div-option]').length;
thisid = this.id
arr_id = thisid.split("-")
num_option_insert += 1
option = `
<div id="option-div-view-${num_option_insert}-${arr_id[4]}" data-div-option="${num_option_insert}" class="col-md-3">
<label class="form-label">select option ${num_option_insert}</label>
<input name="123" type="text" class="form-control" required>
</div>
`
view_option = document.getElementById('view-option-' + arr_id[4])
$(view_option).append(option)
})
// delete fields
$(document).on('click', '.remove-option-select-view', function(e) {
e.preventDefault()
var num_option_insert = $('[data-div-option]').length;
thisid = this.id
arr_id = thisid.split("-")
console.log(arr_id)
var row = $('#option-div-view-' + num_option_insert + '-' + arr_id[4]);
row.remove();
num_option_insert -= 1
})
$(document).on('change', '#select-input-view', function(e) {
e.preventDefault()
let select = $(this).find(':selected').attr('data-input')
arr_select = select.split("-")
if (arr_select[1] == 'static') {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="static-option-${arr_select[2]}" class="mb-3">
<button id="add-option-select-view-${arr_select[2]}" class="btn btn-primary add-option-select-view">add option</button>
<button id="remove-option-select-view-${arr_select[2]}" class="btn btn-danger remove-option-select-view">remove option</button>
<div id="view-option-${arr_select[2]}" class="mt-3">
</div>
</div>
`
} else {
document.getElementById('select-id-input-view-' + arr_select[2]).innerHTML = `
<div id="dynamic-option-1" class="mb-3">
<div class="mb-3">
<label class="form-label">Select Data Dynamic</label>
<select name="select-dynamic" class="form-select" required>
<option selected disabled>Select data dynamic</option>
<?php foreach ($table_database as $data) {
$table = $data->Tables_in_db_builder;
$arr = explode("_", $table);
if ($arr[0] != 'sys') {
?>
<option><?= $data->Tables_in_db_builder ?></option>
<?php }
} ?>
</select>
</div>
</div>`
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-input-view" name="input-type" class="form-select">
<option>text</option>
<option>number</option>
<option>textarea</option>
<option data-input="select-static-1">select static</option>
<option data-input="select-dynamic-1">select dynamic</option>
<option>float</option>
<option>date</option>
</select>
<div id="select-id-input-view-1">
</div>

How can I prevent multiple selection of same value?

I want to prevent multiple selections of same value in my project.
My form
<div class="form-row">
<div class="form-group col-md-6">
<select name="number" class="form-control" id="index0">
<option value="">Select Number</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="form-group col-md-4">
<button class="btn btn-primary" id="addNumber" onclick="addNumber();">Add Number</button>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<select name="letter" class="form-control" id="index00">
<option value="">Select Letter</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</div>
<div class="form-group col-md-4">
<button class="btn btn-primary" onclick="addLetter();">Add Letter</button>
</div>
</div>
<div class="newHtml">
<div class="newLetter">
</div>
</div>
I have two select box one for number and one for letter.
A number can have many letters eg, number 1 can have letters A,B,C,D,E, etc and same goes for other numbers.
When I append new form clicking add number button the selected number should not display there. And if for number 1 letter A is already selected then A should not appear for that number 1 if I click add letter button.
How to achieve that?
Actually it's not so much hard with jQuery/CSS selectors. Try that one:
let letters = ["A", "B", "C", "D", "E"];
function addNumber() {
let val1 = $("#index0").val();
let val2 = $("#index00").val();
if ($(".newLetter > .number[data-value=" + val1 + "]").length == 0) {
$(".newLetter").append(
'<div data-value="' + val1 + '" class="number">' + val1 + "</div>"
);
$('#index0 > option[value="' + val1 + '"]').remove();
$('#index00 > option[value="' + letters[parseInt(val1) - 1] + '"]').remove();
}
}
function addLetter() {
let val1 = $("#index0").val();
let val2 = $("#index00").val();
if ($(".newLetter > .letter[data-value=" + val2 + "]").length == 0) {
$(".newLetter").append(
'<div data-value="' + val2 + '" class="letter">' + val2 + "</div>"
);
$('#index1 > option[value="' + val2 + '"]').remove();
}
}
Look at it on codepen
You should create an array, so can integrate the values. I may not understand correctly.
Is this something like you want to achieve?
let records = [];
const numberDropdown = document.querySelector("#dropdown-number"),
letterDropdown = document.querySelector("#dropdown-letter"),
submitButton = document.querySelector("#submit-btn");
submitButton.addEventListener("click", handleEntry);
numberDropdown.addEventListener("change", updateDropdowns);
letterDropdown.addEventListener("change", updateDropdowns);
function handleEntry() {
let selectedNumber = numberDropdown.value,
selectedLetter = letterDropdown.value;
records.push({
number: selectedNumber,
letter: selectedLetter
});
updateList();
updateDropdowns();
let i = 0;
while (letterDropdown.options[i].disabled) {
i++
};
letterDropdown.selectedIndex = i;
}
function updateDropdowns() {
if (records.length) {
let noLeft = true;
document.querySelectorAll("#dropdown-letter option").forEach((option) => {
let taken = false;
records.forEach((record) => {
if (
option.value == record.letter &&
numberDropdown.value == record.number
) {
taken = true;
}
});
if (taken) {
option.disabled = true;
} else {
option.disabled = false;
noLeft = false;
}
});
if (noLeft) {
submitButton.disabled = true;
alert('select another number');
} else {
submitButton.disabled = false;
}
} else {
document.querySelectorAll("#number-dropdown option").forEach((option) => {
option.disabled = false;
});
}
}
updateDropdowns();
updateList();
function updateList() {
document.querySelector('#list').innerHTML = '';
records.forEach((record) => {
document.querySelector('#list').innerHTML += `<li>${record.letter} | ${record.number}</li>`
});
}
<select id="dropdown-number">
<option value="0" selected>0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="dropdown-letter">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<button id="submit-btn">Add</button>
<p>Entries:</p>
<ul id="list"></ul>

How to enable button upon dropdown item selection in js?

This snippet displays two select elements, and a submit button. Initially, button is disabled.
Desired behavior: enable submit button when both elements have second option (complete) selected. If either one of the elements has first option (received) selected, disable the button.
Current behavior: button is enabled/disabled regardless of the first select element. Meaning: If I select option received in the first dropdown, and option complete in the second, button will be enabled, instead of disabled.
function enableButton() {
var all_statuses = document.body.querySelectorAll(".selected > .form-control");
var option_two = "complete";
for (var i = 0; i < all_statuses.length; i++) {
console.log(i + " This will work")
if (all_statuses[i].value == option_two) {
document.getElementById("btn_completed").disabled = false;
} else document.getElementById("btn_completed").disabled = true;
}
}
$(document).ready(enableButton);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="selected">
<select class="form-control" id="select_one" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
<select class="form-control" id="select_two" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
</div>
</form>
<button id="btn_completed">Completed</button>
So, the question is: How to enable the button if all select elements have option complete selected, or how to disable the button if at least one select element has option different than complete selected?
working code:
<!DOCTYPE html>
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="selected">
<select class="form-control" id="select_one" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
<select class="form-control" id="select_two" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
</div>
</form>
<button id="btn_completed" disabled>Completed</button>
</body>
<script>
function enableButton() {
debugger;
var all_statuses = document.body.querySelectorAll(".selected > .form-control");
var option_two = "complete";
var isdisabled = false;
for (var i = 0; i < all_statuses.length; i++) {
console.log(i + " This will work")
if (all_statuses[i].value != option_two) {
isdisabled = true;
break;
}
}
if(isdisabled) {
document.getElementById("btn_completed").disabled = true;
}
else {
document.getElementById("btn_completed").disabled = false;
}
}
$(document).ready(enableButton);
</script>
</html>

How to display multiple dropdown value on another html fields using jquery

I have few dropdown with text fields.
I want to get all those values and display on a button.
The only condition is that button should be generate upto 5 time.
means -> if all the value of dropdown & text field are displaying on a button field so i want to generate another button and again i want to display my value on that by clicking on generate button.
Here is my code for reference.
$('#left_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#left_period_guider").html('(period,offset)');
}else if ($(this).val()=='ema') {
$("#left_period_guider").html('(close,period,offset)');
}
});
$('#right_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#right_period_guider").html('(period,offset)');
}else if ($(this).val()=='ema') {
$("#right_period_guider").html('(close,period,offset)');
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<select name="left_indicator" id="left_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator">
<option>select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
This button should generate by clicking above the button with the all field provided values.
example : sma(10.2) < ema(3.2)
<button type="button" id="generated1" name="generated1" value="">value will display here</button>
<button type="button" id="removethis" name="removethis">removethis</button>
</div>
</body>
</html>
As you can see here,
I'm just expecting the solution like all the dropdown and text field value should display on a button and generate the button so i can do the same strategies on another button upto 5 time.
so value should display on each generated button like. sma(10.2) < ema(3.2).
The following code would do the Job !
To perform better validation, I added a class name 'chk' to check all input fields.
This would be used to validate and generate the buttons' data.
Notice that I also added an empty value property to your select boxes, that's required for this code.
var data='';
var btnid=0;
function generateBtn(data){
btnid++;
var btns='<button type="button" id="generated'+btnid+'" name="generated'+btnid+'" value="" data-id="'+btnid+'">'+data+'</button><button type="button" id="removethis" class="removethis" data-id="'+btnid+'">removethis</button>';
$('#container').append(btns);
}
function check_inputs() {
var i=0;
//validation to check for empty inputs
//Same loop used to generate valid Button' Data
data='';
//we reset Data
$('.chk').each(function(){
if( $(this).val() === "" ){
$(this).css({'border-color':'red','border-size':'3px'});
} else{
$(this).css({'border-color':'green','border-size':'3px'});
if($(this).is('input')){
data+='('+$(this).val()+')';
} else {
data+=' '+$(this).val();
}
i++;
}
});
if(i==$('.chk').length){
//We gernerate the button
generateBtn(data);
} else{
return;
}
}
//Dynamically generated buttons are non-Dom, so we base selction on the parent container
//Data-id attribute is used to match targeted buttons
$("#container").on('click','.removethis', function() {
$('button[data-id='+$(this).data('id')+']').remove();
});
$("#generateButton").on('click', function() {
//Because we can remove buttons
//We count generated buttons before generating more than 5
if($("[id^=generated]").length<5){
check_inputs();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<select name="left_indicator" id="left_indicator" class="chk">
<option value="">select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)" class="chk">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator" class="chk">
<option value="">select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator" class="chk">
<option value="">select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)" class="chk">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
</div>
I commented the code, but I suggest you revise your HTML code for the small (Non standard) mistakes. Just to pay attention to What's unique and what's not! I don't know if this is meant to be in <form> or not, repeating name property in buttons for example should be taken care of.
From your question, I'm not sure where to put the buttons, so I assumed to place it at the end of the document. To make it even simple I added a div at the end before the closing of the body.
<div id="displayButtons" style="display:block;">
Then you can add the following code in the script tag to achieve what you are looking for.
var buttonCount = 0;
$('#generateButton').click(function () {
if (buttonCount < 5) {
// Get all values
let left_indicator = $("#left_indicator").val();
let left_PeriodAndOffset = $("#left_PeriodAndOffset").val();
let comparator = $("#comparator").val();
let right_indicator = $("#right_indicator").val();
let right_PeriodAndOffset = $("#right_PeriodAndOffset").val();
// Define Button to display
let buttonText = left_indicator + " (" + left_PeriodAndOffset + ") " + comparator + " " + right_indicator + " (" + right_PeriodAndOffset + ")";
let button = '<button id="' + buttonCount + '">' + buttonText + '</button>';
// Display button inside Div
$("#displayButtons").append(button);
buttonCount++;
} else {
alert("Limit of 5 reached");
}
})
$("#removethis").click(function () {
if (buttonCount > 0) {
$("#displayButtons > button:last-child").remove();
buttonCount--;
}
else {
alert("No more buttons to remove.");
}
})
Another additional thing I would like to mention is ;
$('#left_indicator').on('change', function (event) {
event.preventDefault();
/* Act on the event */
if ($(this).val() == 'sma') {
$("#left_period_guider").text('(period,offset)'); <== I think you need to replace html with text to display what you require..
} else if ($(this).val() == 'ema') {
$("#left_period_guider").text('(close,period,offset)');
}
});
I hope that's what you were looking for...
Complete working Code:
var buttonCount = 0;
$('#generateButton').click(function () {
if (buttonCount < 5) {
// Get all values
let left_indicator = $("#left_indicator").val();
let left_PeriodAndOffset = $("#left_PeriodAndOffset").val();
let comparator = $("#comparator").val();
let right_indicator = $("#right_indicator").val();
let right_PeriodAndOffset = $("#right_PeriodAndOffset").val();
// Define Button to display
let buttonText = left_indicator + " (" + left_PeriodAndOffset + ") " + comparator + " " + right_indicator + " (" + right_PeriodAndOffset + ")";
let button = '<button id="' + buttonCount + '">' + buttonText + '</button>';
// Display button inside Div
$("#displayButtons").append(button);
buttonCount++;
} else {
alert("Limit of 5 reached");
}
})
$("#removethis").click(function () {
if (buttonCount > 0) {
$("#displayButtons > button:last-child").remove();
buttonCount--;
}
else {
alert("No more buttons to remove.");
}
})
$('#left_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#left_period_guider").text('(period,offset)');
}else if ($(this).val()=='ema') {
$("#left_period_guider").text('(close,period,offset)');
}
});
$('#right_indicator').on('change', function(event) {
event.preventDefault();
/* Act on the event */
if ($(this).val()=='sma') {
$("#right_period_guider").text('(period,offset)');
}else if ($(this).val()=='ema') {
$("#right_period_guider").text('(close,period,offset)');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="left_indicator" id="left_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="left_PeriodAndOffset" id="left_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="left_period_guider"></div>
<select name="comparator" id="comparator">
<option>select</option>
<option value="=">=</option>
<option value="<"><</option>
</select>
<select name="right_indicator" id="right_indicator">
<option>select</option>
<option value="sma">sma</option>
<option value="ema">ema</option>
</select>
<input type="text" name="right_PeriodAndOffset" id="right_PeriodAndOffset" placeholder="e.g (10.2)">
<div id="right_period_guider"></div>
<button type="button" id="generateButton" name="generateButton">click to generate button upto 5 with remove button</button>
<hr>
This button should generate by clicking above the button with the all field provided values.
example : sma(10.2) < ema(3.2)
<button type="button" id="generated1" name="generated1" value="">value will display here</button>
<button type="button" id="removethis" name="removethis">removethis</button>
</div>
<div id="displayButtons" style="display:block;">

JavaScript Form Validation not working entirely

I am trying to have JavaScript code validate all the elements of this form but for some reason the select box doesn't validated. The user can fill in all the blanks except for the select box and the JavaScript does not catch it. Any ideas as to what I am missing? Thanks.
<script type="text/javascript">
function validateForm() {
var ageErr = document.getElementById('ageErr');
var nameErr = document.getElementById('nameErr');
var radioErr = document.getElementById('radioErr');
var results = document.getElementById('results');
var theName = document.formContact.theName;
var theAge = document.formContact.theAge;
var theRadioGp = document.formContact.contact;
var theSelect = document.formContact.theSelect;
var chkValue;
if(theName.value =="") {
nameErr.innerHTML = "A name is required ";
theName.focus();
return false;
}else {
nameErr.innerHTML= "";
}
if(theAge.value ==""){
ageErr.innerHTML = "An age is required";
theAge.focus();
return false;
}else {
nameErr.innerHTML = "";
}
if(theAge.vale =="") {
age.Err.innerHTML = "An age is required";
theAge.focus();
return false;
} else if (isNaN(theAge.value)) {
ageErr.innerHTML = "Age should be a number";
theAge.select();
} else if (theAge.value < 3 || theAge.value > 120) {
ageErr.innerHTML = "Please enter your real Age";
theAge.select();
return false;
} else{
ageErr.innerHTML = "";
}
for(var i=0; i < theRadioGp.length; i++) {
if(theRadioGp[i].checked ==true) {
chkValue = theRadioGp[i].value;
}
}
if(chkValue == undefined) {
alert('You need to slect a method of contact');
return false;
}
if(theSelect.options[theSelect.selectedIndex].text == "<--PLEASE SELECT ONE-->")
{alert("You need to select an option");
return false;
}else {
alert("Your have selected "+theSelect.options[theSelect.selectedIndex].text);
}
alert("Your form has been completed. Great Job!!");
}
</script>
</head>
<body>
<form action="" id="formContact" method="post" onsubmit="return validateForm();" name="formContact">
<p>Name:<br />
<input type="text" name="theName"><span class="err" id="nameErr"></span>
</p>
<p>Age:<br />
<input type="text" name="theAge"><span class="err" id="ageErr"></span>
</p>
<p>
<p>How may we contact you?<br>
<input type="radio" name="contact" value="email">Email<br>
<input type="radio" name="contact" value="no contact">No Contact<br>
</p>
<p>Please coose a selection below:<br>
<select name="theSelect">
<option><--PLEASE SELECT ONE -->
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
<p><input type="submit" value="Submit" name="btnSubmit" ">
</form>
<span id="results"></span>
</body>
</html>
Your HTML isn't valid. Replace your select part with following
<select name="theSelect">
<option><--PLEASE SELECT ONE--></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Or use a numeric value for the default option
<select name="theSelect">
<option value="0">PLEASE SELECT AN OPTION</option>
<option value="1">One</option>
...
</select>
And check the value (not the text selected)
if(theSelect.options[theSelect.selectedIndex].value == 0){
alert("You need to select an option");
return false;
}else {
alert("Your have selected " + theSelect.options[theSelect.selectedIndex].text);
}
Why not use selectedIndex without the text?
Example:
<select id="mytest">
<option value="-1"><--PLEASE SELECT ONE--></option>
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Then
if(theSelect.selectedIndex == -1)
{alert("You need to select an option");
return false;
}else {
the rest

Categories

Resources