Verify that an Option has been Selected in a Drop Down Box - javascript

On
http://www.greekforme.com/999-apron-01.html, there are several Drop Down boxes.
The script called 'verifyselection' is supposed to show a pop-up box if the user does not change the drop down from 'Select an Option Below'
function verifyselection(form)
{
// result function
var blnResult = true;
// temp name form control
var nameControl = "";
// array of name of radio form controls
var arrNameControl = new Array();
// array of value checked of radio form controls
var arrValueControl = new Array();
// flag existence form control in array
var isExistOnArray = false;
// loop on all elements of form
for(i=0; i<form.elements.length; i++) {
// check type form control
if(form.elements[i].type=="radio") {
// save name form control
nameControl = form.elements[i].name;
// reset flag existence form control in array
isExistOnArray = false;
// loop on all found radio form control
for(j=0; j<arrNameControl.length; j++){
// if giving form control is exist in array
if(arrNameControl[j] == nameControl) {
// set flag
isExistOnArray = true;
// break loop
break;
}
}
// if giving form control is not exist in array
if(isExistOnArray == false){
// set index of array
j = arrNameControl.length;
// add new element to arrays
arrNameControl[j] = nameControl;
arrValueControl[j] = 0;
}
// if giving radio form control is checked
if(form.elements[i].checked == "1"){
arrValueControl[j] = 1;
}
}
if ((form.elements[i].selectedIndex > -1)) {
if (form.elements[i].selectedIndex == 0) {
var opttext = form.elements[i].value.toLowerCase();
if (opttext.indexOf('optional') < 0) {
blnResult = false;
alert('Please select one of the options from the list');
break;
}
}
}
}
// loop on all found radio form control
if(blnResult==true) {
for(j=0; j<arrNameControl.length; j++){
// if radio group form control is checked
if(arrValueControl[j] != 1) {
// set result function
blnResult = false;
// show error message
alert('Please select one of the options from the list');
break;
}
}
}
// return result function
return blnResult;
}
Currently, I can get the Pop-Up box to show when you click the Add to Cart button -
But... it still adds the items to cart.
I want the script to prevent the item from being added to cart if the user does not change the drop downs from 'Select an Option Below'

Where are you calling this function from? If it's in an onsubmit handler, the handler should return false. So, you should have this in your code somewhere:
form.onsubmit = function() {
return verifyselection(this);
}
Or, in html:
<form onsubmit="return verifyselection(this);" ...>
The important thing here being the return part. When the handler returns false, the default action won't be taken. In this case, the form won't submit.

Related

Having Button not run Function With Empty Input Field

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code

Is there a way to clear text and select box field inside html form via java script function?

