-1

I would like to click a button of a webpage within a web browser.

I know I can do this when I have the Id/Class from the button but I don't have the Id/Class in this case (or it is the same for all buttons).

<form action="" method="POST">
  <button class="btn btn-default btn-sm btn-block" type="submit" name="option" value="0">Button 1</button>
  <button class="btn btn-default btn-sm btn-block" type="submit" name="option" value="1">Button 2</button>
  <button class="btn btn-default btn-sm btn-block" type="submit" name="option" value="2">Button 3</button>
</form>

Lets say I would like to click Button 3. How can I do this?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Gewoo
  • 109
  • 1
  • 3
  • 10

2 Answers2

1

You can do it using nth-child(). So in your case, you might need to do:

$(function () {
  $("form button:nth-child(3)").trigger("click");
});

Note:

  1. You can't use server side C# code to interact with the UI.
  2. You need to use JavaScript to do it.
  3. Add jQuery to use the functions given above.

Adding jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

You can use Selenium and WebDriver to do it:

//this will click on button 3. You can also use "0" or "1" for the other buttons
string value = "2"; 
driver.FindElement(By.CssSelector("[value='" + value + "']")).Click();

This will click on the button by the value attribute.

Download from here

Guide how to add Selenium to visual studio here.

Guy
  • 46,488
  • 10
  • 44
  • 88