Select item in CascadingDropDown via JavaScript & invoke update - asp.net

In code-behind I can do this to select something:
// Select item in first DropDownList
myCascadingDropDown_1.SelectedValue = itemValue_1+":::"+itemText_1;
// Select item in second DropDownList
myCascadingDropDown_2.SelectedValue = itemValue_2+":::"+itemText_2;
How can I do this in JavaScript?
(I'm aware, that I could search the list and set the selectedIndex property for each dropdown, but I have many items and i'm very lazy.)
EDIT:
npups answer works: I can select my desired item in the first dropdownlist. The problem is however, that new values based on that selected item (it is a CascadingDropDown, remember?) don't show in the second dropdown so I can't select anything there. I would need to somehow invoke the update method of the second dropdown manually: any suggestions?

I was able to solve this:
1) With npups suggestion I was able to set "myCascadingDropDown_1" to my desired value.
2) Using the
myCascadingDropDown_2.CascadingDropDownBehavior._onParentChange(null,
null);
method I was able to force the second dropdown to repopulate based on the new selected value of "myCascadingDropDown_1".
3) I wrote a timer to check periodically if the second dropdown has finished repopulation and set the desired value if it has (again using npups answer)..

Check this out:
<select id="foo">
<option value="bar">bar</option>
<option value="baz">baz</option>
<option value="bork">bork</option>
</select>
<script type="text/javascript">
var selectElem = document.getElementById('foo');
selectElem.value = 'baz';
</script>
Setting the value of the select element fixes that.
Firefox gets it right even if you just use the tags' content as values (instead of specifying a value in the option's value attribute). Not sure about other browsers.
EDIT, more stuff:
So there is some other select (or equivalent) that is updated by some harmonizing function when the first select changes?
Here, i have it in the first select's onchange. When the selected element is set with this "value-setting" technique, the onchange isn't triggered. Though, one can call the harmonizing function manually when you change the first select. I show two different ways (both in comments) below.
<select id="foo" onchange="harmonize();">
<option value="bar">bar</option>
<option value="baz">baz</option>
<option>bork</option>
</select>
<select id="foo2">
<option value="0">This</option>
<option value="1">That</option>
</select>
<script type="text/javascript">
var select0 = document.getElementById('foo');
var select1 = document.getElementById('foo2');
select0.value = 'baz';
// alternative 1: call harmonize();
// alternative 2: call select0.onchange();
function harmonize() {
if (select0.value==='baz') {
select1.value = '1';
}
else {
select1.value = '0';
}
}
</script>
I didn't bother to hide global variables etc. here, but of course that is a good idea.

you can also use myCascadingDropDown_2.set_SelectedValue(resultval, resultVal) instead of timer (item3)

Related

Default show Mutilple selected options in Select control using Bootstrap Select

