Saturday, 20 August 2016

Selenium2: WebDriver: click: Clicks this element

WebElement interface provides click method to click a web element. There are some preconditions for an element to be clicked. The element must be visible and it must have a height and width greater then 0.


index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
 <script>
  window.onload = function() {
   var radios = document.getElementsByName('o1');
   for (i = 0; i < radios.length; i++)
    radios[i].onclick = checkFire;
  };

  function checkFire(e) {
   var fires = document.getElementById('relocate');
   var evt = e || window.event;
   var target = evt.target || evt.srcElement;
   if (target.checked && target.id === 'yes')
    fires.disabled = false;
   else {
    fires.checked = false;
    fires.disabled = true;
   }
  }
 </script>

 <div>
  Do you like programming<input type="radio" name="o1" id="yes" />Yes <input
   type="radio" name="o1" id="no" />No
 </div>
 <div id="job">
  <input type="checkbox" name="e1" id="relocate" disabled />Are you
  intrested to relocate
 </div>

</body>
</html>

index.jsp generates above jsp page. By default check box is disabled.

<input type="checkbox" name="e1" id="relocate" disabled />


Checkbox will be enabled once you select the radio button yes.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {
 public static void main(String[] args) {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://localhost:8080/application");

  WebElement yesRadioButtion = driver.findElement(By.id("yes"));
  WebElement relocateCheckBox = driver.findElement(By.id("relocate"));
  
  System.out.println("Is checkbox displayed " + relocateCheckBox.isDisplayed());
  System.out.println("Is checkbox enabled " + relocateCheckBox.isEnabled());
  
  yesRadioButtion.click();
  
  System.out.println("\nSelected the yes check box\n");
  
  System.out.println("Is checkbox displayed " + relocateCheckBox.isDisplayed());
  System.out.println("Is checkbox enabled " + relocateCheckBox.isEnabled());
  
  driver.close();
 }
}


Output
Is checkbox displayed true
Is checkbox enabled false

Selected the yes check box

Is checkbox displayed true
Is checkbox enabled true







Previous                                                 Next                                                 Home

No comments:

Post a Comment