click() on css Selector not working in Selenium webdriver - button

HTML
<input class="button" type="button" onclick="$.reload('results')" value="Search">
I don't have an id or name for this . Hence am writing
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://....");
driver.findElement(By.cssSelector("input[value=Search]")).click();
But click() is not happening.
Tried
driver.findElement(By.cssSelector(".button[value=Search]")).click();
Tried
value='Search' (single quotes).
these Selectors are working in
.button[value=Search] {
padding: 10px;
}
input[value=Search] {
padding: 10px;
}

i would inject piece of js to be confident in resolving this issue:
first of all locate element using DOM (verify in firebug):
public void jsClick(){
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("document.getElementsByTagName('button')[0].click();");
js.executeScript(stringBuilder.toString());
}
jsClick();
from the retrospective of your element it be like:
....
stringBuilder.append("document.getElementsByTagName('input')[0].click();");
....
Please, note: document.getElementsByTagName('input') returns you an array of DOM elements. And indexing it properly e.g. document.getElementsByTagName('input')[0], document.getElementsByTagName('input')1, document.getElementsByTagName('input')[2]....
,etc you will be able to locate your element.
Hope this helps you.
Regards.

Please use the below code.
driver.findElement(By.cssSelector("input[value=\"Search\"]")).click();
It works for me. And make sure that the name is "Search", coz it is case sensitive.
Thanks

Are you sure that using this CSS-selector (input[value=Search]) on your page you have only one result?

single quotes are missing in your code, the [value=Search] should be replaced with [value='Search'].
first you have to check if the selector u are using will work or not..
If you are using chrome or FF,you can follow these steps,
go to the page where button (to be clicked) is present,
open web console and type in the following and click enter..
$("input[value='Search']")
or
$("input[value='Search'][type='button']")
or
$("input[value='Search'][type='button'].button")
you will get a list of elements which can be accessed using this selector, if that list contains only one element (button that you want to click), then this selector is valid for your use..otherwise u'l have to try some other selector..
If any of the above selector is valid,u'l have to change your code accordingly..
driver.findElement(By.cssSelector("input[value='Search'][type='button'].button")).click();

Related

Find element within table cell in webdriver using java

I want to check if there is a clickable image present in the table cell.
If(clickable image present)
{
//
}
else
{
//
}
How do I do it in webdriver using Java?
Does your image tag have a name or id associated with it ?? Please post some code to help us help you.
in that case use
WebElement image = driver.findElement(By.name("imagename"));
image.click();
or
WebElement image = driver.findElement(By.id("imageid"));
image.click();
This identification can be done on name,id,class,xpath etc.
If not you may have to use xpath or css selectors
WebElement image = driver.findElement(By.xpath("xpath"));
image.click();
You can check if the image is clickable by using
WebDriverWait wait = new WebDriverWait(yourWebDriver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//xpath_to_element"));
and then perform element.click().

How to make an assertion based on class name in web driver

The HTML is as follows:
<section class="my-account-box-element">
<span class="item icon-home icon-color-1"></span>
</section>
Need to make an assertion based on the class name which changes from 'icon-home icon-color-1' to 'icon-home icon-color-0' depending upon the condition.
First i must warn that you can't add two classes when searching for it using the By, since 'item', 'item-home' on your example are the same. I'm going to assume the main difference is in 'item-color-1' and 'item-color-0'.
WebElement myAccountBoxElement = driver.findElement(By.className("my-account-box-element"));
WebElement spanItem = myAccountBoxElement.findElement(By.tagName("span"));
boolean itemColor = (spanItem.getAttribute("class").contains("item-color-1")) ? true : false;
if (itemColor) {
// do stuff for item-color-1 element
}
// do stuff for the item-color-0 element
}
The above code should work flawlessly provided the above code is the actual HTML, if there are more tags, use findElements() instead and loop in it.
Also i went with a ternary if since it keeps a cleaner code, providing you are only working with those two elements
change as per your needs
assertTrue(driver.findElements( By.Xpath(".//span[contains(#class,'icon-color-1')]")).size() != 0)
Can also use this
By.className("classname");
boolean isElementPresent = driver.findElement(By.className("classname"));

How to get the radiobutton for corresponding datalisty item?

I want to convert this code to JavaScript code:
rdb1 = (RadioButton)DataList1.Items[i].FindControl("rdb1");
How can it be done?
Put a unique class on the radio button and then you can easily use jQuery to walk the DOM and find that control.
Here is an example of finding a control here on Stack Overflow.
Here is a tutorial of How to Get Anything You Want from a web page via jQuery.
Good luck, and hope this helps.
In JavaScript using the id attribute makes it easy to retreive a specific element since the id must be unique for all tags.
var radio1= document.getElementById("rdb1"); //this returns the element
Here is a simple tutorial on how to do other things after getting the element.
EDIT- I see you just want the selected value in javascript:
function radiochanged(){
var radio1= document.getElementById("rdb1");
var rdb1_value;
for (i=0;i<radio1.length;i++)
{
if (radio1[i].checked)
{
rdb1_value = radio1[i].value;
}
}
}
<input id="rdb1" type="radio" onClick="radiochanged()">