Is there a way to clear input text and select box field inside html form via java script function?
Here is my answer...
function clearFields(formName)
{
var formElements = formName.elements;
for(var i=0;i<formElements.length;i++)
{
var elementType = formElements[i].type;
if('text' == elementType){
formElements[i].value="";
formElements[i].disabled = false;
}
else if('select-one' == elementType){
formElements[i].selectedIndex = 0;
formElements[i].disabled = false;
}
else if('select-multiple' == elementType)
{
var multiOptions = formElements[i].options;
for(var j=0;j<multiOptions.length;j++)
{
multiOptions[j].selected = false;
}
}
}
}
$(document).ready(function () {
$('#textbox').val("");
}
Yes, Using javascript alone you can
document.getElementById('idoftextinput').value = "";
Be sure you have id attribute in your input and select elements
You can use an HTML reset button (no script required):
<form>
<!-- any number of form controls -->
<input type="reset" value="Reset all controls to their default values">
</form>
Or if you really must use script, call the form's reset method:
// Assuming there's one form in the document
document.forms[0].reset();
If you want to reset particular controls of a form, and assuming that form is a reference to a form element, then:
var controls = form.elements;
for (var i=0, iLen=elements.length; i<iLen; i++) {
if ( /* some test to filter controls */ ) {
// set control to its default value
resetControlValue(controls[i]);
}
}
or similar. Though in the second case you need to also filter on the type of control to set the state of checkboxes and radio buttons, and for select elements set their selectedIndex to the index of the default selected option (if there is one) or to multiple default selected options.
A reset button is simpler. A function to reset form controls to their default value (or checked-ness or selected-ness) is a bit of work:
function resetControlValue(control) {
var tagName = control.tagName.toLowerCase();
// Do inputs and textareas
if (tagName == 'input' || tagName == 'textarea') {
// Set radios and checkboxes to their default checked state
if (control.type == 'radio' || control.type == 'checkbox') {
control.checked = control.defaultChecked;
// Set text inputs and textareas to their default value
// Include buttons
} else if (control.type != 'button' || tagName == 'textarea') {
control.value = control.defaultValue;
}
// Set select elements to their default selected option
} else if (tagName == 'select') {
// Clear all selected inputs
control.selectedIndex = -1;
// Set default selected as selected
for (var i=0, iLen=control.options.length; i<iLen; i++) {
if (control.options[i].defaultSelected) {
// If single select, leave after setting first
if (control.type == 'select-one') {
control.selectedIndex = i;
return;
}
// If multipe, set all default selected
control.options[i].selected = true;
}
}
}
}

Issue with Radio button checked in JavaScript

I am working on a JSP page which is having multiple radio buttons with ids ans1, ans2, ans3... etc.. No of radio buttons varies depending upon on the response in previous page. User should select answer for all the radio buttons. i.e. user must select response for all the radio buttons ans1, ans2, ans3 ... etc. I have written a Javascript code for submit button click event as below for validation and to make sure user has responded to all the answers:
function beforeSubmit(){
var obj = document.quizcreen;
var qCount = obj.totQuesHidden.value;
for (var i=1; i<=qCount; i++){
if(document.getElementById("ans"+i).checked){
// checked
}else{
alert("Please select ateleast one option"); // unchecked
return false;
}
}
obj.submit();
return true;
}
For some reason above code is not working. The form should not be submitted if all the radio buttons are not selected. Please help, I know it's very simple and common issue, but I am unable to figure it out. Thanks in advance.
Also following is the form action:
<form name="quizcreen" id="quizcreen" method="post" action="QuizResult.jsp" onsubmit = "return beforeSubmit();">
You have a return true statement in your loop. So when the first radiobutton is checked, it will not check the other ones.
function beforeSubmit(){
var obj = document.quizcreen;
var qCount = obj.totQuesHidden.value;
var allChecked = true;
for (var i=1; i<=qCount; i++){
if(! document.getElementById("ans"+i).checked){
allChecked = false;
}
}
if(! allChecked){
alert("Please select ateleast one option"); // unchecked
return false
}
obj.submit();
return true;
}
Ok I found out a better way to handle my scenario, So I am sharing my code for your info:
function beforeSubmit() {
var obj = document.quizcreen;
var allChecked = true;
$("input:radio").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
allChecked = false;
}
});
if (!allChecked) {
alert("Please answer all the questions."); // unchecked
return false;
}
obj.submit();
return true;
}
your problem is at least one to be checked.
do this stuff
function isRadioChecked() {
return ($('input[type=radio]:checked').size() > 0);
}

Enabled and Disabled submit button when multiple fields are empty isn't working

I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY

javascript radio button validation, works in chrome, not in IE

I have this code to check that one from each group of radio buttons has been selected before the user can submit the form. It works fine in chrome, but in IE it always asks the user to answer all questions, even when they have. How can I change this to work correctly in all browsers?
<script>
function validate(){
if (checkRadio("Radio1") && checkRadio("Radio2") && checkRadio("Radio3")){
return true;
}else{
alert("Please answer all questions!");
return false;
}
}
function checkRadio(name){
var radio = document.forms.myForm[name];
for (var option in radio){
if(radio[option].checked){
return true;
}
}
return false;
}
</script>
The issue is in checkRadio() --- you should not use a fast/enhanced for loop with an array.
Calling for (var option in radio) simply returns the name of the radio button group each time (e.g., "Radio1").
You must use the long form for loop:
http://jsfiddle.net/ugZL9/
function checkRadio(name) {
var radio = document.forms.myForm[name];
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
return true;
}
}
return false;
}

Categories

Resources