jquery-select2 send values to server as CSV string - javascript

Is it possible to send as one CSV-string all selected values in HTML select element with multiple="multiple" using jquery-select2 library?

I had a similar requirement and could not find any options to accomplish this directly through the Select2 plugin. However, it was easy enough to create a separate input element and synch it on the select's change event.
var $options = $('select#options'),
$optionscsv = $('input#optionscsv');
$options.select2()
.on('change', function() {
$optionscsv.val($options.val());
});
Here's a live example on codepen: http://codepen.io/anon/pen/gpLbLG

Related

jquery clone and select/select2 selected values on jquery cloned elements getting lost

I'm currently in trouble with a select/select2 and jQuery $.clone issue.
In a html form with html select boxes replaced with select2 but the select2 jQuery plugin is not really relevant for this issue.
I experience problems when I use jQuery $.clone(true, true) to get a copy of a form to work on it.
When I try the following:
window.clone = $('#formSelector').clone(true,true);
The selected values are cloned and get lost. See http://jsfiddle.net/straeger/ct31f34c/9/
Even If I try to remove select2 with the call the cloned select boxes do not hold the selected values.
$('select').select2('destroy');
window.clone = $('#formSelector').clone(true,true);
see: http://jsfiddle.net/straeger/dokenyss/1/
A small hack with a big drawback (if no ID is present) is to copy the selected values to the clone:
$clone.find('select')
.each(function(index, value){
var $el = $(value);
$el.val($element.find('#'+$el.attr('id')).val());
});
see: http://jsfiddle.net/straeger/ct31f34c/10/
My question is what would be the correct way to handle such a problem ?
Does anyone know a way to select the counterpart of the original element from the original jQuery element if I have no ID?
Or a way to persist the currently selected option ? via the attribute e.g.
<option value="c" selected>C Value</selected>

Change Text Field Once Drop Down Has Been Selected (Multiple forms on 1 page)

I'm looking to change the value of a <p> tag once an option from a drop down has been selected. I have that working but my issue is I am going to have lots of forms on one page and feel like I am repeating my code. Is there a way to do this with a function for example? To save me writing a new section of javascript everytime a form gets added to my page?
My javascript code:
$('.orderProduct select#packageOption').change(function(){
$('#packagePrice').html($(this).val());
});
$('.orderProduct2 select#packageOption').change(function(){
$('#packagePrice2').html($(this).val());
});
Thanks.
Add a data-element-id attribute to each select like:
<select data-element-id="packagePrice">...</select>
<select data-element-id="packagePrice2">...</select>
then you simply need this jQuery code:
$('select[data-element-id]').change(function(){
var $this = $(this);
var id = $this.data('element-id');
$('#' + id).html($this.val());
});
If you want to avoid the extra attribute you could use jQuery's DOM traversing functions, to locate which p you should update.

Reading multiple SELECT values with JavaScript/jQuery

I understand that SELECT multiple will let a viewer select multiple items in a dropdown list and then the form submission passes all the selected items. But how does this work in JavaScript when there is no form submission and you're just watching for a select change:
$('#delete_dropdown').change(function(e){
and then looking at $(e.target).val() for the selected values?
Thanks
You can look at this context inside your handler and val() will return the array of elements, with jquery you can do this:
$('#delete_dropdown').change(function(e){
var selectedArray = $(this).val(); //Array of selected values
});
Fiddle
If you are going with vanilla javascript you will need to loop through the options to check which all are selected and add them to suit yourself.

Select2 custom read custom data attributes

I am using the jquery select2 plugin for suggestive form fields. I am trying to access the data stored in my original hidden input fields data attribute. I need the data from these attributes so I can send them to a php script via Ajax. Does anyone have any suggestions on how this would be done? I cannot seem to find a answer on google or the official website.
Thanks
You could also try the following. Suppose you have a select, you can add additional information to the options by using standard data-attribute syntax from jQuery, see jQuery data() API.
<select id="product">
<option value="prod_x" data-additional-info="1234X">Product X</option>
<option value="prod_y" data-additional-info="1234Y">Product Y</option>
</select>
Now in your javascript you can get to the option element itself by using .select2("data"), according to api docs - "Gets or sets the selection. Analogous to val method, but works with objects instead of ids". To get to the option object itself you have to go through the element, an array of all the selected options. In the example below the select is not multi value selectable so I always use the first object from the array, in addition to getting the object I wrap the result from ".element[0]" in $() to make it a jQuery object.
// Get the selected option using select2's api...
var selectedOption = $($("#product").select2("data").element[0]);
Now that we have a jQuery object we can use the jQuery data() API as follows to retrieve the arbitrary data stored on the option element.
var additionalInfo = selectedOption.data("additional-info");
The additional info variable will now contain either "1234X" or "1234Y" depending on which one was selected.
Using this you could eliminate the hidden inputs that holds the additional data and tie it directly to the selected option.
Like in the docs:
//Template:
<select>
<option value="0" data-foo="bar">option one</option>
</select>
//Initiate select2
$("select").select2({
formatResult: format,
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
//access custom data
function format(state) {
var originalOption = state.element;
return $(originalOption).data('foo');
}
We can get data attributes for the selected option
var seledted = $("#selectId").select2().find(":selected");
var s = $(seledted).data("data-field");
I ended up accomplishing this by
$(".suggestive-entry").click(function() {
var val = $(this).siblings('input:hidden').attr('data-field');
alert(val);
});
as you can see i used the siblings attribute to get the hidden input closest to the select2 box that generated the click event.

Using data attributes to filter a select box (using third party JS filtering code)

I am using this relatively simple JS program:
http://www.barelyfitz.com/webdesign/articles/filterlist/
The program just filters a select box using a text box.
However, I want to jquery and HTML5 data attribute which is different how it was originally used. I give my text box filterer a data attribute:
<input id="filter_text" name="filter_text" data-filterable="myselect"
type="text" />
I use the following jquery to get the name of the select box that is to be filtered and then filter the select box:
$(function() {
$('input[data-filterable]').keyup(function() {
select_box_name = $($(this).data('filterable'))[0];
filter = new filterlist(select_box_name);
filter.set(this.value);
});
});
which NEARLY works. You can filter but if you press backspace to de-filter then nothing happens i.e. it doesn't 'unfilter'.
It must be something really small!!
Thank you :).
You need to initialize the filter outside the event handler:
$(function() {
$("input['data-filterable']").each(function() {
var filter = new filterlist($($(this).data('filterable'))[0]);
$(this).keyup(function() {
filter.set(this.value);
);
});
});
On every keyup you're reinitializing filter. So you can only filter on the select as it is right when you press a key. Move the initialization of the filter out of the keyup event and it's working.
Here's a fiddle.

Categories