Populate textbox from checkbox list using ASP.NET and AJAX - c#

I have a textbox control and a checkbox list control on my page.
I am first populating my checkbox list with a list of employee objects in the code-behind. An employee has an id and a name. Both are displayed in the checkbox list like so:
Jim (1)
Alex (2)
Gary (3)
When a user checks one of the boxes, the employee's name needs to be populated in the textbox. So if Jim is selected, the textbox value is "Jim". It also needs to support multiple values, so if Jim and Gary are selected, the textbox value is "Jim, Gary".
Also, if a user enters a valid value in the textbox, the correct employee should be checked. This needs to support names and id's. So if I enter "1,Alex" in the textbox and then click outside the textbox, Jim and Alex should be selected.
I'm using ASP.NET and I need to do this using AJAX, but I have no experience with using jQuery and AJAX. Could someone show me a simple example of how to do this?

Here is something I through together that might help get you started. It's not tested and not complete but I don't have time to do it all right now, so thought this might help. There definitely needs to be a lot more checks and paring done that I left out for you to implement.
$(function() {
// gets all checkbox items by a common class you will put on all of them
$('.checkboxlistclass').click(function(e) {
var txt = $(this).text();
var employeeName = txt; // change this to parse out the name part and remove the id
var currentTxtVal = $('#textboxid').val();
var newVal = currentTxtVal + ',' + employeeName; // check if you need the comma or not
$('#textboxid').val(newVal);
});
// textboxid is the id of the textbox
$('#textboxid').change(function(e) {
var textboxVal = $(this).val();
// split on the comma and get an array of items
// this is dummy data
var items = [];
items.push('Jim');
items.push(2);
// go through all the items and check if it's a number or not
// if it's a number do a selection based on the id in parenthesis
// if not then check first part for name match
for (var i=0; i < items.length; i++) {
if (isNaN(parseInt(items[i])) {
$(".checkboxlistclass:contains('" + items[i] + " ('").attr('checked', true);
}
else {
$(".checkboxlistclass:contains(' (" + items[i] + ")'").attr('checked', true);
}
}
});
});

Related

How to detect if a check box is selected using MVC3 Razor

As I am new to MVC framework, I have been spending a couple of hours to generate a check box list in a View file. Finally, I could figure it out well. Here is my code:
#foreach (var item in Model.GetRoleNames)
{
#Html.CheckBox("chk_" + item.Value, new { value = item.Value })#item.Text<br />
}
But, I need to detect which of them is selected and if all the ckeckboxes are left unchecked, then preventing some operations.
Question: How can I get the checked items when I am within a controller action?
As the others said, you should use a Boolean value as the second parameter to CheckBox to indicate the checked status. A bit of string manipulation should help you get the ids of the selected check boxes..
First lets change the way the checkbox helper is used
<div id='myCheckboxDiv'>
#foreach (var item in Model.GetRoleNames)
{
#Html.CheckBox("chk_" + item.Value, false)#item.Text<br />
}
</div>
As you can see, I have set the second parameter to false and wrapped the mix in a div
And, when you want to get the ‘values’ associated with the selected checkboxes
var values = $(‘# myCheckboxDiv’).find('input:checkbox:checked').map(function () {
// get the name ..
var nameOfSelectedItem = this.attr('name');
// skip the ‘chk_’ part and give me the rest
return nameOfSelectedItem.substr(4);
}).get();
I am assuming item.Value to be a number. If its is not, please remove the white spaces using C#

Submit both value and text of a dropdownlist in a form

I use MVC HTML Helper to render a Html DropDownList:
#Html.DropDownListFor(m => m.ParentId, menuSelectList)
I put this DropDownList in an HTML form. When press the button Submit in this form, a HTML Form Data will be created and sent in POST request. This data will contain key name ParentId with key value is DropDownList's selected value. How I can include DropDownList's selected text in this data with key name is ParentName.
1) You could use an hidden "ParentName" input, and populate it with the selected text (javascript / jQuery) when an change event is fired on your combo (DropDownList).
2) Just get the value from the key after submit (in the POST action), it should be possible (db query, for example).
3) Build your selectList in a way that the key contains key AND value (separated by a ~ for example, and split the "key~value" in the POST action)
I would personnaly go for second solution, but...
You can do it with JavaScript, as the browser is not sending the selected text anywhere.
One trick is placing such code in the very bottom of your .aspx page: (before the </body>)
var arrDDLs = document.getElementsByTagName("select");
for (var i = 0; i < arrDDLs.length; i++) {
var oDDL = arrDDLs[i];
if (!oDDL.name || oDDL.name.length === 0)
continue;
var inputName = oDDL.name + "_text";
var input = document.createElement("input");
input.type = "hidden";
input.name = inputName;
input.id = inputName;
oDDL.form.appendChild(input);
oDDL.onchange = function () {
var index = this.selectedIndex;
var text = (index >= 0) ? this.options[index].text : "";
var inputName = this.name + "_text";
var input = document.getElementById(inputName);
input.value = text;
};
//populate initial text:
oDDL.onchange();
}
This code is essentially implementing the first idea in this other answer and to take the selected text you just have to read Request value of the select key plus "_text" e.g.:
string selectedText = Request.Form[m.ParentId + "_text"];
Live test case. (JavaScript side only)

set combobox text from textbox

