change name of dynamically added select option element - javascript

I am dynamically generating some dropdowns and then allowing them some of those to be removed on board dyanmically. so that time, i have encountered an error of selection option (dropdown) elements id mismatch. something like below is.
newly added dropdowns.
select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">/select>
select name="CSSAtapsClient[client_time_window_arr][1]" id="client_time_window_1">/select>
select name="CSSAtapsClient[client_time_window_arr][2]" id="client_time_window_2">/select>
select name="CSSAtapsClient[client_time_window_arr][3]" id="client_time_window_3">/select>
after i dynamically remove them via javascript. (lets say i am removing the second one) so then new ones will be displayed as followings,
select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">/select>
select name="CSSAtapsClient[client_time_window_arr][2]" id="client_time_window_2">/select>
select name="CSSAtapsClient[client_time_window_arr][3]" id="client_time_window_3">/select>
So now the issue i have is, the names of the dropdowns are like this, (0,2,3)
CSSAtapsClient[client_time_window_arr][0],
CSSAtapsClient[client_time_window_arr][2],
CSSAtapsClient[client_time_window_arr][3]
So this is causing an error for me and i need to reorder this name and make it be like this, (0,1,2)
CSSAtapsClient[client_time_window_arr][0]
CSSAtapsClient[client_time_window_arr][1]
CSSAtapsClient[client_time_window_arr][2]
how can i simply rename these dropdowns name attribute (from 0 to how much ever dropdows are exisiting) ? appreciate an early reply
EDIT 1
I tried this, but didnt work.
$('#tbl_dynamic_call_dates select').each(function(i){
$(this).attr('name',"CSSAtapsClient[client_time_window_arr][i]");
});

You can simply reset the values using .attr() method:
$('#tbl_dynamic_call_dates select').attr('name', function(i) {
return 'CSSAtapsClient[client_time_window_arr]['+ i +']';
});

I did this,
$('#tbl_dynamic_call_dates select').each(function(i){
$(this).attr('name',"CSSAtapsClient[client_time_window_arr][" + i + "]");
});

Related

With select2, how to access the original select/input element after it's been processed?

I'm using a combination of JQuery EasyUI and Select2 to be able to drag options from a right panel, onto a left select box.
In the original HTML, the select boxes are empty, and I only "add" anything to them if I drop an option on them,
<form id="section1">
<select class="select2" class="drop_target" id="selected_options" name="selected_options"></select>
<div>
<div class="draggable_option" data-id="1234">1234</div>
</div>
</form>
<form id="section2">
<select class="select2" class="drop_target"></select>
<div>
<div class="draggable_option" data-id="1235" id="selected_options" name="selected_options">1235</div>
</div>
</form>
Then in javascript, I do something like this,
$('.drop_target').droppable({
accept: '.draggable_option',
onDrop:function(e, source){
var $dragged_source = $(source);
var $drop_target = $(this);
}
});
The problem comes at this point, if you're dynamically adding things to the select, you have to check it doesn't exist, and if it doesn't, you create a new option, and add it,
var new_option = {
id: $drag_source.data('id'), data_id: $drag_source.data('id'),
text: $drag_source.val(), selected: true};
// Set the value, creating a new option if necessary
if (!$drop_target.find("option[value='" + new_option.id + "']").length) {
// Append it to the select
$drop_target.append(new Option(
new_option.text, new_option.id, true, true)).trigger('change');
}
var data = $drop_target.select2('data');
$drop_target.select2('data', data.concat([new_option]));
Clear as mud? Unfortunately it goes wrong at this point. While all calls to .select2 from $drop_target work as expected, this is not the select that was originally in the HTML, this is a div that select2 created, after hiding the original select, with an id attribute like id="s2id_selected_options". So when we append the new option to it, it doesn't get added to the select, and gets added to select2's div incorrectly instead.
My HTML pseudocode is deliberately set up in this "obtuse" way, because my page is like that. I have multiple forms, and multiple "identical" selects in those forms, generated by WTForms. So the "general" method of selecting your select by id, $('#selected_options') doesn't work correctly.
What I need to do, within the javascript, is gain access directly to the original, now hidden, select, and I can't access it via id.
When you have access to one of the elements that's "associated" with the generated by select2, you can access meta information for it via .data('select2'), or in this instance,
$(this).data('select2');
In here, there's loads of metadata that select2 uses (which you can see if you browse the source). For this question, to get the original select or input element, you can use,
var $drop_target = $(this).data('select2').opts.element;
Whether you're using a select, or an input, this gives you a jQuery element linking to it. If you're using a select, and are only interested in that, you can use the shorter option,
var $drop_target = $(this).data('select2').select;
This may be in the docs somewhere, but I was unable to find it, and I'm also not able to find it by searching now, because searching the docs for "data" and "select2" returns a result for nearly every page of their docs (hence the reason I'm answering this question myself, to hopefully save others the trouble).

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>

