1

I want to write a javascript validation code for validating that one of f:selectItem must be selected but i'm unable to access checked property of f:selectItem through java script. Below is my JSF page.

JSF Page:-

<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html> 
 <f:view> 
    <body 
        <h:form styleClass="form" id="form1"">
            <h:selectOneRadio id="searchType" value="#{auditTrailDTO.searchType}">
            <f:selectItem itemLabel="Male" itemValue="m"/>
            <f:selectItem itemLabel="FeMale" itemValue="f"/>
        </h:selectOneRadio>
        </h:form>
    </body>
</f:view>
 </html>

AuditTrailDTO.java:-

class AuditTrailDTO
 private string searchType;
 public String getSearchType() {
    return searchType;
 }
 public void setSearchType(String searchType) {
    this.searchType = searchType;
 }
}

Edit:-

I have succeeded in accessing f:selectItem by following way.Now when no one is selected it shows alert message as expected.But it shows alert message even when second of the radio button is selected. I'm calling below method on form onsubmit attribut.Any idea please?

function validateForm(){
var searchType = document.getElementsByName("form1:searchType");
var a = !(searchType[0].checked);
var b = !(searchType[1].checked);
if(a&&b){
    alert('Please select search type');
        return false;
}
 return true;
} 
Adnan
  • 4,517
  • 15
  • 44
  • 54

2 Answers2

1

Set the required attribute on the tag

If the rendering is

<input type="radio" name="form1:searchType" value="Male">
<input type="radio" name="form1:searchType" value="FeMale">

then you can do this in plain JS DEMO

window.onload=function() {
  document.getElementById('form1').onsubmit=function() {
    var isChecked = this.elements["form1:searchType"][0].checked || this.elements["form1:searchType"][1].checked;
    if (!isChecked) {
      alert('Please check gender');
      return false
    } 
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I tried above method but java script error is coming that form1:searchType is null or not an object. – Adnan Nov 21 '11 at 09:24
  • I'm using f:selectItems instead of f:selectItem because I have to make select items dynamically, does it causing above error? – Adnan Nov 21 '11 at 09:28
  • Here is generated html of radio button portion. – Adnan Nov 21 '11 at 09:52
0

You can try with required and requiredMessage attributes:

<h:selectOneRadio required="true" requiredMessage="Message... ">
...
</h:selectOneRadio>

You can catch the requiredMessage with:

<h:messages> or <h:message>

Michel Foucault
  • 1,724
  • 3
  • 25
  • 48