How do I get input element id from placeholder text? - c#

I'm using Selenium and C#.
I'm trying to find an element id for an input field by the already typed in text (the elements id is autogenerated randomly for every instance) and then type a new text.
My failed attempt:
public void SetValues(){
var textField = driver.FindElement(By.XPath("//input[contains(text(),'my_text')]"));
((IJavaScriptExecutor)driver)
.ExecuteScript("window.scroll(" + textField.Location.X + "," + (textField.Location.Y - 200) + ");");
textField.sendKeys("some_text");
}
How can I make my code to work?

Place holder is an html attribute so you can use #placeholder, check the following line:
var textField = driver.FindElement(By.XPath("//input[#placeholder='my_placeholder']"));
Edited:
There is no way to get the text entered manually if javascript assigns the value to an attribute.

Related

to carry selected text and id value together of multiselect dropdown to other dropdown using jquery

I have a multiselect dropdown. All of its selected text and values should be displayed as each entry on other dropdown. I coded somewhat like this but its not working. All the selections of multiselect dropdown are appending on a single entry of the other dropdown. It is not displaying as separate entries.
#LstCashAccount is the multiselect dropdown and #ddlDefaultCash is the dropdown where entries selected in multiselect dropdown have to get affected
$('#LstCashAccount').change(function () {
$("#ddlDefaultCash").empty();
$("#ddlLoyaltyAcc").empty();
var CashAcc = "";
var CashAccId = $("#LstCashAccount").val();
CashAccIdSplit = CashAccId.splice(",")
CashAcc = $(this).find("option:selected").text();
CashAccSplit = CashAcc.split(".")
$("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit + '>' + CashAccSplit + '</option>');
});
So there are multiple issues here.
First, it's important to realize that the .append() function is what's actually creating your items. You only call this once, so expecting there to be multiple items is, frankly, a bit silly.
Second, you're using .splice() on a string, which isn't valid. I have a hunch you meant to do .split(), but without your HTML markup, it's a bit of a shot in the dark.
And finally, your CashAccSplit variable is (and, I assume, your CashAccIdSplit is supposed to be) an array. If you just concatenate this with a string, it will output the entire array.
If we clean this up, you might be looking for something more like the following...
$('#LstCashAccount').change(function () {
$("#ddlDefaultCash").empty();
$("#ddlLoyaltyAcc").empty();
var CashAcc = $(this).find("option:selected").text();
var CashAccId = $("#LstCashAccount").val();
var CashAccIdSplit = CashAccId.split(",")
var CashAccSplit = CashAcc.split(".")
//Use .each to iterate through the array, append each member as an item
$.each(CashAccIdSplit, function(index, item) {
$("#ddlDefaultCash").append('<option class="InputDefCash" Id=' + CashAccIdSplit[index] + '>' + CashAccSplit[index] + '</option>');
});
});

Capture value of Textbox when OnChange is defined in the textbox

I have a dynamically generated grid with x number of textboxes that will be in it. As each textbox is generated, I give it an OnChange event that is a set function.
Html.TextBox(... new { #onchange = "ChangeItemQuantity(" + vm.ID + ", " + fk.id + ")" ...
So when it's rendered, it looks like this:
<input ... type="text" onchange="ChangeItemQuantity(1939, 3)" />
Then, in the script section:
function ChangeItemQuantity(ItemId, ForeignKeyId) {
...
}
In the ChangeItemQuantity() function, how would I also capture the new value of the textbox? I don't really want to use an id on the textbox, because it is part of a grid with many textboxes.
Should I pass it in as a parameter? If so, what would the syntax be of the code that renders the textbox?
Or, is there a way to capture is inside the javascript function?
Thanks!
If you want to store data in the html element why not use data- attributes?
Set them like so
#Html.TextBox(.... new { #class="someClass" data-vmId="vm.ID", data-fkId="fk.id" })
Then set a listener on that class
$('.someClass').change(function() {
var value = $(this).val();
var vmid = $(this).data('vmid');
var fkid = $(this).data('fkid');
}

Passing multiple variables between pages and using them

I have three variables I'm trying to pass from one page to another: Two checboxlists (just the checked values) and one DateTime.
I'm getting the checked items like this (this is just for one of these checkboxlists which is called lstUsers):
string cblvalues = "";
foreach (ListItem cbitem in lstUsers.Items)
{
if (cbitem.Selected)
{
cblvalues += cbitem.Value + "-";
}
}
cblvalues = cblvalues.Trim('-');
Response.Redirect("Results.aspx?cblvalues=" + cblvalues);
How would I pass the other checkboxlist and the DateTime to "Results.aspx" as well? I've seen a few different examples such as Server.Transfer, and I'm not sure which one is correct here.
And for using them on the Results.aspx page, would I just do:
string cblvalues = Request.QueryString["cblvalues"];
You can put as many values as you like on the query string. (Though as query strings get very long the web server would eventually impose a limit.) Here you simply append one key/value pair:
Response.Redirect("Results.aspx?cblvalues=" + cblvalues);
Just use a & to separate additional key/value pairs:
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&moreValue=" + moreValues);
If you do get to the point where the query string becomes absurdly long and you basically have a lot of data to pass to the next page, then you'd be looking at other ways of doing this. A simple alternative may be to store the values in session state, redirect the user, then pull the values from session state. Something as simple as this:
Session["cblvalues"] = cblvalues;
Session["moreValues"] = moreValues;
Response.Redirect("Results.aspx");
Then in Results.aspx you can get the values:
var cblValues = Session["cblvalues"];
// etc.
You might also clear the session values once you get them, if the session doesn't need to keep carrying them:
Session.Remove("cblvalues");
You can pass multiple values through query string by seperated them with a &
so your snippet will be like the following:
Let cblSecond be the second combobox then;
// Building first value here
foreach (ListItem cbitem in cblSecond.Items)
{
if (cbitem.Selected)
{
cblSecondValues += cbitem.Value + "-";
}
}
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&cblSecondValues=" + cblSecondValues);
So that you can access them separately like this:
string cblvalues = Request.QueryString["cblvalues"];// gives you the first value
string cblSecondValues= Request.QueryString["cblSecondValues"];// gives you the second value
Response.Redirect(String.Format("Results.aspx?value1={0}&value2={1}&value3={2}", Value1, Value2, Value3));
If you really want to pass them using querystring then you ahouls include them as well
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&cblvalues1=" + cblvalues + "&datetimemy=" + datetimevalue);
Form of a query string like below
http://server_name/path/aspxfile?field1=value1&field2=value2&field3=value3..&fieldn=valuen
As other answer mentioned, there are multiple ways like using Session or cookies or as well you can expose those control values as public properties and use then in next page using Page.PreviousPage property but the restriction is that you will have to use either of Server.Transfer() or Server.Execute() method instead of Response.Redirect.

How to Avoid Updating item searched by Dictionary?

In .NET WinForms C# app, I have a Dictionary<string, RefItemDetails> collection named listItems. I store data in it on start of the app. In a static class I have as follows:
// listItems is populated bt reading a file.
// No other operations are performed on it, except finding an item.
public static Dictionary<string, RefItemDetails> itemsList;
// Find RefItemDetails of barcode
public static RefItemDetails FindRefItem(string barcode)
{
RefItemDetails itemDet = null;
try
{
//if (itemsList.TryGetValue(barcode, out itemDet) == false)
// System.Diagnostics.Debug.WriteLine("Barcode " + barcode + " not found in Items");
//itemDet = itemsList.First(item => item.Key == barcode);//.First(item => item.Barcode == barcode);
if (itemsList.ContainsKey(barcode))
itemDet = itemsList[barcode];
}
catch (Exception)
{
itemDet = null;
}
return itemDet;
}
For retrieving an item from listItems in another class, I use :
refScannedItem = null;
// Get Unit Barcode & Search RefItem of it
refScannedItem = UtilityLibrary.FindRefItem(boxItem.UnitBarcode.Trim());
// Display BOX item details
refScannedItem.Barcode = boxItem.BoxBarcode.Trim();
refScannedItem.Description = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
refScannedItem.Retail *= boxItem.Quantity;
refScannedItem.CurrentCost *= boxItem.Quantity;
Here what happens above is, I search for an item & I get it "refScannedItem" and I append the Description of it by "BOX of " + boxItem.Quantity + " " + refScannedItem.Description; . So if the original Description was "Aquafina", I make it "BOXof 10 Aquafina". The nest time I scan the same product, I find the product, but now its descrption has become "Box of 10 Aquafina", so my line of setting Description turns to "BOX of 10 BOX of 10 Aquafina". The same goes on like "BOX of 10 BOX of 10 BOX of 10 Aquafina" and so on.
As you cna see in my find code, I had initially used TryGetValue, then tried using LINQ, then tried using ContainsKey, but in all of them why does the value of listItem get updated.
I understand that as TryGetValue has out parameter, so the value is passed as a reference, and then it will be chnaged. But in listItems[key] also updates it !!! How can I avoid this to happen ? I had selected Dictionary collection for easy & fast searching, but this part gives a lot of problems and a big bug too on my app. I couldn't find nay solution where the receive the value but shouldn't be updated. All articles shows how to search & update it.
Kindly suggest a solution for the above. Any help is highly appreciated.
Thanks
You return a pointer to the item contained in your Dictionary, so it makes sense that any manipulations you make to this Object will be stored in the original Dictionary object.
What you want to do is, in FindRefItem, return a pointer to a copy of your RefItemDetails object.
An easy way to do this would be to write a new constructor.
Something like:
public RefItemDetails(RefItemDetails original)
{
this.Barcode = original.Barcode ;
this.Description = original.Description ;
this.Retail = original.Retail ;
this.CurrentCost = original.CurrentCost ;
//Set any other properties here
}
and then replace return itemDet; with return new RefItemDetails(itemDet);
I think you are going about this the wrong way.
You shouldn't have a writeable Description property that you update whenever the quantity changes.
Instead, I think you should have a separate Name property which contains the name of the item (e.g. Aquafina) and a dynamically-created readonly Description property like so:
public string Description
{
get
{
return string.Format("Box of {0} {1}", Quantity, Name);
}
}
Or something along similar lines.
This should do the trick:
if (!refScannedItem.Description.StartsWith("BOX of "))
{
refScannedItem.Description = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
}
You are getting an object from a Dictionary - and then changing it, so of course it's properties will change in the Dictionary as well ... you haven't cloned it so why would you be taking a copy?
The solution is quite simply not to change the values of the item and use the amended text in a different way:
var amendedDescription = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
Looks like you need to make a copy of the RefItemDetails to make modifications to after you get it back from the call to UtilityLibrary.FindRefItem(boxItem.UnitBarcode.Trim())

C# Jquery Reference Error is Undefined

I have a C# MVC4 application in which I am writing a JQuery function to grab some values, post to an ActionResult and then refresh a partial view. All functionality is working except for setting a new var equal to the value of a variable within one of my div elements.
The pre-existing variable is called myName and is located in a div with an id of NameDiv.
Ive tried these four versions of code and each results in: Reference Error myName is not defined.
var origname = myName;
var origname = myName.value();
var origname = myName.val();
var origname = $('#NameDiv').valueOf(myName);
When running the application and inspecting element, I see that myName is populating with the correct value.
Use:
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
// console.log(origname);
This will find the element on the page with the id of "NameDiv". Then it gets the input elements on the page with the name of "myName". Then it gets the first one found. It will then get the value of it (by using .val()), and store that value in the variable origname.

Categories