CGurrell CGurrell - 2 months ago 5x
HTML Question

How to render a new page in a javascript script

I am using XHTML, JSF and JavaScript to create a form, validate that information has been submitted into selected fields onclick in a h:commandButton, and if validated, redirect to a different page homepage.xhtml. Everything works up to the redirection, which I can't get to work.

In the JavaScript function Validation(), I have tried location="homepage.xhtml", window.location.href="homepage.xhtml", location.url="homepage.xhtml" and a few others, but nothing seems to work. I have a feeling I'm supposed to have some sort of statement which adds href="homepage.xhtml" to the h:commandButton if Validate() returns true, but I am unsure as to how to do that.

Any help is greatly appreciated. I have added the relevant code below.


<h:commandButton class="btn btn-warning" value="Continue" onclick="Validation()"/>


function Validation() {

var nameCheck = document.getElementById('formdiv:cardName');
var numCheck = document.getElementById('formdiv:cardNumber');
var expCheck = document.getElementById('formdiv:expDate');


var variablesToCheck = [nameCheck, numCheck, expCheck];

for(i=0; i < variablesToCheck.length; i++){
if(variablesToCheck[i].value == null || variablesToCheck[i].value == ""){

alert("Fields marked with a * must be completed");
return false;

// This is where the redirection needs to go, I think...
return true;

EDIT: Just noticed the if else statement is incorrect logically, but syntactically it shouldn't make a difference. The else part needs to be a statement outside of the loop without a condition; this code simply tries to redirect when the field it is checking has something in, not when all fields have something in.

EDIT 2: Loop corrected


Why you need h:commandButton anyway you are using simple javascript validation h:commandButton is rendered as <input type="submit" ../> its mission is to submit the form so what ever javascript you are writing your form will be submitted and your page is gonna be refreshed, So If you need it this way you have to force it not to submit the form,

However from understanding your needs all you need is simple <a /> or <button /> , Or you can just add type="button" into your h:commandButton ex:<h:commandButton type="button" .../>