Weirdest repeat call of function ever - javascript

I made a questionnaire form that has a problem with the validation. There are several validating functions, that are called when clicking the submit button. But the first validating function is then called twice. To show the problem, I made a bare bones version that has the same problem. This is the whole source code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Demo Double Call</title>
</head>
<body>
<form name="upssForm" action="submit.php" method="POST" onsubmit="return validateForm()">
A1 <input type="radio" name="A" value="1">
A2 <input type="radio" name="A" value="2"><br>
B1 <input type="radio" name="B" value="1">
B2 <input type="radio" name="B" value="2"><br>
<button type="button" onclick="validateForm()">Validate and submit button</button><br>
<input type="submit" value="Validate and submit input">
</form>
<script>
function checkA() {
var radioA = upssForm.elements['A'];
if (radioA[0].checked == false) {
alert('A1 not checked');
return false;
}
else return true;
}
function checkB() {
var radioB = upssForm.elements['B'];
if (radioB[0].checked == false) {
alert('B1 not checked');
return false;
}
else return true;
}
function validateForm() {
checkA();
checkB();
if ((checkA() == false) || (checkB() == false))
return false;
else
upssForm.submit();
// return true; /* doesn't work either with the submit input */
}
</script>
</body>
</html>
Just click the submit button or the submit input, and see that the alert 'A1 not checked' comes up twice, the second time after the function checkB() is executed. What is causing this, and how do I solve it?

You are calling checkA() twice, once at the beginning of validateForm() and once in the if() statement.
Store the result in a variable, and then check that in the if() statement:
var aResult = checkA();
if(aResult == false) {
}

The answer WildCrustacean gave indeed solved the problem. For the record and future reference, I'll just give the whole function how it should be:
function validateForm() {
var aResult = checkA();
var bResult = checkB();
if ((aResult == false) || (bResult == false))
return false;
else
upssForm.submit();
}
Thanks, bro!

WildCrustacean's answer is correct, so I've edited mine down. Just FYI, you might want to refactor your if statements. For example, if (foo == false) is the same as if (!foo) (although, interestingly, if (foo === false) is not). So, incorporating WildCrustacean's answer and taking out some redundant code:
function checkA() {
var radioA = upssForm.elements['A'];
if (!radioA[0].checked) {
alert('A1 not checked');
}
return radioA[0].checked;
}
//function checkB() { ...
function validateForm() {
var a = checkA();
var b = checkB();
if (a && b) {
upssForm.submit();
}
return false;
}
It's okay that validateForm always returns false, because the only time that affects anything is when the user clicks the input (not the button) while the form is invalid.
Demo: http://jsfiddle.net/5GA5F/2/
In fact, if you don't mind odd-looking code, you can take advantage of Boolean short-circuiting to shrink the code even more:
function checkA() {
var radioA = upssForm.elements['A'];
return radioA[0].checked || alert('A1 not checked');
}
function checkB() {
var radioB = upssForm.elements['B'];
return radioB[0].checked || alert('B1 not checked');
}
function validateForm() {
var a = checkA(),
b = checkB();
return a && b && upssForm.submit();
}
Demo: http://jsfiddle.net/5GA5F/3/

Here's another way to do it:
function validateForm() {
if ((result = (checkA() && checkB()))){
upssForm.submit();
}
return result;
}
This way, your function always returns information on whether it succeeds or not. Another thing to notice here: in JavaScript, assignment statements return the value of the assignment. We didn't have to assign the result value separately because we could call it in the if condition.
One thing to keep in mind: checkB() will only run if checkA() succeeds. If you need them both to execute, assign their values to a variable and then check those variables.

Related

Validate a form only if every input is empty

Well, the question's pretty self-explanatory. I've been looking for a while and haven't found a proper way to do this kind of validation.
All I need to do is to run an error message if all the inputs are empty. If one of them is filled, then I don't need to stop the form from submitting.
I thought something like:
function checkForm() {
$('input').each(function(){
if( $(this).val() == "" ){
return false;
}
});
});
But this will stop my form if there's, at least, one input without data.
Any ideas? Thanks in advance.
Reverse your logic. I.e. return true if any input has a value, otherwise return false:
function checkForm() {
$('input').each(function() {
if ($(this).val() !== '') {
return true;
}
});
return false;
};
Reverse your logic since you want to check if the value is non-empty for one input field.
Also you probably want to return from your actual function and not from the callback which has no effect.
function checkForm() {
let bool = false;
$('input').each(function(){
if( $(this).val() !== '' ){
bool = true;
}
});
console.log(bool);
return bool;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<button onclick="checkForm()">check</button>

How to prevent Foxycart Action on submit with empty field?

Hollo All,
I am creating a form that exports data on submit to an ecommerce solution called Foxycart. I would like the form to only proceed onto foxycart when the date field is entered however it currently only displays the alert message then proceeds to the action on the form. Does anyone have advice on how to prevent the action on submit? please see code below:
<script>
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
}
}
</script>
<form name="delivery-date-info" action="https://austin-roman.foxycart.com/cart" method="post" accept-charset="utf-8" onsubmit="return validateForm()">
<div class="add-to-bag">
<label for="datepicker-example3"></label>
<input id="datepicker-example3" type="text" name="Delivery_Date_is">
<input type="submit" id="datepicker-example3" type="text" class="button-add">
</div>
</form>
Assuming you're using FoxyCart's default "sidecart" approach (as of v2.0), you'll need to use FoxyCart's own event system, described here. For your specific example, it might look like this:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
if (validateForm()) {
next();
}
});
};
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
} else {
return true;
}
}
Here's an alternate approach that'd be a bit more flexible, would allow more than one product form per page, and also shows a little more what's going on:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
$element = $(params.element);
if (
$element.attr('name') == 'delivery-date-info'
&& $element.find('[name="Delivery_Date_is"]').length > 0
&& !$element.find('[name="Delivery_Date_is"]').val()
) {
alert('Date must be filled out');
} else {
next();
}
});
};

function not working in jsp page?

<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length

How to convert from javascript form action to jquery?

I have a code javascript of a action form:
<form name="myform" onsubmit="return OnSubmitForm();" method="post">
<input type="text" value="" id="type" />
<input type="submit" value="submit" />
</form>
And javascript:
function OnSubmitForm() {
var type = document.getElementById('type').value;
if(type == '1') {
document.myform.action = "index.php?type=1";
}
if(type == '2') {
document.myform.action = "index.php?type=2";
}
return false;
}
How to convert this javascript to jquery, please this ideas?
$("form[name='myform']").submit(function() {
this.action = "index.php?type=" + this.type.value;
return false;
});
form[name='myForm'] selects a form with the name myForm.
Calling .submit(function () { ... }) binds an event handler for the submit event.
Inside the function, this refers to the form.
Example: http://jsfiddle.net/4SZrH/ (check out the form action in Firebug or similar).
First note that this function always returns false, so your form will never submit. But to answer your question, you could use jQuery's submit event
$("form[name='myform']").submit(function(){
var type = this.type.value;
if (type === '1' || type === '2')
this.action = "index.php?type=" + type;
return false;
});
Or more simply:
$("#myForm").submit(OnSubmitForm);
Also note that, for dom level 0 event handlers, you don't want the return statement inline. In the future just do
<form name="myform" onsubmit="OnSubmitForm();"
And let OnSubmitForm return true or false
Finally, note that in JavaScript, functions starting with a capital letter by convention denote a constructor. Consider renaming this function to onSubmitForm

javascript return true not working

i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit

Categories