2016-08-17 30 views
0

我使用XHTML,JSF和JavaScript创建表单,验证信息已提交到选定字段中的onclick中:commandButton,如果验证,则重定向到其他页面homepage.xhtml。一切工作到重定向,我无法去工作。在JavaScript函数Validation()中,我尝试了位置=“homepage.xhtml”,window.location.href =“homepage.xhtml”,location.url =“homepage.xhtml”和其他几个,但是,似乎没有任何工作。我有一种感觉,我应该有某种类型的声明,如果Validate()返回true,那么会向h:commandButton添加href =“homepage.xhtml”,但我不确定如何操作。如何在JavaScript脚本中渲染新页面

任何帮助,非常感谢。我在下面添加了相关的代码。

按钮:

<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'); 

    console.log(nameCheck.value); 
    console.log(numCheck.value); 
    console.log(expCheck.value); 

    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; 
} 

编辑:只是注意到如果else语句是不正确逻辑,但在语法上不应该有所作为。 else部分需要在没有条件的循环之外进行声明;这个代码只是尝试当它检测领域中拥有的东西,而不是在所有领域有一些重定向

编辑2:循环修正

+0

不应该在for循环之后重定向吗? –

+0

@JasperdeVries是的,我注意到了我自己。现在修改它 – CGurrell

+0

http://stackoverflow.com/questions/15515946/how-to-validate-a-field-in-jsf –

回答

1

为什么你需要h:commandButton反正你正在使用 h:commandButton呈现为<input type="submit" ../>它的使命是 提交表单所以什么都的JavaScript你写你的表单将提交简单javascript验证和你的页面会被刷新,所以如果你需要这样,你必须迫使它不提交表单,

但是从了解您的需求所有你需要的是简单的<a /><button />,或者你也可以添加type="button"到您的h:commandButton例如:<h:commandButton type="button" .../>

+0

我添加了type =“button”,它工作得很好!感谢您的帮助 – CGurrell

+0

@CGurrell:请参阅以上BalusC的评论。看起来你有一辆保时捷911,但尝试像家用车一样使用它。 – Kukeltje

0

您可以使用.. window.location.replace('Your_url'); .. 或者你可以使用..
window.location.href= 'Your_url'; ..我想也必须有其他功能。如果你想打开它在另一个窗口,如弹出,你可以使用.. window.open('your_url');

希望这会有所帮助!

+0

好,所以window.location.replace和window.location.href不想工作,但window.open确实工作,它打开我想要的页面它会在新窗口中打开。问题是它让我想关闭的页面打开。 – CGurrell

+0

嗯。正如下面的评论所说,为什么你不尝试使用提交表单?听起来对我来说是个好主意! –