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.
Related
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.
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.
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
I'm having a bit of trouble here, hoping someone can help:
I am dynamically populating an html select element in a razor script and onChange I am hoping to get this posted value.
It is posting back as the page is refreshing but I don't seem to be getting the value of the select; The reason I know is that I am passing a category and filtering on it. This filtering works when I change the querystring in the URL manually and post it.
Razor Script:
#using umbraco.MacroEngines
#inherits DynamicNodeContext
#{
dynamic rootNode = #Model.NodeById(1066);
DynamicNodeList list = rootNode.Descendants();
List<dynamic> categories = new List<dynamic>(list.Cast<dynamic>());
List<string> alias = new List<string> { "GeneralPage" };
var filtered = categories.Where(n => alias.Contains(n.NodeTypeAlias));
}
<form method="post" action="">
<select id="selectCategory" name="selectCategory" onchange="this.form.submit(); alertMe(selectCategory)">
#foreach (var node in filtered)
{
<option value="#node.Name">#node.Name</option>
}
</select>
</form>
<script type="text/javascript">
function alertMe(selectCategory) {
alert(selectCategory)
}
</script>
You'll notice I have a function to alert the selected value but this is coming back as [object HTMLSelectElement]
I can post more code if needed to show what's happening on the server, but as I said the filtering DOES work, however I am trying capture the value in the following way:
string category = Request["selectCategory"];
if (category != null)
{
Any help much appreciated.
Thanks
Try:
ViewContext.RouteData.Values["selectCategory"]
As for the javascript, you are passing in the dom reference to the select list, not the selected item. If you want to see the value of it, you need to use
alert(selectCategory.value)
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)