jQuery text() with <select> - c#

I have a drop downlist as follows:
<select id="example" name="example" runat="server">
which gets populated in the code behind like this:
example.DataSource = new CampControl().GetCountries();
example.DataTextField = "CountryDesc";
example.DataValueField = "ID";
example.DataBind();
example.Attributes.Add("multiple", "multiple");
and on the click of the items in the list I have a jQuery function:
$inputs = this.inputs,
$checked = $inputs.filter(':checked'),
$checked.each(function (index) {
alert($(this).text());
});
But $(this).text() is always coming back as an empty string,
Am I doing anything wrong? Please help
Thanks in advance.

You are looking for the :selected attribute, not :checked

try this:
$inputs = this.inputs,
$checked = $inputs.filter.is(':checked'),
$checked.each(function (index) {
alert($(this).text());
});

try this one
$inputs = this.inputs;
$checked = $inputs.val();
$checked.each(function (index) {
alert($(this).text());
});

I got the value using this:
$inputs = this.inputs,
$checked = $inputs.filter(':checked'),
$checked.each(function () {
alert(($(this)[$(this).index()].title));

In drop downlist we need to populate n'of option to select ,after selecting the option. we can get selected text using below query...
var exampleValue = $("#example option:selected").text();

Related

C# Selenium - dropdown menu/ combobox

I have a problem selecting from a custom dropdown menu.. I have tried both by using the XPath, CssSelector and Id.
I have added a link to the code here:
Picture of the code
I think i have to access the div class="SelectBox" in order to access the id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype'
but i keep getting errors.
This is what I'm currently trying but without any luck:
IWebElement test = driver.FindElement(By.XPath("//div[#class='input']//div[#id='ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype']"));
Can someone give me a clue on how to get access to the items in the dropdown?
Thank you! :)
You need to use "SelectElement" instead of "IWebElement".
SelectElement mySelect = new SelectElement(yourDriver.FindElement(By.Id("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype")));
mySelect.SelectByText("510111 Normalbehandling");
Try This
var select = driver.FindElementById("ctl00_ctl00_ctl00_MP_Blank_Body_MP_Base_Body_MP_TopSideMenu_Body_ctl00_cboBehandlingstype");
var stringValues = select.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
((IJavaScriptExecutor)driver).ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, stringValues[0]);

DropDownList selected value on a razor view page

I have the following DropDownList on a View Layout page that displays languages from an SQL database. I want the selected item of the dropdownlist to be the page current culture (originalCulture). How can I accomplish that?
For example if the page current culture (originalCulture="en") is equal to (item.language_UI="en") then the DDL selected item should be English (item.language). I know that it's easy but I'm not familiar with Razor codes. Can someone help?
#{
var db = Database.Open("DefaultConnection");
var listLanguage = "SELECT language, language_UI FROM Languages";
var originalCulture = Convert.ToString(System.Globalization.CultureInfo.CurrentCulture.TwoLetterISOLanguageName);
List<SelectListItem> languagedropdownlistdata = new List<SelectListItem>();
bool isSelected = false;
foreach (var item in db.Query(listLanguage))
{
languagedropdownlistdata.Add(new SelectListItem
{
Text = item.language,
Value = item.language_UI,
Selected = isSelected
});
}
}
And here is the DropDownList on the content page:
#Html.DropDownList("lang", languagedropdownlistdata
<input type="submit" value="Select" />
It is not really the "Razor" codes. It is mostly C# :)
Your isSelected variable seems to be false always.
You need to change your loop body to the following:
foreach (var item in db.Query(listLanguage))
{
languagedropdownlistdata.Add(new SelectListItem
{
Text = item.language,
Value = item.language_UI,
Selected = (item.language_UI == originalCulture)
});
}
The statement (item.language_UI == originalCulture) would be true only if the language_UI propery will contain exactly the same string as originalCulture, therefore your code should work properly.

Is it possible to get data from C#/Razor in jQuery by way of HTML?

