如何使用JavaScript显示/隐藏HTML元素

时间:2017-07-29 00:44:39

标签: javascript html jsf

我正在尝试使用JSF创建一个带有用户名(显示),角色(隐藏)和密码(隐藏)的唱歌形式。

首先,用户输入他/她的用户名,然后点击“验证”按钮。如果用户名存在,则页面必须显示具有用户名角色的角色<h:SelectOneMenu>,密码输入,并隐藏“验证”按钮。

默认情况下,通过CSS隐藏角色和密码输入:

<body>
  <div class="container">
    <h:form styleClass="form-signin">
      <h2 class="form-signin-heading">SISE<br><small>Inicio de Sesión</small></h2>
      <label for="inputEmail" class="sr-only">Nombre de Usuario</label>
      <input type="text" id="inputEmail" class="form-control" placeholder="Nombre de usuario" required autofocus>
      <br>
      <h:commandButton styleClass="btn btn-lg btn-primary btn-block" value="Validar" action="#{beanInicioSesion.buscarUsuarioDB}" />
      <h:selectOneMenu styleClass="form-control hide">
        <f:selectItem itemLabel="Something" itemValue="Something"></f:selectItem>
      </h:selectOneMenu>
      <label for="inputPassword" class="sr-only">Contraseña</label>
      <input type="password" id="inputPassword" class="form-control hide" placeholder="Contraseña" required>
      <br>
      <h:commandButton styleClass="btn btn-lg btn-primary btn-block hide" value="Iniciar sesión" />
    </h:form>
  </div>
</body>

以下是我在托管用户唱歌中的内容:

public String buscarUsuarioDB() throws SISE_Exceptions, SQLException {
  int usuarioValidado = 0; //validatedUser
  UsuarioDB usrDB = new UsuarioDB();

  try {
    usuarioValidado = usrDB.consultarUsuario(this.getNombreUsuario());
    if (usuarioValidado == 0) {
      setMensaje("Usuario Invalido");
    } else {
      setMensaje("Usuario Valido");
      //Valid user, then show/display the <h:selectOneMenu> and password input.
    }

  } catch (Exception e) {
    // TODO: Add catch code
    e.printStackTrace();
  }
  return "";

}

所以问题是,如何从我的buscarUsuarioDB()方法中选择HTML元素,以便在JSP中显示/隐藏它们?

2 个答案:

答案 0 :(得分:1)

首先,你需要决定是否要使用HTML5 with JSFJSF完全爆炸(我建议你使用后者)。

在解决您的问题时,您使用的是HTML inputJSF生命周期中不知道的标记。

   .....
       <!-- NO   <label for="inputEmail" class="sr-only">Nombre de Usuario</label>-->           
       <!--YES--><h:outputLabel for="inputEmail" class="sr-only" value="Nombre de Usario"/>       
       <!--NO    <input type="text" id="inputEmail" class="form-control" placeholder="Nombre de usuario" required autofocus>-->
       <!--YES--><h:inputText id="inputEmail" class="form-control" required="true" value="#{backingBean.value}"/>
   .....

最后回答你的主要问题, 要添加此类功能,您应该将f:ajax组件h:commandButton包含在<h:commandButton id="submit" value="Submit"> <f:ajax event="click" render="selectOneMenu_id" listener="#{backingbean.doSomething}"/> </h:commandButton> 组件中

selectOneMenu

和您的<h:selectOneMenu styleClass="form-control hide" id="selectOneMenu_id"> <f:selectItem itemLabel="Something" itemValue="Something"/> </h:selectOneMenu>

f:ajax

您的listner AjaxBehaviorEvent指向接受render类型作为参数的方法。

  

此处的关键是f:ajax id 属性,因为它指向   应该是id或空格分隔的组件JSF列表   在Ajax调用重新启动时在视图中更新。

另请注意,id可以为组件提供 <h:inputLabel for="inputEmail" class="sr-only" value="Nombre de Usuario"/> <h:inputText id="inputEmail" class="form-control" value="{renderBean.value}" reqired="true"/> <h:commandButton id="submit" value="Submit"> <!--f:ajax does the magic here and the two attributes that tells JSF what to do during and after the Ajax call to the server is made--> <f:ajax event="click" render="selectOneMenu_id" listener="#{renderBean.doSomething}"/> </h:commandButton> <h:selectOneMenu id="selectOneMenu_id" styleClass="form-control hide" rendered="#{renderBean.rendered}"> <f:selectItem itemLabel="Something" itemValue="Something"/> </h:selectOneMenu> ,因此请务必指定您的内容,或者在how to find components by id上阅读。{/ p>

现在提供指南代码示例:

你的小脸:

@ManagedBean
@ViewScoped 
public class RenderBean{

   private boolean rendered = false;



    //the backing bean method to handle the Ajax call
    public void doSomething(AjaxBehaviorEvent event){
         //do a lot more with the event 
           rendered = true;
         }

    public boolean isRendered() {
        return rendered;
         }

    public void setRendered(boolean rendered) {
        this.rendered = rendered;
         }
}

和你的支持豆

/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the Java client library on Maven or Gradle. Check installation
 *    instructions at https://github.com/google/google-api-java-client.
 *    On other build systems, you can add the jar files to your project from
 *    https://developers.google.com/resources/api-libraries/download/sheets/v4/java
 */

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetRequest;
import com.google.api.services.sheets.v4.model.BatchUpdateSpreadsheetResponse;
import com.google.api.services.sheets.v4.model.Request;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

public class SheetsExample {
  public static void main(String args[]) throws IOException, GeneralSecurityException {
    // The spreadsheet to apply the updates to.
    String spreadsheetId = "my-spreadsheet-id"; // TODO: Update placeholder value.

    // A list of updates to apply to the spreadsheet.
    // Requests will be applied in the order they are specified.
    // If any request is not valid, no requests will be applied.
    List<Request> requests = new ArrayList<>(); // TODO: Update placeholder value.

    // TODO: Assign values to desired fields of `requestBody`:
    BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
    requestBody.setRequests(requests);

    Sheets sheetsService = createSheetsService();
    Sheets.Spreadsheets.BatchUpdate request =
        sheetsService.spreadsheets().batchUpdate(spreadsheetId, requestBody);

    BatchUpdateSpreadsheetResponse response = request.execute();

    // TODO: Change code below to process the `response` object:
    System.out.println(response);
  }

  public static Sheets createSheetsService() throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    // TODO: Change placeholder below to generate authentication credentials. See
    // https://developers.google.com/sheets/quickstart/java#step_3_set_up_the_sample
    //
    // Authorize using one of the following scopes:
    //   "https://www.googleapis.com/auth/drive"
    //   "https://www.googleapis.com/auth/drive.file"
    //   "https://www.googleapis.com/auth/spreadsheets"
    GoogleCredential credential = null;

    return new Sheets.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("Google-SheetsSample/0.1")
        .build();
  }
}

最后,我将指出一个关于如何使用f:ajax的相当好的解释性答案。我希望这会有所帮助。

答案 1 :(得分:0)

您需要在表单焦点和模糊上使用Ajax回调。 使用jquery。使用回调,您可以将元素的类更改为free或used。 您需要使用not template renderer,而不是json response wrapper。