The issue that I am facing at getting multiple values according to dropdowns selection, it should work like this:
A user selects the first value (quantity) and then the second value which is the fruit. It should display the values selected and finally the user press the button to save all of the selected values in the database.
Here's my code:
<form id="form1" runat="server">
<div>
<asp:DropDownList runat="server" ID="lstQuota">
<asp:ListItem Text="100 units" Value="1" />
<asp:ListItem Text="50 Units" Value="2" />
<asp:ListItem Text="10 Units" Value="3" />
</asp:DropDownList>
<asp:ListBox ID="lstFruits" CssClass="DropdownList1" runat="server" SelectionMode="Multiple" AutoPostBack="true">
<asp:ListItem Text="Mango" Value="1" />
<asp:ListItem Text="Apple" Value="2" />
<asp:ListItem Text="Banana" Value="3" />
<asp:ListItem Text="Guava" Value="4" />
<asp:ListItem Text="Orange" Value="5" />
</asp:ListBox>
</div>
<asp:Button Text="Submit" runat="server" OnClick="Unnamed_Click" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('[id*=lstFruits]').multiselect({
includeSelectAllOption: true
});
$('.DropdownList1').change(function () {
alert("Handler for .change() called.");
var mySelection = $("#<%= lstQuota.ClientID %>").val();
alert(mySelection);
});
});
</script>
C# CODE:
protected void Unnamed_Click(object sender, EventArgs e)
{
string message = "";
foreach (ListItem item in lstFruits.Items)
{
if (item.Selected)
{
message += item.Text + " " + item.Value + "\\n";
}
}
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}
It should display the information selected as:
100 Units - Mango
50 Units - Orange
100 Units Apple
In the code behind, it should save every one of them as new rows.
Can somebody help me out with this?
Thanks in advance.
I found by myself, the way is very simple.
There is an asp.net control named "ListBox" which will be populated once the onselectedindexchanged method is running, but this needs to be encapsulated under an UpdatePanel control. Here is a good reference about the UpdatePanel UpdatePanel Control in ASP.Net.
Then just create a simple string variable which captures the value from the 1st dropdown and the 2nd dropdown button, then create a new ListItem ListItems and ListBox and finally itinerates the listBox items.
Related
My web form has 2 controls, drpBloodType and rbUnknownBloodType.
I need to disable the list whenever the button is checked.
I tried:
protected void rbUnknownBloodType_CheckedChanged(object sender, EventArgs e)
{
drpBloodType.Enabled = false;
}
and
<script>
$(function () {
$('#rbUnknownBloodType').change(function () {
if ($(this).is(':checked')) {
$('#drpBloodType').attr('disabled', 'disabled');
} else {
$('#drpBloodType').removeAttr('disabled');
}
});
});
</script>
but neither worked.
You need to assign change event handler to all radio-buttons in the same group as '#rbUnknownBloodType'. The change event on a radio-button does not fire when the radio-button becomes unchecked - the line
$('#drpBloodType').removeAttr('disabled');
in your code will never execute.
$(".test").change(function(){
console.log(this.value, this.checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="test" type="radio" name="test" value="1"/>
<input class="test" type="radio" name="test" value="2"/>
Hm, I looked at the picture in your question. Will a checkbox be better there?
If you have the following aspx markup you can do the following in code-behind. Note the usage of AutoPostBack="true" on the CheckBox.
<asp:DropDownList ID="BloodType" runat="server">
<asp:ListItem Text="Select..." Value=""></asp:ListItem>
<asp:ListItem Text="A+" Value="A+"></asp:ListItem>
<asp:ListItem Text="A-" Value="A-"></asp:ListItem>
<asp:ListItem Text="B+" Value="B+"></asp:ListItem>
<asp:ListItem Text="B-" Value="B-"></asp:ListItem>
<asp:ListItem Text="O+" Value="O+"></asp:ListItem>
<asp:ListItem Text="O-" Value="O-"></asp:ListItem>
<asp:ListItem Text="AB+" Value="AB+"></asp:ListItem>
<asp:ListItem Text="AB-" Value="AB-"></asp:ListItem>
</asp:DropDownList>
<asp:CheckBox ID="UnknownBloodType" OnCheckedChanged="UnknownBloodType_CheckedChanged"
runat="server" AutoPostBack="true" />
Code behind.
protected void UnknownBloodType_CheckedChanged(object sender, EventArgs e)
{
//set the dll to default
BloodType.SelectedValue = "";
//cast the sender back to a checkbox and disable the dll based on it's checked status
BloodType.Enabled = !((CheckBox)sender).Checked;
}
Or the jquery solution. This saves a PostBack, but it loses the disabled state after a PostBack. %= UnknownBloodType.ClientID %> only works on the aspx page itself. If you do not want to use it then look into ClientIdMode=Static
<script>
$(function () {
$('#<%= UnknownBloodType.ClientID %>').change(function () {
var dll = $('#<%= BloodType.ClientID %>');
if ($(this).is(':checked')) {
dll.val('');
dll.attr('disabled', 'disabled');
} else {
dll.removeAttr('disabled');
}
});
});
</script>
Does anyone know how can I make sure that they are at least one radio been click when submit in C# .net?
I have the following code:
<asp:RadioButtonList ID="billingType" runat="server" CssClass="cl_billing_method"
RepeatDirection="Horizontal" data-messages="{required:'Billing methods is required'}">
<asp:ListItem Text="Email" Value="1"></asp:ListItem>
<asp:ListItem Text="Digital Mailbox" Value="2"></asp:ListItem>
<asp:ListItem Text="Paper" Value="0"></asp:ListItem>
</asp:RadioButtonList>
How can I validate it so that when submit button is been clicked and it will do the client check and show error if there have no radio button been selected?
<script type="text/javascript" language="javascript">
function Validate_Checkbox()
{
var chks=document.getElementsByTagName('input');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert("Please select at least one checkbox..!");
return false;
}
return true;
}
</script>
and on Submit Button you have to write
write
OnClientClick="return Validate_Checkbox()"
Better option is use a asp:RequiredFieldValidator it will looks like this:
<asp:RequiredFieldValidator ErrorMessage="Billing methods is required"
ControlToValidate="billingType" runat="server" ValidationGroup="validateBill" />
Add ValidationGroup to the button:
<asp:Button Text="Submit" ID="btnSubmit" runat="server" ValidationGroup="validateBill"/>
If you are getting some error saying "UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery' ..." then add the following lines to the config:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
I have a drop down list, say ddlTest, which has Opt1, Opt2 as items. On the same page I have a radio button list, with list items as rblItem1, rblItem2 and rblItem3. Now if a user selects Opt2 in the dropdown list, then I should hide rblItem3 or for any other option selected, I should show rblItem3 in the radio button list.
Can you please let me know if it is possible and how to do that using javascript.
<table>
<tr>
<td>
<asp:RadioButtonList ID="radiobuttonlist1" runat="Server" RepeatLayout="flow" RepeatDirection="horizontal">
<asp:ListItem Text="Radio 1" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Radio 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Radio 3" Value="3"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<input type="button" value="Submit" onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')" />
</td>
</tr>
</table>
Javascript Code:-
<script language="javascript" type="text/javascript">
// Get radio button list value
function GetRadioButtonValue(id)
{
var radio = document.getElementsByName(id);
for (var j = 0; j < radio.length; j++)
{
if (radio[j].checked)
//make hide the Item
}
}
</script>
There is a CheckBoxList (selection can be multiple) and a TextBox which is not displayed by default. The requirements are:
1. When user click "Other" in CheckBoxList, the TextBox should display.
2. Since the TextBox is required when displayed, the Validator should be disabled when the TextBox is not displayed.
.aspx content page
<label for="labelSelection">Please Select:</label>
<asp:CheckBoxList ID="cblSelection" onclick="ShowOtherInfo(this)" runat="server">
<asp:ListItem Text="AAA" Value="1" />
<asp:ListItem Text="BBB" Value="2" />
<asp:ListItem Text="Other" Value="0" />
</asp:CheckBoxList>
<div id="OtherInfo" style ='display:none'>
<label for="labelOtherInfo">Enter detail if "Other" is selected: </label>
<asp:TextBox ID="OtherInfoTextBox" runat="server" />
<asp:RequiredFieldValidator ID="rfvOtherInfo" ControlToValidate="OtherInfoTextBox"
ErrorMessage="Enter other info" SetFocusOnError="true" Display="Dynamic" runat="server" />
</div>
<div>
<asp:Button ID="buttonSubmit" runat="server" Text="Submit" CausesValidation="true" OnClientClick="ShowOtherInfo()" OnClick="buttonSubmit_Click" />
</div>
Javascript placed on .master page
function ShowOtherInfo() {
var OI = document.getElementById('OtherInfo');
var CheckLists = document.getElementById('cblSelection');
var checkbox = CheckLists.getElementsByTagName("input");
if (checkbox[2].checked) {
document.getElementById('OtherInfo').style.display = "block";
ValidatorEnable(document.getElementById('rfvOtherInfo'), true);
} else {
document.getElementById('OtherInfo').style.display = "none";
ValidatorEnable(document.getElementById('rfvOtherInfo'), false);
}
}
Since I prefer using Javascript for validation, I have tried onchange/onclick event for CheckBoxList and onClientClick event for "Submit" button, but none of them works. Any help is greatly appreciated. After initial posting, I tried to replace OnSelectedIndexChanged="ShowOtherInfo" with onclick="ShowOtherInfo(this)" for CheckBoxList. And the code-behind on .cs file is:
public void DisplayOtherInfo(object sender, EventArgs e)
{
CheckBoxList cblSelection = (CheckBoxList)myFormView.FindControl("cblSelection");
RequiredFieldValidator rfvOtherInfo = (RequiredFieldValidator)myFormView.FindControl("rfvOtherInfo");
HtmlGenericControl OtherInfo = new HtmlGenericControl("OtherInfo");
for (int i = 0; i < cblSelection.Items.Count; i++)
{
if (cblSelection.Items[2].Selected == true)
{
OtherInfo.Style["display"] = "block";
rfvOtherInfo.Enabled = true;
}
else
{
OtherInfo.Style["display"] = "none";
rfvOtherInfo.Enabled = false;
}
}
}
But the TextBox still doesn't even display, not to say disable validator.
This is the Javascript Code
<script type="text/javascript">
function ShowOtherInfo() {
var OI = document.getElementById('OtherInfo');
var CheckLists = document.getElementById('cblSelection');
var checkbox = CheckLists.getElementsByTagName("input");
if (checkbox[2].checked) {
document.getElementById('OtherInfo').style.display = "block";
} else {
document.getElementById('OtherInfo').style.display = "none";
}
return true;
}
function onSubmit() {
if (document.getElementById('OtherInfoTextBox').value == "") {
if (checkbox[2].checked) {
alert('Enter other info');
return false;
}
else {
return true;
}
}
else {
return true;
}
}
</script>
and this is your .aspx content
<div>
<label for="labelSelection">Please Select:</label>
<asp:CheckBoxList ID="cblSelection" onclick="ShowOtherInfo(this)" runat="server">
<asp:ListItem Text="AAA" Value="1" />
<asp:ListItem Text="BBB" Value="2" />
<asp:ListItem Text="Other" Value="0" />
</asp:CheckBoxList>
<div id="OtherInfo" style ='display:none'>
<label for="labelOtherInfo">Enter detail if "Other" is selected: </label>
<asp:TextBox ID="OtherInfoTextBox" runat="server" />
</div>
<asp:Button ID="buttonSubmit" runat="server" Text="Submit" CausesValidation="true" OnClientClick="return onSubmit();" />
</div>
I have got the Ajax toolkit autocomplete working using the following asp.net and C# code.
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
Search our Languages: <asp:TextBox ID="txtLanguage" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txtLanguage" MinimumPrefixLength="1"
ServiceMethod="GetCompletionList" UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<br />
<asp:Button ID="btnAddSelected" runat="server" Text="Add to chosen Languages >"
onclick="btnAddSelected_Click" />
<br />
<br />
<asp:Label ID="lblSelectedLanguages" runat="server" Text=""></asp:Label>
</div>
</form>
This is my codebehind C#:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
// Create array of languages.
string[] languages = { "Afrikaans", "Albanian", "Amharic", "Arabic", "Azerbaijani", "Basque", "Belarusian", "Bengali", "Bosnian", "Bulgarian" };
// Return matching languages.
return (from l in languages where l.StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) select l).Take(count).ToArray();
}
protected void btnAddSelected_Click(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
The selected language is added to the label when the button is clicked, however I would like to remove the button and make the selected item from the autocomplete added to the label automatically, using the partial postback from the Ajax toolkit.
Can someone please advise as to how I can achieve this?
Thanks.
Handle OnClientItemSelected on the AutoCompleteExtender control to run a javascript function
All the javascript does is simply fire off the TextChanged event when the selection is made (works on both Enter and left click)
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function ItemSelected(sender, args) {
__doPostBack(sender.get_element().name, "");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Search our Languages:
<asp:TextBox ID="txtLanguage" autocomplete="off" runat="server" OnTextChanged="TextChanged" />
<asp:AutoCompleteExtender OnClientItemSelected="ItemSelected" ID="AutoCompleteExtender1"
runat="server" TargetControlID="txtLanguage" MinimumPrefixLength="1" ServiceMethod="GetCompletionList"
UseContextKey="True">
</asp:AutoCompleteExtender>
<br />
<asp:Label ID="lblSelectedLanguages" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
Code behind:
protected void TextChanged(object sender, EventArgs e)
{
lblSelectedLanguages.Text += txtLanguage.Text += ", ";
}
It looks like you just need to hook onto the on text changed event of your text box and then put your logic in code benind.Something like this
Markup
<asp:TextBox ID="txtLanguage" OnTextChanged="txtLanguage_textChanged" AutoPostback="true" />
Then in your code behind
protected void txtLanguage_textChanged(object sender, EventArgs e)
{
//use the retrieved text the way you like
lblSelectedLanguages.Text =txtLanguage.Text;
}
Hope this helps.I would also suggest that you try looking into the JQuery autocomplete widget.It has brought me sheer happiness and I surely did divorce the autocomplete extender.
Jquery Autocomplete