i have a drop downlist. When Selected Index changes I wanted to handle it in javascript. So, as starting step , I tried to print the value of list item text in a textbox through javascript. But could not accomplish it successfully. Here is the dropdownlist:
<asp:DropDownList Width="300px" ID="PlaceHoldersDropDownList" runat="server"
AppendDataBoundItems="True" TabIndex="3" AutoPostBack="True"
OnSelectedIndexChanged = "PlaceHoldersDropDownList_SelectedIndexChanged" >
<asp:ListItem Value="">Select</asp:ListItem>
<asp:ListItem Value="ContactName">[Contact Name]</asp:ListItem>
<asp:ListItem Value="ProductName">[Product Name]</asp:ListItem>
<asp:ListItem Value="ProductShortName">[Product Short Name]</asp:ListItem>
<asp:ListItem Value="CurrentTime">[Current Time]</asp:ListItem>
<asp:ListItem Value="EventStartTime">[Event Start Time]</asp:ListItem>
<asp:ListItem Value="EventStopTime">[Event Stop Time]</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="tb" runat="server"></asp:TextBox>
Here is the C# code
protected void PlaceHoldersDropDownList_SelectedIndexChanged(object sender,
EventArgs e)
{
var text = PlaceHoldersDropDownList.SelectedItem.Text;
string x = text;
PlaceHoldersDropDownList.Attributes.Add("onchange", "javscript:PasteTextInEditor
('"+text+"')");
}
Here is the javascript
function PasteTextInEditor(text) {
var x = document.getElementById("<%= tb.ClientID %>");
x.value = text; }
Can you please let me know the mistake I've been doing?
first you have to set AutoPostBack to false to handle it in client side(javascript) and you don't need to add onchange event programatically, you can just write it in the <asp:DrobDownList> something like that
<asp:DropDownList Width="300px" ID="PlaceHoldersDropDownList" runat="server"
AppendDataBoundItems="True" TabIndex="3" AutoPostBack="false"
onchange="PasteTextInEditor()">
and the PasteTextInEditor method will become
function PasteTextInEditor() {
var text = $("#<%= PlaceHoldersDropDownList.ClientID %> option:selected").text();
$("#<%= tb.ClientID %>").val(text);
}
note I am using jquery syntax
Using jQuery you can make the following:
1- turn off AutoPostBack and don't handle the OnSelectedIndexChanged event:
<asp:DropDownList Width="300px" ID="PlaceHoldersDropDownList" runat="server" AppendDataBoundItems="True" TabIndex="3" >
2- add a reference to jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
3- add a "startup" script to hook the onchanged event for the dropdown list, read the javascripts comments for more details.
<script type="text/javascript">
$(function () {
var ddl = $("#<%= PlaceHoldersDropDownList.ClientID %>");
var txt = $("#<%= tb.ClientID %>");
// hook the change event for the drop down list
$(ddl).change(function (e) {
var selectedValue = $(ddl).val();
// set the selectedValue into the textBox
$(txt).val(selectedValue);
});
});
</script>
Related
I have a dropdownlist in a table with a blank item in it, I want a error message showed in a label if a button is pressed while that blank item is selected in the dropdrownlist
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownListParedesinteriores_ItemChanged">
<asp:ListItem Text="" Value="-1"></asp:ListItem>
<asp:ListItem Value='5'>Excellent</asp:ListItem>
<asp:ListItem Value="4">Very good</asp:ListItem>
<asp:ListItem Value="3">Good</asp:ListItem>
<asp:ListItem Value="2">Bad</asp:ListItem>
<asp:ListItem Value="1">Very bad</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Label9" runat="server" Text=""></asp:Label>
This is my Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function ()
{
$("#Button1").click(function ()
{
var a = $("#<%= DropDownList1.ClientID %>");
if (a.val() === "-1")
{
document.getElementById("Label9").innerHTML = "<b>Please select an option</b>";
document.getElementById("Label9").style.color = "red";
}
else
{
document.getElementById("Label9").innerHTML = "<b>Comfirmed</b>";
document.getElementById("Label9").style.color = "green";
}
})
})
</script>
First of all this button is a server side button you have to disable postaback to make it work on client side by using onClientClick="return false" .Secondly in order to use Button1 as id($("#Button1")) you need to change ClientIDMode to static same goes for the label
<asp:Button ID="Button1" runat="server" Text="Button" onClientClick="return false" ClientIDMode="Static" />
<asp:Label ID="Label9" runat="server" Text="" ClientIDMode="Static"></asp:Label>
if you dont want to use static client id you have to replace
$("#Button1") with $("#<%= Button1.ClientID %>")
document.getElementById("Label9") with document.getElementById("<%= Label9.ClientID %>")
Your button 1 selector "$("#Button1).click" click event does not consider the client ID like your dropdown list does. That may be causing the issue if jquery finds nothing for button 1 and the click event never gets triggered.
A possible fix is to change the selector to the same as you do in the line where you use jquery to get the dropdown list.
I'm working with two dropdown boxes after a user selects the first required drop down based on what they choose the other drop down will load the final list. I have that working but I don't want the page to reload on once the first dropdown option is picked is there a way around this below is my test code
Behind code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add(new ListItem("3 Days", "3 Days"));
DropDownList1.Items.Add(new ListItem("4 Days", "4 Days"));
DropDownList1.Items.Add(new ListItem("5 Days", "5 Days"));
DropDownList1.Items.Add(new ListItem("7 Days", "7 Days"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList2.Items.Clear();
DropDownList3.Items.AddRange(GetListItems(DropDownList1.SelectedValue));
}
private ListItem[] GetListItems(string value)
{
var items = new List
<ListItem>
();
if (value == "3 Days")
{
DropDownList2.Items.Add(new ListItem("1", "1"));
}
if (value == "4 Days")
{
DropDownList2.Items.Add(new ListItem("2", "2"));
}
if (value == "5 Days")
{
DropDownList2.Items.Add(new ListItem("3", "3"));
}
if (value == "7 Days")
{
DropDownList2.Items.Add(new ListItem("4", "4"));
}
return items.ToArray();
}
<div class="1">
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="1">
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
</asp:DropDownList>
</div>
(FROM MSDN)
The ScriptManager control and the UpdatePanel control. These controls remove the requirement to refresh the whole page with each postback, which improves the user experience. By default, a postback control (such as a button) inside an UpdatePanel control causes a partial-page update. By default, a button or other control outside an UpdatePanel control causes the whole page to be refreshed,
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<fieldset>
<div class="1">
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="1">
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
</asp:DropDownList>
</div>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
You will need to use JQuery with an AJAX call in order to avoid postback.
First, you'll need to remove the auto postback and event handler from your drop down list:
<div class="1">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="1">
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
</asp:DropDownList>
</div>
Then, use JQuery to make a call which sends the selected option and returns the options for the second drop down list.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#<%=DropDownList1.ClientID%>').change(function() {
var selectedOption = $(this).val();
console.log(selectedOption); //verify you have the value
$.ajax({
type: "POST",
url: "codebehind.aspx/GetListItems",
data: JSON.stringify({ value: selectionOption }),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).success(function (data) {
console.log(data); //verify the format of the return data
obj = JSON.parse(data.d);
console.log(obj); //verify obj structure
//adding options to drop down list will look something like...
$.each(data, function (index, optiondata) {
$("#DropDownList2").append("<option value='" + optiondata.Value + "'>" + optiondata.Text + "</option>");
});
});
});
});
</script>
And you'll need to change your function in code behind to:
[WebMethod]
public static List<ListItem> GetListItems(string value)
{
//..do stuff
return JsonConvert.SerializeObject(items);
}
The act of including ClientIDMode="Static" to the DDL was the culprit in my case. I know this isn't the case with OP's markup, but a subset of users reading this will be in the same boat I was. Just passing it along.
I generate a report according to selection of company and their customer. I use one dropdown for company and according to company the customer is displayed. However, I want to make it possible to select multiple customers, and when the user clicks on the button to the view report, I want to update the query string with that selection. If the selection of customer is three, I want to pass their customer code using query string. In sort querystring is send according to the selection of customer.
Please help me.
Thanks and regards.
Mitesh
In your selection page (aspx):
...
<script type="text/javascript">
function submitSelection() {
var customerList = document.getElementById('<%= lbCustomers.ClientID %>');
var companyList = document.getElementById('<%= lbCompany.ClientID %>');
var selectedCustomerQuery = [];
for (var i = 0; i < customerList.options.length; i++) {
if (customerList.options[i].selected)
selectedCustomerQuery.push('customer_id=' + customerList.options[i].value);
}
location.href = 'Report.aspx?company_id=' + companyList.value + '&' + selectedCustomerQuery.join('&');
}
</script>
<asp:DropDownList ID="lbCompany" runat="server" SelectionMode="Single" >
<asp:ListItem Value="1">Company 1</asp:ListItem>
<asp:ListItem Value="2">Company 2</asp:ListItem>
</asp:DropDownList><br />
<asp:ListBox ID="lbCustomers" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="John" Value="1"></asp:ListItem>
<asp:ListItem Text="Paul" Value="2"></asp:ListItem>
<asp:ListItem Text="Peter" Value="3"></asp:ListItem>
</asp:ListBox><br />
<input id="Button1" type="button" value="View Report" onclick="submitSelection()" />
...
Then in your Report.aspx.cs:
...
protected void Page_Load(object sender, EventArgs e)
{
var selectedCompany = Request.QueryString["company_id"];
//get passed selected customers, will be stored in an array
var selectedCustomers = Request.QueryString.GetValues("customer_id");
Response.Write(string.Format("Company ID: {0}, Customers: {1}", selectedCompany.ToString(), string.Join(",", selectedCustomers)));
}
...
This illustrates an example without posting back to the page. If you need to post back to handle other logic in your code behind, you'll have to change the <input> button to an ASP.NET button control and handle its OnClick event.
I have done a code to disable a control when user clicks on a control. On my form i am having a TextBox and a DropDown. When user clicks on a TextBox i will disable the DropDown like that when click on DropDown i will disable the TextBox which works fine.
But when the user clicks on Disabled control i would like to enable that control. Means if i click on TextBox which was disabled i would like to Enable it like that for dropdown too..
My sample Script is as follows
<script type="text/javascript">
function toggleDropDownList1()
{
var d=document.getElementById("<%= DropDownList4.ClientID %>");
if(d.disabled)
{
d.disabled=false;
}
else
{
document.getElementById("<%= TextBox1.ClientID %>").disabled = true;
}
}
function toggleDropDownList2()
{
document.getElementById("<%= DropDownList4.ClientID %>").disabled = true;
}
</script>
Design
<asp:TextBox ID="TextBox1" runat="server" onclick="toggleDropDownList2();"></asp:TextBox>
<asp:DropDownList ID="DropDownList4" runat="server" onclick="toggleDropDownList1();">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="One" Value="1"></asp:ListItem>
</asp:DropDownList>
Apparently Firefox, and perhaps other browsers, disable DOM events on form fields that are disabled, and any event that starts at the disabled form field is completely canceled and does not propagate up the DOM tree.
So, if you want to achieve something like that, you will probably have to do it with a workaround.
Instead of actually disabling the field try to style the fields to look as if they are disabled, that way you can still capture the click event.
The idea is to place a div in front of dropdown list, and this div accept the onclick event.
The issue here is that the div can not place so easy in front of dropdown list. To place it you need to do that dynamically and use the absolut position.
I make here a small code, and test it and working. I have left the background color RED on div to see where it is. Some details I left it to you, eg to find the width and height of your control list, I place the onclick, you can place back the double click, And just remove the red background.
<script type="text/javascript">
function toggleDropDownList1()
{
var MyDiv = document.getElementById("DivForClick");
MyDiv.style.display = "none";
var d=document.getElementById("<%= DropDownList4.ClientID %>");
if(d.disabled)
{
d.disabled=false;
}
else
{
document.getElementById("<%= TextBox1.ClientID %>").disabled = true;
}
}
function toggleDropDownList2()
{
document.getElementById("<%= DropDownList4.ClientID %>").disabled = true;
var MyDdl = document.getElementById("<%= DropDownList4.ClientID %>");
var MyDiv = document.getElementById("DivForClick");
MyDiv.style.display = "block";
MyDiv.style.left = MyDdl.style.left;
MyDiv.style.top = MyDdl.style.top;
// need to find the height/width
// MyDiv.style.height = MyDdl.style.height;
// MyDiv.style.width = MyDdl.style.width;
}
</script>
and the asp code.
<asp:TextBox ID="TextBox1" runat="server" onclick="toggleDropDownList2();"></asp:TextBox>
<br /><br />
<div id="DivForClick" onclick="toggleDropDownList1();" style="z-index:999;position:absolute;left:0;top:0;height:20px;width:40px;background-color:Red;display:none;">
</div>
<asp:DropDownList ID="DropDownList4" runat="server" onclick="toggleDropDownList1();" style="z-index:2;">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="Two" Value="2"></asp:ListItem>
</asp:DropDownList>
Do you mean
function toggleIt() {
var d=document.getElementById("<%= DropDownList4.ClientID %>");
var t =document.getElementById("<%= TextBox1.ClientID %>");
d.disabled=!d.disabled
t.disabled=!t.disabled
}
<asp:TextBox ID="TextBox1" runat="server" onclick="toggleIt();"></asp:TextBox>
<asp:DropDownList ID="DropDownList4" runat="server" disabled="disabled" onclick="toggleIt();">
<asp:ListItem Text="One" Value="1"></asp:ListItem>
<asp:ListItem Text="One" Value="1"></asp:ListItem>
</asp:DropDownList>
I am having 2 dropdown lists on my page if i select an item the same selected item should be displayed in another drop down list. Can any one give me a javascript for this i need Javascript not Jquery
here is a very simple implementation of what you are describing:
given the html:
<select id="select1">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<select id="select2">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
and this javascript:
document.getElementById('select1').onchange = function(e) {
var index = this.selectedIndex;
document.getElementById('select2').options[index].selected = true;
}
you can achieve what you want. note the indexes should be exactly the same in both select boxes (as in the options should be in the same order)
You can attach an onchange event on your dropdown.
Then whenever your selected Index changes, it will fire and call the supplied update method.
For example:
HTML
<asp:DropDownList id="FirstDropdown" onChange="javascript:update();" ...>
JavaScript
<script type="text/javascript">
function update ( ) {
document.getElementById('<%= SecondDropdown.ClientID %>').value =
document.getElementById('<%= FirstDropdown.ClientID %>' ).value;
}
Try this
<asp:DropDownList ID="ddl1" runat="server">
<asp:ListItem Value="1"></asp:ListItem>
<asp:ListItem Value="2"></asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem Value="4"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<script type="text/javascript">
function MyApp(sender){
var lbMatch = false;
var loDDL2 = document.getElementById('DropDownList1');
for(var i=0; i< loDDL2.length-1; i++){
lbMatch = sender.value==loDDL2.options[i].value;
lsSelected = lbMatch ? "<=SELECTED" : "";
if(lbMatch)
loDDL2.selectedIndex = sender.selectedIndex;
}
}
</script>
In page load event add this
ddl1.Attributes.Add("OnChange", "MyApp(this)");