Use naming convention to apply class if label contains text

I'm new to jquery, and sorry if this question is asked before (could find exactly what I was looking for)
I would like to implement the following convetion: If I create a error label with the name '_lblError' like this:
<div>
<asp:label ID="_lblError" text="this is a error msg"/>
</div>
classA or classB would be applied to it depending on a empty string or not in the 'text' parameter of the label.
I also would like to place this code in a external js file that would be used throughout the app.
Thanks for any help!
To start with, you probably need to give the label a css class that can be used for selection:
<asp:Label Id="_lblError" Text="This is the error message"
CssClass="ThisIsWhatWeWillllWorkWith" />
This will probably output something like
<span id="ct100__lblError" class="ThisIsWhatWeWillWorkWith">
This is the error message.
</span>
You can now select the label in jQuery using the class as selector, and add class A or B depending on whether the .text() property is empty or not.
$(function() {
$('.ThisIsWhatWeWillWorkWith').each(function() {
if($(this).text() == '') { $(this).addClass('ClassA'); }
else { $(this).addClass('ClassB'); }
});
});
All code is provided as is, with no guarantees of working without modification. But you get the general idea of how to solve the problem...
EDIT: In response to your comment, here's a way to do it without adding a css class to the label. Instead of using an <asp:Label> tag for the error message, wrap a literal in a tag you hard-code on your page:
<span class="ThisIsWhatWeWillWorkWith"><asp:Literal ID="__ltlError" Text="This is the error message.</asp:Literal></span>
Another, perhaps more elegant way, would be to create your own custom label, and use that instead.
public class ErrorLabel : System.Web.UI.WebControls.Label
{
public ErrorLabel() {
this.CssClass = "ThisIsWhatWeWillWorkWith";
}
}
You then put the error message on your page with the following line:
<asp:ErrorLabel ID="__lblError" Text="This is the error message" />
Again, not sure if the above code will work as is. But again, you get the idea of what to do...
If the idea is to provide say, have different font and/or background if there is an error and display nothing if there is no text in the error label then you could make the control a literal instead of a label. The literal control does not create a control with no text (MSDN doc)

Forcing client ids in ASP.NET

I know that in the next version of ASP.NET we'll finally be able to set the clientids on System.Web controls without the framework doing it for us in a quasi-intelligent way e.g:
id="ctl00__loginStatus__profileButton"
Does anyone know a good method in the meantime to force the above id to something like
id="profileButton"
The main reason for this is manipulation of the clientids in jQuery when dynamically adding controls to a page. The problem I can see is changing the ids will break the Viewstate?
You have to use the ClientIDMode attribute:
<asp:xxxx ID="fileselect" runat="server" ClientIDMode="Static"/>
What I tend to do is dynamically generate javascript methods which handle this. You can do this in markup or code behind so for example:
<script language="javascript" type="text/javascript">
function doXYZ()
{
$("#" + getListBoxId()).css(...)
}
function getListBoxId()
{
return "<%=this.myListBox.ClientId>";
}
</script>
You can also build the functions in the code behind and register them.
EDIT
A couple months ago I needed to fix the id of some server controls, I managed to hack it in and I described my method here here.
Basically you need put the controls inside a naming container like a user control, and then override a couple of properties which prevents the child controls from getting their uniqueid.
The performance isn't great, but you can use this selector syntax to match messy ClientIDs:
$("[id$='_profileButton']")
That matches any element ending in _profileButton. Adding the leading underscore ensures that you're matching the desired element and not another element that ends in the substring "profileButton" (e.g. "myprofileButton").
Since it has to iterate over the entire DOM, the performance can be poor if you use it in a loop or several times at once. If you don't overuse it, the performance impact is not very significant.
Another way would be to wrap your control with a div or span with a static id, then access the control through that.
E.g.
<span id="mySpan">
<asp:TextBox id="txtTest" runat="server" />
</span>
You could then target input tags inside MySpan. (though I agree it would be nice to be able to specify a nice name, provided you could handle the naming conflicts...)
I have often run in to this "problem" while developing in asp.net webforms. In most cases I tend to use the css class of the element.
jQuery(".My .Container12")
Before starting to manipulate the id:s, perhaps that is a way you can handle it aswell? It's a simple solution.
There is another solution not mentioned which is to subclass the ASP.NET controls and force the IDs:
public class MyCheckBox : CheckBox
{
public string ForcedId { get;set; }
public override string ID
{
get
{
if (!string.IsNullOrEmpty(ForcedId))
return ForcedId;
else
return base.ID;
}
set
{
base.ID = value;
}
}
public override string ClientID
{
get
{
return ID;
}
}
}
Then use this where you know the IDs will never clash:
<mytag:MyCheckBox ForcedId="_myCheckbox" runat="server" />
If you are using lists you will need to write a ListControlAdapter, and also adapters for each type of list you're using (dropdown,checkbox,radiobutton,listbox). Alternatively cross your legs and wait for .NET 4.0.

Resources