I want to get data from a C# function, store it in a hidden HTML field, and then access it in jQuery.
This is what I'm thinking:
C#:
public static string getDuckbillDepts()
{
List<string> duckbillDptsStr = new List<string>();
for (int i = 2; i < 100; i++)
{
duckbillDptsStr.Add(i);
}
return string.Join(",", duckbillDptsStr); // <-- will this work?
}
Razor:
// I first wanted to use List<int> but then realized HTML would probably mutiny if I tried to give it that data type
#{string duckbillDeptsCSV = CCRReporterUtils.getDuckbillDepts()}
HTML:
<input type="hidden" name="AllDepts" id="hiddenAllDepts" value="#duckbillDeptsCSV" />
jQuery:
var deptsArray = $('hiddenAllDepts').val();
...but "duckbillDeptsCSV" in the HTML is red, indicating (right?) that it's confusing the compiler. Am I doing it wrong?
You could replace your <input type="hidden"... with Html.Hidden:
#Html.Hidden("AllDepts", duckbillDeptsCSV, new { id = "hiddenAllDepts" })
And update your jQuery to use # to tell it to look for that id (as is, it's looking for a <hiddenAllDepts> tag)
var deptsArray = $('#hiddenAllDepts').val();
If you are not against having some JavaScript within the MVC View, then you can just add the code directly into the JavaScript. e.g.
<script>
var deptsArray = '#CCRReporterUtils.getDuckbillDepts()';
</script>
This is just an alternative way to the other answers.
To convert this into an array you should be able to just do something like;
var deptsArray = ('#CCRReporterUtils.getDuckbillDepts()').split(',');
You can just instantiate a variable in javascript passing it the C# value and then retrieve it in jquery. Using Html.Raw and the Json.Encode method
In C# return the array instead of joining it:
public static List<string> getDuckbillDepts()
{
List<string> duckbillDptsStr = new List<string>();
for (int i = 2; i < 100; i++)
{
duckbillDptsStr.Add(i.ToString());
}
return duckbillDptsStr;
}
In your view you would have something like:
<script type="text/javascript">
var deptsArray = #Html.Raw(Json.Encode(CCRReporterUtils.getDuckbillDepts()));
</script>
And then in jquery you would just do something with it, since you would have an array of strings it seems:
<script type="text/javascript">
$.each(deptsArray, function (i,e) {
// Do something with each value
});
</script>
Try using the right # filter with jquery to get the element by id, for sample:
var deptsArray = $('#hiddenAllDepts').val(); // get a string
If you want a array, you have to use .split() method of javascript and get the value as a array, for sample:
var deptsArray = $('#hiddenAllDepts').val().split(','); //get a array of strings

Obtain selected value from dropdown in code behind

I have the follwing dropdown list and to get the selected value with javascript is easy enough.
<select id="FirstDropDown" runat="server" onchange="ValidatePrimaryDropDown();" >
<option>[Please Select Yes Or No]</option>
<option>Yes</option>
<option>No</option>
</select>
var e = document.getElementById("FirstDropDown");
var dropDownFirst = e.options[e.selectedIndex].value;
I prefer to use this dropdown as apposed to 'asp:DropDownList'.
How can I retrieve the selected value in code behind C#?
There are FindByText and FindByValue function available.
ListItem li = Select1.Items.FindByText("Three");
ListItem li = Select1.Items.FindByValue("3");
li.Selected = true;
Link to source
Is that an aspx page? If so, add a name attribute to your select and use
Requets.Form["elementName"];
in aspx.cs.
Btw: to your javascript code: is there any particular reason why are you using DOM selection instead of jquery? In jquery you wold just use
var selectedItem = $("#FirstDropDown").find(":selected").text()

How can I compare a value from C# Viewbag in Javascript?

I want to compare a boolean value from the Viewbag in javascript. So at first I tried this:
if (#Viewbag.MyBoolValue)
do_sth();
But then I have error in console like: Value False/True is not declared (not exactly).
So I tried this:
#{
string myBool = ((bool)Viewbag.MyBoolValue) ? "true" : "false";
}
and in javascript:
if (#myBool == "true")
do_sth();
But it does not work too. How can I make it work? Any help would be appreciated.
What you have should work, assuming that the value from the ViewBag is of a type which javascript can understand.
Note however, that your first example most likely did not work because boolean values are lowercase in javascript and uppercase in C#. With that in mind, try this:
var myBoolValue = #ViewBag.MyBoolValue.ToString().ToLower();
if (myBoolValue)
do_sth();
The below will create a javascript vailable with value from viewbag
<script>
var myBoolInJs = #Viewbag.MyBoolValue;
if(myBoolInJs == true)
do_sth();
</script>
var myBoolVal = #((ViewBag.MyBoolValue ?? false).ToString().ToLower());
or
var myBoolVal = '#(ViewBag.MyBoolValue)'==='#true';
or
var myBoolVal = #(Json.Encode(ViewBag.MyBoolValue ?? false));
This will work.
#{
string myBool = Viewbag.MyBoolValue.ToString().ToLower();
}
if (#myBool)
do_sth();
Insted true and false use 0 and 1 in your controller, on top of razor page
#{
var isSomething= Viewbag.MyBoolValue;
}
Later down
if (#isSomething== 0)

Categories