Is it possible to create a validation using javascript to be implemented on the onCLick property of grails' <g:submitButton>
tag? I am using a webflow to proceed from one page to another. Here is my code for the Next button:
<g:submitButton class="btn btn-primary" name="next" value="Next" onclick="return isfilipinoCitizen()"></g:submitButton>
The isfilipinoCitizen function is found on my javascript code:
<script type="text/Javascript">
function isfilipinoCitizen() {
var selected = "${accountInfo?.filipinoCitizen}";
if(selected == "1"){
return true;
}else{
alert(selected)
alert("You must be a Filipino citizen to register!")
document.location.href = "myhomepage";
}
}
</script>
What I wanted to do here is to prevent the page from proceeding to the next page if the input from the user is 0, and redirect the user to the home page of the system. But it seemed that it doesn't work at all.
Any help from you guys is highly appreciated.
Thanks!
First of all, I think you should use Firebug to check on what is actually rendered as html. It also help uncovering some javascript errors or fail-to-load resources.
Second, you should check if the javascript get called in the first place, by placing an alert('come here');
right at the beginning of isfilipinoCitizen(). After that, an alert in the first condition. Javascript is a special language, we must be careful when dealing with it :) :
<script type="text/Javascript">
function isfilipinoCitizen() {
alert("come here");
var selected = "${accountInfo?.filipinoCitizen}";
if(selected == "1"){
alert("come there");
return true;
}else{
alert(selected)
alert("You must be a Filipino citizen to register!")
document.location.href = "myhomepage";
}
}
</script>
At last (after you guarantee that your javascript function get called properly), you must do more than "document.location.href" to prevent the form from submitting. For quick effect, I would recommend jQuery and the onSubmit() event. If you like pure javascript solution, you can follow the solution that Galm and Anuj propose: put onsubmit into the tag:
<g:form name="myForm" action="myaction" onsubmit="return isfilipinoCitizen()">...</g:form>
In the failing case, please remember to return false :)
P/s: Inserting ${accountInfo?.filipinoCitizen}
directly to javascript might work, but it's not a best practice. Transfering "isFilipinoCitizen" as a parameter to the javascript function is better.
Another usability thought: if you already know which user has the right to register, why must we wait until the user fill all the form, to tell them that they must be Filipino citizen to register? Why aren't users notified before(after page load) ?
Try onsubmit
instead.
<g:submitButton class="btn btn-primary" name="next" value="Next" onsubmit="return isfilipinoCitizen()"></g:submitButton>
And in your function return true
or false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With