How can I check the checkbox state using Selenium? - c#

How can I verify if a checkbox is checked or unchecked using Selenium?
Because method "element.Selected" does not work in this case.
Here is the HTML code if a checkbox is checked:
<td class="dxgvCommandColumn_MetropolisBlue dxgv" onclick="aspxGVScheduleCommand('messageGrid',['Select',1],1)" align="center">
<span id="messageGrid_DXSelBtn1_D" class="dxICheckBox_MetropolisBlue dxichSys dxWeb_edtCheckBoxChecked_MetropolisBlue">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
</td>
Here is the HTML code if a checkbox is unchecked:
<td class="dxgvCommandColumn_MetropolisBlue dxgv" onclick="aspxGVScheduleCommand('messageGrid',['Select',1],1)" align="center">
<span id="messageGrid_DXSelBtn1_D" class="dxWeb_edtCheckBoxUnchecked_MetropolisBlue dxICheckBox_MetropolisBlue dxichSys">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
</td>
Image:

As per the HTML you have shared, it's clear that the <span> tag of the outerHTML of the Checkbox contains the following class attributes:
Checked
<span id="messageGrid_DXSelBtn1_D" class="dxICheckBox_MetropolisBlue dxichSys dxWeb_edtCheckBoxChecked_MetropolisBlue">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
Unchecked
<span id="messageGrid_DXSelBtn1_D" class="dxWeb_edtCheckBoxUnchecked_MetropolisBlue dxICheckBox_MetropolisBlue dxichSys">
<input id="messageGrid_DXSelBtn1" value="U" readonly="readonly" style="border-width:0;width:0;height:0;padding:0;margin:0;position:relative;background-color:transparent;display:block;" type="text"/>
</span>
So to check if the Check Box is checked or unchecked you can induce the following validation:
if(driver.FindElement(By.XPath("//input[#id='messageGrid_DXSelBtn1']//preceding::span[1]")).GetAttribute("class").contains("dxWeb_edtCheckBoxChecked_MetropolisBlue"))
Console.WriteLine("Check Box is Checked");
else
Console.WriteLine("Check Box is Unchecked");

"element.Selected" is not working, because you do not have checkbox element on the page at all. Selenium does not know that the input "looks" like checkbox. It is just HTML input of type: "text".
Your only chance is to get the JavaScript executor and check the attributes yourself (elm is your Selenium "input" object got by XPath or CSS selector):
To set the value
ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
new object[] {elm, "value", value });
To get the value:
ExecuteScriptReturn("return arguments[0].getAttribute(arguments[1]);",
new object[] {elm, "value" });
where the method is:
private void ExecuteScript(string script, object[] arguments)
{
var jsExecutor = (IJavaScriptExecutor)_browser;
jsExecutor.ExecuteScript(script, arguments);
}
private void ExecuteScriptReturn(string script, object[] arguments)
{
var jsExecutor = (IJavaScriptExecutor)_browser;
return (string)jsExecutor.ExecuteScript(script, arguments);
}
EDIT:
Just note you in fact are not checking the value of input in this case, but the value of class of these two elements:
span id="messageGrid_DXSelBtn1_D" class="dxICheckBox_MetropolisBlue dxichSys dxWeb_edtCheckBox**Checked**_MetropolisBlue"
and
span id="messageGrid_DXSelBtn1_D" class="dxWeb_edtCheckBox**Unchecked**_MetropolisBlue dxICheckBox_MetropolisBlue dxichSys"

Related

HTML-Razor float as input value

I have this bit of HTML which should call /nodes/calibratePH?value=afloatnumber:
<div style="float:left; width:50%; margin-bottom:30px;">
<h3>PH calibration</h3>
<form id="CalibrationBar" action="/Nodes/CalibratePH" method="post">
<select id=ids type="text" name="name">
<option value="0" disabled selected>name</option>
#{
foreach (var configuration in Program.CAN_Listener.KnownConfigID)
{
if (configuration.type == Web_App.Models.Sensor_Types.PH)
{
<option value="#configuration.name">#configuration.name</option>
}
}
}
</select>
<input type="number" step="0.01" max="10.0" min="-10.0" placeholder="calibration value" name="value">
<input type="submit" value="calibrate PH">
</form>
The problem is, when I enter for instance: 3.09 or 3,09 (doesn't matter). The method CalibratePH in the controller(MVC, ASP.NET) gets the value: 309. 1.1 gives 11, and so forth. Does anyone have an idea how to solve this? I'm thinking about entering the input as text and evaluate the value upon recieval in the method, but that's not how it should be... right?
EDIT:
This guy seems to have sort of the same problem
I suggest you to make the parameter string on method calibratePH and when you receive it then cast it to float number.

Blazor List Of Strings Input Binding

I'm trying to display a list of strings and I want the user to be able to edit the list to make changes to the object but when I view the list after modifying the input fields the changes haven't been made.
How do I bind a list of strings?
#foreach (var message in UserMessageService.GetSomeData())
{
<tr>
<td><input type="text" bind="#message.Username" value="#message.Username" onblur="SaveMessages"/></td>
<td><input type="text" bind="#message.Message" value="#message.Message" onblur="SaveMessages"/></td>
</tr>
}
Use right Blazor syntax:
<input
type="text" #bind="#message.Message"/>
If you need to execute function on blur:
<input value="#message.Message"
#onchange="#((ChangeEventArgs __e) =>
{ message.Message = __e.Value.ToString());
SaveMessages(); })" />
More info: https://learn.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#data-binding
silly mistake on my part, the issue wasn't with my syntax. I made the mistake of binding to my service instead of a local variable so when I left focus it couldn't update and just retrieved from the service
I simply added the local variable below
#foreach (var message in dataVariable)
{
<tr>
<td><input type="text" #bind="message.Username" /></td>
<td><input type="text" #bind="message.Message" /></td>
</tr>
}
#code {
private List<someData> dataVariable;
protected override void OnInitialized()
{
TableSeats = UserMessageService.GetSomeData();
}
}