I have created a multi selection select control using Bootstrap select.
By default I need to show dynamically selected items. When I make selected in option ALL selection (<option value="All" selected >All</option>) by default it shows selected in UI. But when do for one option selected its not shows the tick.
Demo is here: https://jsfiddle.net/sharmilashree/L7wzv5k0/10/
(i.e)
<option value="All" selected >All</option>
<option value="EC" selected>EC (Early Childhood)</option>
I suspect the issue is as you commented, here:
$('#myselect').selectpicker().change(function () { toggleSelectAll($(this)); }).trigger('change');
If you drop the trigger('change') it works as expected:
https://jsfiddle.net/Twisty/3pfq5u41/
I guess my question is why trigger a change event? Really, I would think that you only want to execute toggleSelectAll() when the "All" value is selected.
Perhaps something like: https://jsfiddle.net/Twisty/3pfq5u41/2/
Hope that helps.
Wrong event selection:
Replace
$('#myselect').selectpicker().change(function () { toggleSelectAll($(this)); }).trigger('change');
to
$('#myselect').selectpicker().change(function () { toggleSelectAll($(this)); }).trigger('select');
Check for "undefined" as well.
if (control.data('allOptionIsSelected') != allOptionIsSelected && typeof(control.data('allOptionIsSelected')) != "undefined")
{
And you are done!
Happy Coding.

How to detect the CTRL-Key state in the onChange() handler for an HTML select element

I want to handle the change event of a select element depending on whether the CTRL-Key is pressed, but it does not work.
Here's what I have: An ASP.NET WebForms ListBox control (that renders to a select element with options like so (slightly simplified):
<select name="ctl00$ContentPlaceHolder1$MultiselectDropDownStatus" id="ctl00_ContentPlaceHolder1_MultiselectDropDownStatus" size="7" multiple="multiple">
<option selected="selected" value="">All</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
Now, when the user selects one option, I want to do something depending on the state of the CTRL-Key. I will handle the change event like so:
script.AppendLine(#" $(""#" + ClientID + #""").change(function (e) {");
//....
Inside the script method I want to check the key state
script.AppendLine(#" if (e.ctrlKey) {");
script.AppendLine(#" alert(""ctr key was pressed during the click"")");
script.AppendLine(#" }");
//...
However, this way, the e.crtlKey is always undefined.
But, when I handle the click event of the listbox control directly (not via the change event), like so:
script.AppendLine(#" $(""#" + ClientID + #""").click(function (e) {");
script.AppendLine(#" if (e.ctrlKey) {");
script.AppendLine(#" alert(""ctr key was pressed during the click"")");
script.AppendLine(#" }");
Here, the e.crtlKey gives me the correct value.
Why can I not get the CTRL-Key state correctly in the change handler?
I am working with IE 11 right now, but it should also work on other major browsers.
Update: Originally I wanted to handle the event of having multiple selections using the CTRL key state. I realised that this was wrong and now I have solved this by explicitly counting the selected options. However, this question remains valid, and thus I will leave it here: How to detect the key state in the changed handler?
You cannot. The change event does not define ctrlKey, as you have noted.
change is an event which uses the base event interface, which does not handle ctrlKey.
To have ctrlKey defined, you need to use a TouchEvent, MouseEvent, or KeyboardEvent.
In your example, click leads to change being triggered. click, being a MouseEvent, has the ctrlKey information, but change does not.
If desired you could have a global variable updated in the click event which would indicate if ctrlKey was pressed and then use that within the change event.

How to get last selectedindex

I need to get the last selected value from a dropdown control. But I get wrong information.
I need this kind of control to allow users to select every option they want. But I've to validate every option they select after getting the selectedvalue.
I've deployed an ASP.NET dropdown control in a webform. It's databinded in server side, and the resulting hmtl is the following:
<select name="ddl" id="ddl" multiple="multiple" data-native-menu="false">
<option value=""></option>
<option value="1">1800346</option>
<option value="2">1800353</option>
<option value="3">1800358</option>
<option value="4">1800509</option>
<option value="5">1800514</option>
</select>
And this is my jQuery code: It alerts the selectedIndex and the selected text.
$("#ddl").on("change", function () {
alert($("#ddl")[0].selectedIndex);
alert($("#ddl option:selected").text());
});
With alert($("#ddl")[0].selectedIndex) I get the first selected index. For example, if you click on the first checkbox, you'll get "1" the first time. After that, if you click on the third checkbox you'll get "1" again (instead of "3"). Because the first option is selected.
I also tried with alert($("#ddl option:selected").text()) but I get everything.
Is there any way to get only the last selected value? I'm only able to get the first selected index.
You can find my code also here: http://jsfiddle.net/bDvkQ/342/
Any help will be very welcome,
Regards,
Check for this code
$("#ddl").on("change", function () {
var lastText = "";
var last = 0;
$("#ddl option:selected").each(function () {
lastText = this.text;
last = this.value;
});
alert(lastText);
alert(last);
});
and you can find from this link to http://jsfiddle.net/bDvkQ/344/
I think it wasn't clear for you.
When you click on the ddl, it will choose the selected value. Just return it.
Do something like this:
$("#ddl").on("change", function () {
alert($("#ddl").val());
alert($("#ddl option:selected").text());
});
It works well for me.
Hope this helped.
Here is how we can select the last selected value (and first one),
$("#ddl").on("change", function () {
var selValues = $("#ddl").val();
alert(selValues[0]);
alert(selValues[selValues.length - 1]);
});
However, if user starts selecting values in the reverse direction (from bottom), you will not get the last selected/clicked value but you will always get the selected value that comes last in the dropdown.
I would suggest to create another function/handler that gets all the selected values and validates them one by one rather than doing validation on every single click/selection of this multi select control.

using Form to retrieve dropdownlist value

I have a dropdownlist which has both text and value .When I try to retrieve the data from Page.Request.Form["ID1"] I am getting back the value and not the text ..Is there a way I can get both of these .
<select id="ID1">
<option Value="1">
Test
</option>
<Option Value="2">
Test2
</Option>
</select>
Thanks
Changing my answer based upon the criteria
I'm kinda writing this off the cuff so I apologize if there are syntax errors - hopefully you get the general idea
Since you have control over the client side.. you could pass over the form text / value like this
<select name="mySelect">
<option value="myName1:myValue1">myName1</option>
<option value="myName2:myValue2">myName2</option>
<option value="myName3:myValue3">myName3</option>
</select>
Then... server side you could do something like this...
var mySelect = Page.Request.Form["mySelect"].ToString();
var myText = mySelect.Split(":".ToCharArray()).First();
var myValue = mySelect.Split(":".ToCharArray()).Last();
Only the value is post back on the form.
Using the value you can find the text in the list, that you need to have save/keep, either on viewstate, either keep it on Drop Down list box. If you can not use them, then one other solution is to keep all your data that you wish to get on the value, and split them later.
There is a way this can be done.
During initialisation of the webcontrol, in the code behind, store the dropdownlist in a member variable so you keep a reference to it, and populate it's Items collection during initialisation.
Then get the posted back value (key) using Request.Form(ddl.UniqueID) also during initialisation.
Use the key to look up the item in the drop down list eg.
dim selectedValue as string = Request.Form(ddl.UniqueID)
dim theItem as ListItem = Nothing
If Not IsNothing(ddl.Items.FindByValue(selectedValue)) Then
theItem = ddl.Items.FindByValue(selectedValue)
dim strText as string = theItem.Text
End If

make drop down list item unselectable

I have a dropdownlist which has several options for generating reports. Based on the type of account the user has certain options which should be visible but not selectable (as an incentive for them to upgrade).
I was wondering if anyone knew of a way to accomplish this.
The permissions are already in place i just need assistance with making certain items unselectable.
Any help would be much appreciated.
Not sure if you are still looking for an answer for this?
Mark Redman's answer is great if you can define the select list in the aspx page, however if you bind the drop down list dynamically obviously you cannot.
I had success using the following to achieve the result you are after (not sure on full browser support but works in newer versions of IE)
foreach ( ListItem item in dropdownlist.Items )
{
if ( [item should be disabled condition] )
{
item.Attributes.Add( "disabled", "disabled" );
}
}
This will render your disabled elements greyed out.
You can disable an <option> tag in an html <select>
See: http://www.htmlref.com/reference/appa/tag_option.htm
in asp.net:
<asp:DropDownList ID="MyDropDownList" runat="server">
<asp:ListItem Text="Standard Report" Value="SR"></asp:ListItem>
<asp:ListItem Text="Enterprise Report" Value="ER" disabled="disabled"></asp:ListItem>
</asp:DropDownList>
You can use a required field validator and set the initial value property to the value of the item in the drop down list you do not want selectable.
<asp:RequiredFieldValidator ID="RequiredFieldValidator" runat="server"
ErrorMessage="" ControlToValidate="DropDown" InitialValue="Unselectable Item"></asp:RequiredFieldValidator>
You could try this
myDropDownList.Items.FindByValue("ReportValue").Attributes.Add("disabled", "disabled");
I had this same problem and tried to use the first answer posted, but it didn't work for me. I then changed the first post to:
foreach ( ListItem item in dropdownlist.Items )
{
if ( [item should be disabled contdition] )
{
item.Enabled = false;
}
}
and it worked for me.
Adam Fox is absolutely correct with this snippet:
foreach ( ListItem item in dropdownlist.Items )
{
if ( [item should be disabled condition] )
{
item.Attributes.Add( "disabled", "disabled" );
}
}
The only caveat is that it needs to be called in the OnDataBound event, and not the OnDataBinding event (this is too early in the lifecycle).
You could do this client-side with a handler that is triggered when an item is selected. Then unselect the item and/or display an error message.
If this is HTML control, then its very easy to make it UNselecteable. just use the "optgroup" HTML element. e.g.
<select>
<optgroup label="Hardware"></optgroup>
<option id="1">mouse</option>
<option id="2">keyboard</option>
<option id="3">monitor</option>
<optgroup label="Software"></optgroup>
<option id="Option1">windows XP</option>
<option id="Option2">MS Office</option>
<option id="Option3">VStudio</option>
</select>
(NOTE : this works in both IE/firefox)
Thanks
Sushil Jinder
Try this
myDropDownList.Items.FindByValue("ReportValue").Enabled = false;
This will disable the item from the list by basically not showing it in the list.
"ReportValue" = the value of the item to be disabled.

Resources