Retrieving attribute data from selected ListBox items in code behind - javascript

I have a web application using asp.net and C#. I have a ListBox where the user can select multiple items. They are grouped using the attribute property. I need this property in the code behind in the button click event. I thought I could set the attribute values on the client side and they would be available on the server side and have learned that is not the case.
I don't know the best way to go about this. Each ListItem has a Name, Value and Group that I would like to have on the server side. The name and value are already available on the server side. I need the group associated with each selected item. Should I create a hidden field for each selected item? Should there be one hidden field with the grouping and value associated with each grouping? I have a jquery function that sets the grouping attribute. I would like to use that to set the hidden field but I am not sure if I should use one hidden field or as many as items selected.
This is the javascript that I have already:
$(document).ready(function () {
//Create groups for recipient dropdown list
$(".chosen-select option[grouping='GlobalGroups']").wrapAll("<optgroup label='Global Groups'>");
$(".chosen-select option[grouping='PersonalGroups']").wrapAll("<optgroup label='Personal Groups'>");
$(".chosen-select option[grouping='Individuals']").wrapAll("<optgroup label='Individuals'>");
//Configure the ListBox using the 'chosen' jquery plugin
$(".chosen-select").chosen({
search_contains: true,
no_results_text: "Sorry, no match!",
allow_single_deselect: true
});
$('.chosen-container').css('width', '600px');
//set attribute property for selected list
$(".chosen-select").chosen().change(function (evt) {
$(".chosen-select").find("option:selected").each(function () {
var label = $(this).closest('optgroup').prop('label');
if (label == "Global Groups") {
$(this).attr("grouping", "GlobalGroups");
}
else if (label == "Personal Groups") {
$(this).attr("grouping", "PersonalGroups");
}
else {
$(this).attr("grouping", "Individuals");
}
});
});
});
This is the HTML:
<asp:ListBox ID="lstBoxTo" runat="server" SelectionMode="Multiple"
data-placeholder="Choose recipient(s)…" multiple="true" class="chosen-select">
</asp:ListBox>

For any with this problem...I went with a hidden field, asp:HiddenField, and adding all of the selections in a semicolon delimited string.
I parsed the string in the code behind to determine the recipients that were groups and ones that were individuals.
This was my final jquery script:
$(".chosen-select").chosen().change(function (evt) {
$("#hdnRecipientAttr").val("");
$(".chosen-select").find("option:selected").each(function () {
var label = $(this).closest('optgroup').prop('label');
var currentHdnValue = $("#hdnRecipientAttr").val();
if (label == "Individuals") {
var attrText = "Individuals-" + $(this).prop('value') + ";";
$("#hdnRecipientAttr").val(currentHdnValue + attrText);
}
else {
var attrText = "Group-" + $(this).prop('value') + ";";
$("#hdnRecipientAttr").val(currentHdnValue + attrText);
}
});
//remove ending semicolon
var hdnValue = $("#hdnRecipientAttr").val();
$("#hdnRecipientAttr").val(hdnValue.slice(0, -1));
});

Related

How to serialize just one value of input via jQuery?