How can I add only unique options in multiple select tags which are in same class?

I need to dynamically add options to the select tags. Those options I will be fetching it from a file. There can be many selects in the form. Now I need to check all the selects whichever is in the same class If it doesn't have the option which I fetched from the file Then I need to add that option to that particular select.
var name = $(this).attr('name');
$('.slct').each(function(){
if($('this option[value="'+name+'"]').length==0)
{
$('<option>').val(name).text(name).appendTo(this);
}
});
When I tried the above code, Options are getting duplicated. For example I have 3 select tags. In the first tag I have an option called option1 remaining two tags are empty. Then after the execution of this code. First select tag contains the option1 twice and the remaining two tags contain only once. Can Someone tell me how do I do it ? I am new to jquery.
You can use find() to check if option with specific value exists in the select this way:
if($(this).find('option[value="'+name+'"]').length==0)
{
$('<option>').val(name).text(name).appendTo(this);
}
FIDDLE DEMO:
http://jsfiddle.net/3Lkv638x/1/

Can't programmatically select option using Select2

I have a Select2 working fine attached to a select list but when someone enters a new item and I rebind the select list and try to programmatically select the new item, it refuses to display.
There are a number of other posts re this but their solutions don't work for me.
Use .select2("val", value). Does nothing.
Use .select2("data", value). Does nothing. Not sure how this is supposed to be different.
Use the InitSelection option to set a value. This leads to the following error message: Uncaught Error: Option 'initSelection' is not allowed for Select2 when attached to a select element.
In the Ajax success function after adding the new option to the database, I have the following Javascript:
BindDishes(RestaurantID); //rebinds the select list successfully
$('#hidDishID').val = data.DishID; //populates a hidden field
var arr = '[{id: "' + data.DishID + '", text: "' + data.DishName + '"}]';
$("#dd").select2("data", arr);
So in this latest iteration I have tried to supply an array with the id and text from the select list item as per another suggested solution but still nothing occurs. What am I doing wrong? Is this impossible when using Select2 with a select list?
Edit: I have the following line in MVC that creates the Select list:
#Html.DropDownGroupListFor(m => m.DishID, Model.GroupedSelectList, "Select a dish", new { id="dd",style="width:470px;" })
which must be causing the problem by binding to DishID from the model which was originally blank when it came from the server. DropDownGroupListFor is just an HTML helper that allows for using OptionGroups in a Select but it must be the binding that is a problem. What is the best approach here, to bind in a different way or to somehow update the model's DishID, not sure of the best practice?
var $example = $(".js-example-programmatic").select2();
$example.val("CA").trigger("change");
You need to destroy your select2 before adding/modifying items. If you do, then your select2 will respond just like its bound first time
Select2 Dropdown Dynamically Add, Remove and Refresh Items from

multiple set of check box?

im having a set of multiple check bxes, like one set contain 3 check box share same name another set contain 3 check sharing same name . how can i get the value of these two different set of check box using a single code .
var form = $('usersurvey');
checkboxes = form.getInputs('checkbox');
for(count=0; count< checkboxes.length; count++){
if(checkboxes[count].checked){
retValue=true;
break;
}
}
return retValue;
}
im tried with this code but it fetch all the check boxes , i want only that have the same name, i used prototype.js
if you give each set of checkboxes a different class you could select them using jquery like:
$(".className").each(function(index, element) { ... });
for instance. somebody may be able to improve on this solution by selecting by name (i wasnt sure if you could do that, i always just select by class).
EDIT: sorry i should elaborate probably. the $(".className") piece will select all the checkboxes of class 'className'. since it sounds like you want to DO something with each of them though, i just added the each call on the end. inside the each call, you can define a function (shown) that will do something for each checkbox that was selected. reference the jquery each docs here:
http://api.jquery.com/each/

Categories