How to use unobtrusive validation to make an input field required field if another input field is empty?

I have a simple form with three different text boxes to enter the search criteria before a resultset can be returned. Among the three fields I want to make two fields conditionally required if the other one is empty.
In the attached screenshot the search form cannot be submitted without entering either the "Title" or "Performers" fields. It is fine if both fields have values. I wanted to achieve this by making "Title" as a required field when "Performers" is empty. But my code below doesn't work. I have the necessary validation at the server side. I am looking for a client side solution.
HTML Source code:
<form id="searchWorkForm">
<div class="contourField textfield">
<label for="searchWorkTitle" class="fieldLabel">Title</label>
<div class="search-input">
<a id="searchWork" href="#" style="z-index: 2000; margin-top: 0;"><img src="/images/profile-search.png" alt="" style="z-index: 1000;" id="profileSearch" /></a>
<input type="text" name="searchWorkTitle" id="searchWorkTitle" class="text caps" value="" placeholder="Title" data-val="true" data-val-requiredif="title is mandatory" data-val-requiredif-otherpropertyname="searchWorkPerformer">
<span class="field-validation-valid" data-valmsg-for="searchWorkTitle" data-valmsg-replace="true"></span>
</div>
</div>
<div class="contourField textfield">
<label for="searchWorkWriter" class="fieldLabel">Writers</label>
<div class="wideInput">
<input type="text" name="searchWorkWriter" id="searchWorkWriter" class="text caps" value="" placeholder="Writer Name">
<span class="field-validation-valid" data-valmsg-for="searchWorkWriter" data-valmsg-replace="true"></span>
</div>
</div>
<div class="contourField textfield">
<label for="searchWorkPerformer" class="fieldLabel">Performers</label>
<div class="wideInput">
<input type="text" name="searchWorkPerformer" id="searchWorkPerformer" class="text caps" value="" placeholder="Performer Name" data-val="true">
<span class="field-validation-valid" data-valmsg-for="searchWorkPerformer" data-valmsg-replace="true"></span>
</div>
</div>
</form>
Client side validation code:
$(function() {
if ($.validator && $.validator.unobtrusive) {
$.validator.addMethod("requiredif", function (value, element, params) {
return !(value.length === 0 && $(params).val().length === 0);
});
$.validator.unobtrusive.adapters.add("requiredif", ["otherpropertyname"], function (options) {
options.rules["requiredif"] = "#" + options.params.otherpropertyname;
options.messages["requiredif"] = options.message;
});
}
$("#searchWork").click(function() {
if ($("#searchWorkForm").valid()) {
// Make an Ajax Call and get the search result
}
});
}
You first need to move the $.validator.addMethod() and $.validator.unobtrusive.adapters.add() functions outside the $(function() { .. }
But based on the description of what your wanting to validate, then the code in your $.validator.addMethod() method should first check if the 'other property' (searchWorkPerformer) has a value, and if so return true. If it does not, then check if searchWorkTitle has a value. If it has, then return true, otherwise its invalid, so return false.
// scripts for jquery, jquery.validate and jquery.validate.unobtrusive
<script>
$.validator.addMethod("requiredif", function (value, element, params) {
if ($(params).val().length === 0) {
return true;
} elseif (value.length === 0) {
return false;
}
return true;
});
$.validator.unobtrusive.adapters.add("requiredif", ["otherpropertyname"], function (options) {
options.rules["requiredif"] = "#" + options.params.otherpropertyname;
options.messages["requiredif"] = options.message;
});
$(function() {
$("#searchWork").click(function() {
if ($("#searchWorkForm").valid()) {
// Make an Ajax Call and get the search result
}
});
}
</script>
Side note: requiredif does not really describe your validation - perhaps requiredifempty would be more appropriate since you only require a value if the other property is empty.

Cant get values of inputs asp.net

My problem i always get null from my inputs or default value. Some how if i set value at page_load like Form_txt_Ad.Value="ExampleValue"; i can get it. But i cant get any value from inputs.
protected void Save_Button_Click(object sender, EventArgs e)
{
string exapmle = Form_txt_Ad.Value;
string example = Form_txt_Soyad.Value;4
}
<div class="input">
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" runat="server" />
<span><i class="glyphicon glyphicon-user"></i></span>
</div>
<div class="col-md-12" style="text-align: center;">
<button type="button" runat="server" onserverclick="Save_Button_Click" class="btn btn-success btn-raised btn-lg" title="Kaydet"><i class="glyphicon glyphicon-floppy-saved icon-marginRight"></i>Kaydet</button>
</div>
Thx for help.
Make sure all your control elements are placed inside <form> ... </form> tag.
Since you have placed runat="server" you should be able to get the value by either using any of them
Form_txt_Ad.Value
(OR)
Form_txt_Ad.Text
Else use Request.Form["Form_txt_Ad"]
Not sure though why not use a server side control using <asp:TextBox ... which will allow you to get the textbox value directly using the Text property
Add the name attribute to your input and make sure it's inside a form element.
<form>
...
<input type="text" translate translate-attr-placeholder=".PLACEHOLDER_NAME" placeholder="Ad" id="Form_txt_Ad" name="Form_txt_Ad" runat="server" />
...
</form>

RadioButtonList SelectedItem always returns EmptyString

I have this custom radiobuttonlist I'm using in my .aspx page in order to be able to get the GroupName to actually work since I will have 2 RadiobuttonList controls on the same .aspx page:
public class CustRadioButtonList : RadioButtonList, IRepeatInfoUser
{
void IRepeatInfoUser.RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
RadioButton radioButton = new RadioButton();
radioButton.Page = this.Page;
radioButton.GroupName = "radioButtonGroup";
radioButton.ID = this.ClientID + "_" + repeatIndex.ToString();
radioButton.Text = this.Items[repeatIndex].Text;
radioButton.Attributes["value"] = this.Items[repeatIndex].Value;
radioButton.Checked = this.Items[repeatIndex].Selected;
radioButton.TextAlign = this.TextAlign;
radioButton.AutoPostBack = this.AutoPostBack;
radioButton.TabIndex = this.TabIndex;
radioButton.Enabled = this.Enabled;
radioButton.RenderControl(writer);
}
}
So that's just a simple extentension where I set the GroupName to be sure that all the radiobuttons created by that RadioButtonList have the same GroupName so that now, if anyone selects a value from RadiobuttonList1, it deselects any value they have selected in Radiobutton2 and vice versa (so they are mutually exclusive sets of radiobuttons).
Note: The radiobuttonlists are definitely being binded via a method call that's wrapped in a check for !Page.IsPostBack so that is not the issue here.
Here is an example where I'm using it in my .aspx page:
<aj:CustRadioButtonList checked="false" ID="rblEmail" runat="server" />
<aj:CustRadioButtonList checked="false" ID="rblReason" runat="server" />
Here in my code-behind, I'm checking for the selectedValue from the rblEmail within an onclick even of a button on my page..but it always returns empty string even if I have selected an item in the list:
protected void btnContinue_Click(object sender, EventArgs e)
{
_actionID = rblEmail.SelectedValue;
I've spent an entire day around trying to figure out now why I keep getting an emptystring when clearly I have selected a value in rblEmail. Same holds true for the other radiobuttonlist rblReason. In either case, when checking from code-behind I get emptystring for SelectedValue.
If you look at the markup, here's how it looks:
<table id="rblEmail" checked="false" border="0">
<tr>
<td><input id="rblEmail_0" type="radio" name="radioButtonGroup" value="0" /><label for="rblEmai_0">All Offers</label></td>
</tr><tr>
<td><input id="rblEmail_1" type="radio" name="radioButtonGroup" value="1" /><label for="rblEmail_1">week</label></td>
</tr><tr>
<td><input id="rblEmail_2" type="radio" name="radioButtonGroup" value="2" /><label for="rblEmail_2">month</label></td>
</tr><tr>
<td><input id="rblEmail_3" type="radio" name="radioButtonGroup" value="3" /><label for="rblEmail_3">Holiday</label></td>
</tr>
</table>
</div>
...
<table id="rblReason" checked="false" border="0">
<tr>
<td><input id="rblReason_0" type="radio" name="radioButtonGroup" value="1" /><label for="rblReason_0">I receive</label></td>
</tr><tr>
<td><input id="rblReason_1" type="radio" name="radioButtonGroup" value="2" /><label for="rblReason_1">I have no need</label></td>
</tr><tr>
<td><input id="rblReason_2" type="radio" name="radioButtonGroup" value="3" /><label for="rblReason_2">Other</label></td>
</tr>
</table>
Don't know exactly why this isn't working, but it seems like a little javascript would provide an easy workaround. Instead of a custom control, just use regular RadioButton objects... then attach some javascript to clear the selection on List1 when something on List2 is selected, and vice versa.
Not sure why you'd use any sort of repeater here if you already know how many radiobuttons there would be? (per your comments above)
It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RadioButtonList
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}

Categories

Resources