I started to do dropdown list instead select bcz it is not possible to stylize but I did not think to future and now I found that if I want to save data from form to db I need to get ids via $_POST instead of names.
For ex. I have dropdown list with status of product:
New
Old
Handmade
If I want to save chosen sattus for chosen product it is better for me to get ID of status option. Bcz my table is like this:
item_id | option_value
1 | 1
If I send name as "old" via $_POST, I need to get its ID from another table before insert it.
I created dropdown list like this:
/* SELECT REPLACED BY DIV JS */
var select = $('.add-item__select').hide(); // Hide original select options
// Replace each select by div
select.each(function() {
var selectVal = $(this).find('.add-item__select-main').text(),
name = $(this).attr('name');
newDropdownDiv = $('<input class="add-item__input-select" name="' + name + '" placeholder="' + selectVal + '" readonly required><i class="arrow down"></i></input>')
.insertAfter($(this))
.css({paddingLeft: '0.3em', cursor: 'pointer'});
});
Each SELECT has addaed INPUT after it.
If I want to show shosen vale from dropdown list I need to show it in this way:
$('.add-item__input-select').val("text copied from list");
After this if I add ID of option to input in this way:
$('.add-item__input-select').attr("value", optionID);
Then If I want to serialize all fields values from form and this is point,
$('.add-item__form').serializeArray()
I get two results for status:
name: "status", value: "text copied from list"
and
name: "status", value: optionID
But I need just optionID.
I have everything optimized for this structure, so I would like to ask you if there is some easy way how to fix it or I need to modify structure.
I am thinking to remove INPUT and just change SELECT opacity to 0 instead of display none and use SELECT for form data serialize. But then I will need to replace all INPUTs by some DIV which will hold text of chosen option and also change everything else connected with it. For ex, if user clicked on INPUT the label was showed above it.
Thanks for advices
I found one solution but I have problem that it is working just if user will not refresh page. In DOM is everything the same after refresh but serializeArray() get just input text value and not value="ID" after page refresh.
I just remove these values which I do not want from FormData.
// Send formData to upload.php
$('.add-item__form').on('submit', function() {
event.preventDefault();
event.stopPropagation();
if ( checkFieldsIfNotEmpty() == true ) {
var formDataFields = $('.add-item__form').serializeArray(), // Get all data from form except of photos
count = Object.keys(data).length; // count fields of object
// Fill formData object by data from form
$.each(formDataFields, function(index, value) {
if ( value.name === 'category' && !$.isNumeric(value.value) || value.name === 'subcategory' && !$.isNumeric(value.value) ) {
// do nothing
} else if ( (value.name.indexOf('filter') >= 0) && !$.isNumeric(value.value) ) {
// do nothing
}
else {
formData.append(value.name, value.value); // add name and value to POST data
}
});
// foreach - fill formData with photos from form
$.each(data, function(index, value) {
formData.append('files[]', value);
});
uploadData(formData); // send data via ajax to upload.php
}
});
Can you advice me what can be problem?

Saving additional field from dropdown

I m having list of relations, when I select Other, new fields shows AddOther, and when I enter Test into new field, in database i get stored Other, because it takes from the f.select. What should i do to save into database from new field when i choose Other from the list.
= f.select(:relationship, ['Father', 'Mother', "Sibling", "Children", "Friend", "Spouse", "Other"], {}, { :class => 'form-select RelationshipSelect' })
fieldset class="form-group" style="display:none"
input#AddOther.mt-4.form-control[type="text" style="display:none" placeholder="Enter other relationship"]
$('.RelationshipSelect').change(function() {
var v;
v = $(this).val();
if (v == 'Other') {
$('#AddOther').slideDown();
} else {
$('#AddOther').slideUp();
}
});
I tried to add AddOther to f.select but no progress.
Cant figure it out how to save AddOther into list to be able to save it as Father, Mother....
This feels risky, because the relationship will only be valid/available for one use. You will be prone to pick up lots of "dirty" data.
That said, you could add jquery to monitor the 'change' event of AddOther, which would retrieve the value, add a new option to the select, set the value of the select to that value.
$('#AddOther').on('change', function(){
relationship = $(this).val();
$('.RelationshipSelect').append("<option value=\"" + relationship + "\">" + relationship + "</option>").val(relationship);
$(this).slideUp();
});
The best way was to create another column and save data from additional field in that column, and displayed it like that.

How can I capture checkboxes that I'm creating programmatically?

