0

I have two functions; one that validates the form, the other executes some code if the first function returns true.

<form name="calculator" method="POST" onsubmit="return checkForm(); result(trueOrFalse);" onreset="clearForm()">

The checkForm() function is defined as follows:

function checkForm() {
 var valid = true;
 var radios1 = document.getElementsByName("item");
 var radios2 = document.getElementsByName("postage");
 if (document.getElementById("constituency").value == 0) {
 document.getElementById("constituency").style.border = "1px solid #a60f28";
 document.getElementById("constituency").style.borderRadius = "2.5px";
 document.getElementById("conWarning").style.display = "block";
 valid = false;
 }
 //similar code as above for other fields
 trueOrFalse = valid;
 return valid;
}

The result(valid) function is defined as:

function result(valid) { //use trueOrFalse as parameter
 if (valid == true) {
 document.getElementById("result").style.display = "none";
 document.getElementById("result").innerHTML = "Yay"; //test display value
 document.getElementById("result").style.display = "inline";
 }
 else {
 document.getElementById("result").style.display = "none";
 document.getElementById("result").innerHTML = "0";
 document.getElementById("result").style.display = "inline";
 }
 return valid;
}

The goal here is to check first if the form filled out by the user is valid; if it is then produce a value to show to the user in the HTML as follows:

<div id="pound">&#163; <div id="result">0</div></div>

I'm not sure if the way I'm calling my two functions is correct/legal or if it is, whether the value to be display by the result(valid) function has been written correctly. The form is supposed to act as a calculator.

asked Oct 30, 2014 at 10:47
2
  • 1
    why not call result() from checkForm() function Commented Oct 30, 2014 at 10:48
  • onsubmit="return result( checkForm() )"? Commented Oct 30, 2014 at 10:54

1 Answer 1

3

Instead of:

trueOrFalse = valid;
return valid;

Try this:

return result(valid);

Then remove result(trueOrFalse); from your onsubmit.

answered Oct 30, 2014 at 10:50
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it enabled me to write up some code to also stop the form from reloading on submit :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.