I have user submitted content that is loaded into c# winform in our office for processing before officially added to database. The user can submit a 'Referrer' as two text fields-first and last name. In the office I want to have a combobox will all existing referrers loaded in, then the first couple letters of the name to advance the combobox down to the area it needs to be at. I want to do something like this, taking the first two letters of the name and use that to initialize the combobox.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = "" + txtrefFirstName.Text[0] + txtrefFirstName.Text[1];
firstStart = firstStart.ToUpper();
ddlReferring.SelectedText.StartsWith(firstStart);
}
else
ddlReferring.Text = "";
Any ideas or suggestions to get this to work?
Thanks
David K.
You could write something like this...
foreach (string item in ddlReferring.Items)
{
if (item.StartsWith(firstStart))
{
ddlReferring.SelectedText = item;
break;
}
}
Assuming the ddl's datasource is a List of String objects, you should be able to do some comparison on the datasource itself. I tend to use Linq for things like this but it isn't strictly necessary, just shorter.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = txtrefFirstName.Text.Substring(0,2).ToUpper();
string Selection = ddlReferring.DataSource.Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
ddlReferring.SelectedText = Selection ?? "";
}
else
ddlReferring.Text = "";
The selection line can also come from the items collection directly
string Selection = ddlReferring.Items.OfType<string>().Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
Or if you REALLY dont want to use Linq...
string Selection = "";
foreach (object item in ddlReferring.Items)
if (item.ToString().StartsWith(firstStart))
{
Selection = item.ToString();
break;
}
Similar methods can be used even if the ddl's data is not a list of strings, just make sure to cast the items appropriately and compare the correct values.

grid view search using dropdown list and text box filter?

Sir/madam now my problem is this that I want to filter the Grid View of a page using a Drop Down list and a text box.
I mean to say like we write a SQL such as:
Select * from student where roll_no = 101;
Right,
Now I what that the column (roll_no in above statement) should be selected by the drop down list and the value (101 in the above statement) should be entered by the Text box.
In short I want to populate my grid view using Drop Down list and the value of text box by clicking a button..
For developing i am using dataset and table adapters.
Please, help me for this..
I use a drop-down list (combo-box) and a textbox to filter my DataGridView the following way and I think this is what you are looking for.
First, populate your DataGridView. You state you are using a DataSet and TableAdapters. I am guessing that you are using a BindingSource to tie your Data to your DataGridView. If that is the case, then you can Filter your data via the BindingSource.
My set up is similar to this:
My combobox contains the fields that I want to use in my Filter and the textbox is the value that I will be applying. The values in the combobox are user-friendly names so they will understand which field they are filtering on.
The code to apply the filter is:
private void ApplyFilter()
{
var filterEntered = FilterTextBox.Text.Trim().ToLower();
MyBindingSource.RemoveFilter(); // remove previous filter
string filterText = string.Empty;
string filterComboText = string.Empty;
switch (FilterComboBox.Text)
{
case "Profile":
filterComboText = "TSProfile"; // column name in the query
break;
case "User Id":
filterComboText = "TSUserId";
break;
case "Center":
filterComboText = "TSCenter";
break;
case "Prefix":
filterComboText = "TSPrefix";
break;
}
filterComboText = filterComboText + " = '";
filterText += (string.IsNullOrEmpty(filterComboText) ? string.Empty : filterComboText);
filterText += (!string.IsNullOrEmpty(filterText) && !string.IsNullOrEmpty(filterEntered) ? filterEntered + "'" : string.Empty);
MyBindingSource.Filter = filterText;
}
Basically what it is doing, is getting the text name of the combo-box and then the text in the textbox and applying the Filter to the BindingSource.
MSDN has an article on Filtering thats contains full sample code.
The one thing that I recommend is to provide the user with a way to easily remove the filter, I use a Remove Filter button.
it would be helpful if you showed us a little code first..
you could try something like this tho:
in your codebehind, add items to your dropdownlist.
List<yourObject> list = new List<yourObject>();
foreach (yourObject i in list)
{
DropdownList1.Items.Add(new ListItem("" i.name, "" + i.id));
}
im just giving an example here, i.name could be the name of a certain student, i.id would be the id associated with that given student.
Make sure you have the autopostback attribute of your dropdownlist set to true, like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
Then in the selected Index Changed event of your dropdownlist, do the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
yourDataControl.DataSource = someMethod(Convert.toInt32(DropDownList1.SelectedValue));
yourDatacontrol.DataBind();
}
as i said, im not entirely sure what you're trying to do or how you're trying to do it.
the way i'm describing, you dont need the textbox to enter a certain value, by selecting an item in the dropdownlist you wil automatically get a value: in this case the ID associated with the selected item in the dropdownlist.

How do I toggle the display for a dynamic id table?

I have a table that displays rows based on a drop down list option. The rows are dynamically created. I use the value on the ddl for the initial row, then a simple counter to make it unique. Is there a way to say something like show all the rows that start with "tableShoes" even though the rows are something like tableShoes1, tableShoes2, etc?
$('#itemSelect').change(function() {
var item = $('#itemSelect').val();
$('#itemList tr').each(function() {
$(this).hide();
});
$('#' + item + 'Header').show();
$('#' + item + '1').show();
//Because the table is dynamic, I am not sure how many
//rows would be available so I only see the first option.
});
I would suggest adding the same CSS class name to each row as it is added, perhaps the same as the value of the selected item. That way your last line could just be:
$('.' + item).show();
And you wouldn't have to worry about the index.
this selector shoud solve your problem: $('[id|=tableShoes]')

Categories

Resources