In my code below, I'm pulling in data from SharePoint (basically an excel spreadsheet) and displaying on my page. Checkboxes are pushed to my page using .innerHTML and are given an ID programmatically.
My question: How can I determine whether those checkboxes are checked (being that they could be different each time my app loads) ?
(Once I know what is checked, I'll display more metadata on the next page based on the checks - that part I have figured out)
$.ajax({
url: "myWebsite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+courseName.replace(/\s+/g, '')+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
You will need a way to know how many checkboxes has been created. When creating the checkboxes, them id must have a generic name and a number, for example id="checkbox0", id="checkbox1 and so on, then write the ammount of checkboxes in some part of the html code and put it some hidden tag. Then when reading the checkboxes data read the ammount of checkboxes and do a for
function getCheckboxes(){
var ammount = parseInt(document.getElementById("checkBoxesAmmount"));
var checkbox;
for(var i = 0; i<ammount; i++){
checkbox = document.getElementById("checkbox"+i);
//do staff
}
return;
I hope this works for you c:
This bit of jQuery returns all the checked input boxes that are in a ul with the class courseList:
jQuery('ul.courseList input:checked')
If your question is asked because the course name might change (your checkbox IDs are based on the course name), I suggest switching to the course number instead (or an appropriate mix of the two).
If you want to know if your dynamically created checkboxes were checked and want to do this via Javascript before the form is submitted, then add a class to your checkboxes (say dynamicCourse) and look for get the checked checkboxes via jQuery('input.dynamicCourse:checked').
Also, your checkboxes in your example don't have a value attribute set. If you're submitting it to a backend, you'll probably want it to have some value (course number would be my suggestion from the looks of it).

Disable Drop-down list item without removing the value from FormCollection

I have a number of the following drop-down lists within this page, each with a list of selectable users. When a user is selected in one list, I don't want them to be selected in any further lists. For this reason I have written a script to disable them.
When the form is submitted, the username of each user selected in a drop-down list should be appended to the Uservalue in the Form Collection.
This works correctly without the disabling of names but when I add seat-selectinto the class description, the names are always returned in the FormCollection as empty strings.
Do you know why this is or what I can do to keep the names populating correctly in the FormCollection?
Drop-Down List:
#Html.DropDownListFor(m => m.User, Model.UserList, "Select User", new { #class = "form-control seat-select", #id = "uniqueID", #onchange = "cleanUsers(this);" })
Java Script:
function cleanUsers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) { $(".seat-select option[value='" + val + "']").attr("disabled", true); }
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
UPDATE 06/06/2016:
Apologies to bring back an old post. I have tried the advice listed below and this works to return one of the selected values. Unfortunately, In my solution I have a number of identical drop-down lists and I need to keep track of exactly which result is from which drop-down.
I have posted my new code below. The string is overwritten when each of the drop-down menus is changed so does not currently work for me.
New JavaScript:
function cleanRowers(ddl) {
var val = ddl.options[ddl.selectedIndex].value;
var vOldVal = $("#" + ddl.id).attr("data-selected");
$("#" + ddl.id).attr("data-selected", val);
//Remove selected
if (val != 0) {
$("#SelectedUserText").val(val);
$(".seat-select option[value='" + val + "']").attr("disabled", true);
}
if (vOldVal != undefined) { $(".seat-select option[value='" + vOldVal + "']").attr("disabled", false); }
}
The Hidden value being updated:
#Html.HiddenFor(m => m.SelectedUserText)
I am trying to make the code as re-usable as possible so dont really want a different identifier for each of the drop-downs but it is important that I keep track of which drop-down the information is coming from.
Is there a way in which this can be done?
Disabled attribute do not put value in form submission thats why you are receiving empty string .
Here is a trick you can apply :
Put the selected value in a hidden input field onchnage function then read the hidden value on form submission instead of reading vslue of disabled dropdown.
Hope that helps .

Adding more than one value to text box

I'm trying to allow users to add a list of 'favourites' to a text box but when adding more than one value it replaces the value already there. Can anybody help? Thanks this is my code:
var name
function getFavourite() {
name = "Student 1, ";
$('#output').val(name)
saveFavourites();
}
function getFavourite2() {
name = "Student 2, ";
$('#output').val(name)
saveFavourites();
}
function saveFavourites() {
var fav = $("#output").val();
if (fav !== "") {
localStorage[name] = $("#output").val();
$("#output").val(name);
}
}
function loadFavourites() {
var fav = $("#name").val();
if (name !== "") {
$("#output").val(localStorage[name]);
$("#name").val("");
}
}
using val will replace the existing value as you already noticed so i would do something like this if you want to add to that value.
$("#output").val($("#output").val() + ', ' + name);
At least if i understand you correctly. This would get the excising value and then add the new value to it (in this case with a comma but is not necessary)
Of course if you need the same element twice or more is better to assign it to a var instead of calling the selector twice.
I think you are looking into multiple select dropdown, something like this:
http://codepen.io/martynasb/pen/kawxq
You don't an text input, you want a select where you can select multiple values. In html, it's <select multiple>.
The plugin I know that provides the best experience for this is is Select2: http://ivaynberg.github.io/select2/#basics
And you don't have to load all the options right away, they can be fetched via ajax easily.

Categories