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.
Related
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?
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 .
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));
});
I'm using select2() field using select2 library and Drag and Drop Sorting is enabled in the field.
It works well, but once i save it, the ordering break and they are ordered alphabetically.
I was wondering if its possible to anyhow save ordering of elements after drag drop in select2() fields.
Please suggest.
Per Select2 documentation, the new ordered values are saved in a attached hidden field.
http://ivaynberg.github.io/select2/
(right click on the Input field and then inspect element to find the line below just after the div#select2-container)
There are two options that might work for you:
Option 1:Easy one
Check the ordering of how you are feeding the control, specific on:
$("#e15").select2({tags:["red", "green", "blue", "orange", "white", "black", "purple", "cyan", "teal"]});
The control just render the same order that the above line is specified.
If you are not saving those values as comma separated text and instead as row records, maybe your database query is ordering them alphabetically.
Option 2: A little bit further
This code will serve you to save the ordered values in a cookie, so you can have the same order within your whole session.
$(function(){
if ($.cookie('OrderedItemList') != null){
$("#e15").select2({tags: $.cookie('OrderedItemList').split(',')});
}
$("#e15").on("change", function() {
$("#e15_val").html($("#e15").val());
$.cookie('OrderedItemList', $("#e15").val(), { expires: 365 });
});
});
Please note, this code might not work for database bound fields, you might need to add some code if thats what you need.
Well I had your problem. I've overcome it with something like this...
A hidden input to save your order.
the listener on the select2.
$("#reports").on('change', function(){
var data = $(this).select2('data');
var array = [];
$.each(data, function(index, val) {
array[index]=val.id;
});
array.join(',');
$("input[name=reports]").val( array );
});
<form class="form-horizontal form-bordered" action="#something" method="post" accept-charset="utf-8" target="_blank" >
<input type="text" name="reports" >
<select id="reports" class="form-control select2me" multiple >
<? foreach ($Balance::getSeparators() as $key => $value ) { ?>
<option value="<?=( $key )?>"><?=( $value )?></option>
<? } ?>
</select>
</form>
This way the input[name=reports] sends to your page the correct order.
Select2 has progressed to version 4, which is based on <select/> and <option/>-tags, instead of <input/>-tags. I solved it for version 4 as follows:
$(".select2").select2().on('select2:select', function(e){
var $selectedElement = $(e.params.data.element);
var $selectedElementOptgroup = $selectedElement.parent("optgroup");
if ($selectedElementOptgroup.length > 0) {
$selectedElement.data("select2-originaloptgroup", $selectedElementOptgroup);
}
$selectedElement.detach().appendTo($(e.target));
$(e.target).trigger('change');
})
Basically I remove and re-add the selected items to the select-options-list, so that they appear in order of selection.
The hidden field solution was a good solution in my case, but Select2 plugin still keep a numerical/alphabetical(?) order, that is not the user selection's order
I found a solution, that solves all my needs.
In my symfony form declaration will be the hidden field called selectOrder in which to save the current order:
$("#form_people").on('change', function(){
var data = $(this).select2('data');
var array = [];
$.each(data, function(index, val) {
array[index]=val.id;
});
array.join(',');
$("#selectOrder").val( array );
});
and in the javascript part after form declaration there is my Multi Select2:
var sel = $("#form_people").select2({
maximumSelectionSize: 3,
minimumInputLength: 1,
escapeMarkup: function(m) { return m; },
});
then
//After reloading page you must reselect the element with the
//right previous saved order
var order = $("#selectOrder").val().split(",");
var choices = [];
for (i = 0; i < order.length; i++) {
var option = $('#form_people option[value="' +order[i]+ '"]');
choices[i] = {id:order[i], text:option[0].label, element: option};
}
sel.select2('data', choices);
It's what I need, and maybe can help other developers
I am hoping for some insight on the best way to accomplish the following. I want to create a form that will allow for more fields to be added when a + or add button is clicked. So for example the user would fill out a text field lets call it "Description" and then next to it another field called "Unit number". I want to allow for multiple "Description" and "Unit number" fields without submitting the form after each entry, but for the sake of keeping the site looking "Clean" I don't want there to be several duplicate fields if the user only needs to enter information into one of them. I was thinking about using JavaScript to hide the additional fields by just setting display:none. Is this a good/efficient solution? Is there a better solution? I am new to programming so take it easy if you feel this is a dumb question.
The best way to do this is to make your fields and put them in a div and then hide it. Use jQuery to .clone your first row and then update the field names any time the user clicks an add link.
You can use a templating library like mustache or handlebars. You can also do this using jQuery. My approach would be to generate new elements on the fly. I won't hide it so that the user can see if he is already inputting duplicate. But if you want to make your markup cleaner, you can also hide the field once the user has already inputted something. So when the user clicks on the add button, you will need to check if the user has actually inputted something, if there is an input, then hide it and then generate a new input again.
If you need a code sample, feel free to ask.
Here's some javascript I wrote on my own site awhile ago:
var SITE = SITE || {};
SITE.fileInputs = function() {
var $this = $(this),
$val = $this.val(),
valArray = $val.split('\\'),
newVal = valArray[valArray.length-1],
$button = $this.siblings('.button'),
$fakeFile = $this.siblings('.file-holder');
if(newVal !== '') {
$button.text('File Chosen');
if($fakeFile.length === 0) {
$button.after('<span class="file-holder">' + newVal + '</span>');
} else {
$fakeFile.text(newVal);
}
}
};
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span class=\"file-wrapper\"><input type=\"file\" name=\"screenshot[]\" id=\"screenshot\" /><span class=\"button\">Choose a screenshot</span></span>";
document.getElementById(divName).appendChild(newdiv);
counter++;
$('.file-wrapper input[type=file]').bind('change focus click', SITE.fileInputs);
}
}
$(document).ready(function(){
$("#addss").click(function(){
addInput("screenshots");
});
});
Then you can just use the array for the name in the php or whatever else you're using to handle the data.
HTML:
<div id="screenshots">
<span class="file-wrapper">
<input type="file" name="screenshot[]" class="screenshot" />
<span class="button">Choose a screenshot</span>
</span>
</div>
<input type="button" id="addss" value="+Screenshot" class="btn" />