I have a multi-select <asp:listbox> and a button. I want to disable the button unless >= 1 item in the listbox is selected. How can I do this client-side? I can't find some sort of OnSelect callback, only OnSelectedIndexChanged which from googling seems complicated to use for this behavior, possibly impossible.
Use OnChange event, and count the selected items :
<script>function enableButton(opt) {
var selected = new Array();
var count = 0;
for (var intLoop=0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].selected) {
count++;
}
}
if (count >= 1)
{
// disable button
}
}
</script>
<select id="list" style="font-size: 11px;"
onChange="enableButton(this.options);" MULTIPLE SIZE="5">
<option value="0">Select...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
EDIT : ASP:ListBox rendered to HTML as select as the code above. So all you need to do is to add the script at the onchange attribute :
myListBox.Attributes.Add("onchange", "enableButton(this.options);");
This wouldn't be so hard to do using jQuery. Something along the lines of -
$("select#myListBox").change(function() {
if ($("select#myListBox option:selected").length >= 1)
$("input#myButton").attr("disabled", "true");
}
All hail the mighty jQuery.
OnClick or OnChange for a selectbox is the same thing as a "OnSelect".
Related
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.
I'm working on an older ASP.NET project (not MVC I don't think) and one of the features they require is to view a description of an item when they hover over that item in a dropdown list. This can be simply done with HTML using the following code and making use of title text:
<select>
<option value="1" title="Option 1 Desc">Option 1</option>
<option value="2" title="Option 2 Desc">Option 2</option>
<option value="3" title="Option 3 Desc">Option 3</option>
</select>
Ok so how do I do this using ASP.NET DropDownList control? I have the following code:
<asp:DropDownList ID="DropDownListLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownListLocation_OnSelectedIndexChanged" CssClass="editorFieldServerControl" ClientIDMode="Static"></asp:DropDownList>
And in the 'code behind' page:
private void PopulateFacilityDropdown(List<FacilityAvailableByLocation> facilities, int? selectedID)
{
DropDownListFacility.DataSource = facilities;
DropDownListFacility.DataTextField = "FacilityName";
DropDownListFacility.DataValueField = "FacilityID";
DropDownListFacility.DataBind();
DropDownListFacility.Items.Insert(0, new System.Web.UI.WebControls.ListItem("", ""));
if (selectedID.HasValue && selectedID.Value > 0)
DropDownListFacility.SelectedIndex = facilities.FindIndex(b => b.FacilityID == selectedID.Value);
else DropDownListFacility.SelectedIndex = 0;
}
}
Basically each facility in the list of facilities there has properties for an ID, Name, Description that I can get out. I just want to be able to put a title attribute on each <option> that gets rendered and put the description into it. Either that or be able to add a custom attribute like 'data-description' to each <option> tag then I can add the title into each option tag myself using a bit of jQuery which is easy enough.
I miss the days where you could just loop through a list and output the custom dropdown code manually.
Any ideas? Many thanks
You can manually add a title attribute to each list item like this. Give it a shot:
private void PopulateFacilityDropdown(List<FacilityAvailableByLocation> facilities, int? selectedID)
{
DropDownListFacility.DataSource = facilities;
DropDownListFacility.DataTextField = "FacilityName";
DropDownListFacility.DataValueField = "FacilityID";
DropDownListFacility.DataBind();
DropDownListFacility.Items.Insert(0, new System.Web.UI.WebControls.ListItem(String.Empty, String.Empty);
foreach (FacilityAvailableByLocation f in facilities)
{
DropDownListFacility.Items.FindByValue(f.FacilityID).Attributes.Add("title", f.TitleDescription);
}
if (selectedID.HasValue && selectedID.Value > 0)
DropDownListFacility.SelectedIndex = facilities.FindIndex(b => b.FacilityID == selectedID.Value);
else DropDownListFacility.SelectedIndex = 0;
}
}
f.TitleDescription would be the property you want the title to be.
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)
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.
Using the following form in a view
<% using (Ajax.BeginForm("PatientSearch", new {}, new AjaxOptions()
{
HttpMethod = "POST",
UpdateTargetId = "searchResults",
OnBegin = "BeginRequest",
OnSuccess = "SuccessRequest",
OnFailure = "FailRequest"
}))
{ %>
<%=Html.DropDownList("patientType",(SelectList)ViewData["PatientTypeList"]) %>
<%=Html.DropDownList("edCenterID",(SelectList)ViewData["EdCenterList"]) %><br />
<input type="submit">
<%} %>
Results in the following HTML
<select id="patientType" name="patientType">
<option selected="selected">Referral</option>
<option>Patient</option>
</select>
<select id="edCenterID" name="edCenterID">
<option value="2">Barren River District Health Department</option>
<option value="3">Madison County Health Department</option>
</select>
and I attempt to catch the values with the code in the my controller
public ActionResult PatientSearch(string patientType, int edCenterID) {
//do something with values
}
patientType is always passed as ""; however, edCenterID is posted and received just fine.
If I change this from an Ajax.BeginForm to an HTML.BeginForm, everything works perfectly.
Is the problem in my DropDownList, my controller, both?
ADDED FROM COMMENTS
#Eoin pointed out to me that my select is rendering without a value and that is probably the problem. That brings up two questions:
1. Why does it work with the a standard post, but not an Ajax post.
2. How do I get my dropdownlist to contain a value with the list is a simple string only list (no key). I am posting the code used to generate my SelectList below
ViewData["PatientTypeList"]=new SelectList(new List<string>()
{ "Referral", "Patient"});
Does the patientType List have a .Value
By the looks of things, theres no value being rendered for the PatientType DDL <option>'s so essentially every option has a value="" so it is actually post back the correct value.
The problem is with what's being rendered in the first place.
edit
Try
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("referral", "referral");
d.Add("patient", "patient");
ViewData["PatientTypeList"]=new SelectList(d, "Key", "Value");
Is there no solution to this? Seems like something is broken in the Ajax form submission.
Here is a good fix, write your methods as normal, then run:
function addDropDownValues() {
$("select option").each(function(i) {
if ($(this).text() == "Red") { $(this).attr('value', "Red"); }
else if ($(this).text() == "Amber") { $(this).attr('value', "Amber"); }
else if ($(this).text() == "Green") { $(this).attr('value', "Green"); }
else if ($(this).text() == "Complete") { $(this).attr('value', "Complete"); }
});
}
Where "red", "amber", etc... are the values you want to be passed through
This will append a value to each dropdown, producing:
<select name="status1" id="status1"><option value="Red">Red</option>
<option value="Amber">Amber</option>
<option selected="selected" value="Green">Green</option>
<option value="Complete">Complete</option>
</select>
This will work with both Firefox AND Internet Explorer. Internet Explorer requires the value item, firefox does not.