ABHISHEK DAS
ABHISHEK DAS

Reputation: 63

The radio button is not getting selected with this HTML code for that. How to do that?

<input id="radio2" name="radioGroup" type="radio">
<label class="flRight" for="radio2">
  ::before
  "Senior Citizen"
  ::after
</label>
WebElement senior = driver.findElement(By.id("radio2"));
      senior.click();

Now the problem is the code is not able to click the desired element.

Upvotes: 1

Views: 63

Answers (4)

Moshe Slavin
Moshe Slavin

Reputation: 5204

Use WebDriverWait:

WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement senior = wait.until(ExpectedConditions.elementToBeClickable(By.id("radio2")));
senior.click();

After seeing the WebSite it looks like the input is not the element you want to click rather the label...

So just change the senior var to:

WebElement senior = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='RadioButton']//label[@for='radio2']")));

The best way to automate human actions in the case where the element is not clickable dew to other elements covering them is to use Actions:

WebElement senior = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='RadioButton']//label[@for='radio2']")));
Actions actions = new Actions(driver);
actions.moveToElement(senior).click().build().perform();  

(using JavascriptExecutor and executeScript doesn't realy click... it just invokes the method that can be good but not for testing...)

As a last resort use JavascriptExecutor:

JavascriptExecutor jse= (JavascriptExecutor) driver; 
jse.executeScript("arguments[0].click();", senior);

Upvotes: 1

Pratik
Pratik

Reputation: 357

Try with this:

WebElement senior = driver.findElement(By.xpath(".//div[@class='radioBtn']/label[2]"));
    WebElement close = driver.findElement(By.xpath(".//div[@id='nvpush_cross']"));
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOf(close));
    close.click();
    senior.click();

Code didnt worked before because there is popup you need to close it.

Upvotes: 1

SeleniumUser
SeleniumUser

Reputation: 4177

Please try below solution :

  WebDriverWait wait = new WebDriverWait(driver, 10);
  WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[@class='flRight' and @for='radio2']")));

  Actions action=new Actions(driver);
  action.moveToElement(element).click().perform();

Upvotes: 0

KunduK
KunduK

Reputation: 33384

You need to induce WebdriverWait And to click on the radio button use JavaScript Executor since neither webdriver click nor action class is working

WebDriverWait wait = new WebDriverWait(driver, 20); 
WebElement item=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[@class='flRight' and @for='radio2']")));
JavascriptExecutor js= (JavascriptExecutor) driver; 
js.executeScript("arguments[0].click();", item);

Upvotes: 1

Related Questions