How do you get chosen.js to use javascript generated cloned content? - javascript

I am using chosen.js version 1.8.7
I am able to clone the content of a div to another div with all of the data and events using clone(true).I have changed all of the ID's to have a new ID on the cloned items.
The problem is when I select a javascript generated select list, it activates the original select list and not itself.
I have tried cloning without all of the data and events by using clone(). It clones but it doesn't allow the newly generated <select> to drop-down at all.
I have removed chosen.js and the clone(true) copies everything and each <select> list works individually but there is no filter capability.
<form method="post" name="add_items">
<div class="clone-test" id="cloned">
<select id="items1" name="contract_item[]" class="form-control chosen-select" data-placeholder="Choose a item...">
<option value="0">Select a Item</option>
<option value="1">Car 1</option>
<option value="2">Car 2</option>
<option value="3">Car 3</option>
</select>
</div>
<div class="col-md-6" id="new_items"></div>
</form>
<input type="button" onclick="clone_div()" name="add" value="Add Another Item" class="btn btn-primary" id="add_select">
<script type="text/javascript">
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $("#cloned").length;
function clone_div(){
$("#cloned").clone(true)
.appendTo("#new_items")
.attr("id", "cloned" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
cloneIndex++;
$("#new_items").html(html);
$(".chosen-select").chosen();
}
</script>
I expect to have each individual <select> list to work independently having each list with filter capability using chosen.js. What I am getting is having the original select list activate no matter which javascript generated <select> list I choose.

Related

how to get multiple dropdown list value in jQuery when i clone multiple dropdown

when i click button clone is worked but it is showing value only one dropdown list
i want to get value clone multiple dropdown list and show the alertbox
there is my code
$(document).ready(function() {
$('#btnid').click(function() {
$('#idcuntry').clone().attr('id', 'id_' + $(this).index()).insertAfter('#idcuntry');
var a = $('#idcuntry').val();
alert(a);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="idcuntry">
<option value="10">Selection </option>
<option value="20">Pa </option>
<option value="30">India </option>
</select><br/>
<input type="button" value="clone" id="btnid">
The first problem is that you are getting the value of #idcuntry, and there's only one with this ID (which is good, IDs should be unique, so you made the right choice of changing the ID of your clones).
To target multiple elements, you can add a class to them, for example class="countryselect".
Then, .val() will only return the value of the first element. But you can use .map() to get them all in an Array:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btnid').click(function() {
$('#idcuntry').clone().attr('id', 'id_' + $(this).index()).insertAfter('#idcuntry');
var a = $('.countryselect').map(function() {
return $(this).val();
}).get();
alert(a);
});
});
</script>
<select id="idcuntry" class="countryselect">
<option value="10">Selection </option>
<option value="20">Pa </option>
<option value="30">India </option>
</select><br/>
<input type="button" value="clone" id="btnid">

duplicate drop-downs on button click

Currently I have this setting.
My page loads with 2 drop-downs aligned adjacent and an ADD button.
The ADD button adds a drop-down in the next row using the function addRow().
The function is probably the worst implementation though.
a) I want ADD button to add 2 similar drop-downs aligned adjacent as in the page initially, to the next row. (right now the code only adds 1 drop-down in the next row)
b) is there any way I can put my ADD button to be below the drop-downs I have instead of being next to the first row of drop-downs?
Below is the code
<div class="container">
<table>
<tr>
<td>
<select id="soflow">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="soflow">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<button class = "button" type="button" onClick ="addRow(this)">Add</button></td>
</tr>
</table>
</div>
<script>
function addRow(btn) {
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
//var element2 = document.createElement("input");
var element2 = document.createElement("select");
element2.setAttribute("id", "soflow")
//element2.type = "select";
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.add(option1, null);
var option2 = document.createElement("option");
option2.innerHTML = "Option2";
option2.value = "2";
element2.add(option2, null);
cell1.appendChild(element2);
}
</script>
Thank you for any help.
Give id to your <tr> to be cloned and to the table. Then use cloneNode() to clone the row and append it to the table.
<div class="container">
<table id="myTable">
<tr id="initialRow" class="select_row">
<td>
<select id="soflow" class="select1">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="soflow" class="select2">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
</tr>
</table>
<button class = "button" type="button" onClick ="addRow()">Add</button>
<button class = "button" type="button" onClick ="getValues()">Print values</button>
</div>
<script>
const table = document.querySelector('#myTable');
const rowToDuplicate = document.querySelector('#initialRow');
function addRow() {
var duplicate = rowToDuplicate.cloneNode(true);
duplicate.removeAttribute('id'); table.appendChild(duplicate);
}
function getValues() {
const rows = document.querySelectorAll('.select_row');
rows.forEach((row, i) => {
console.log(`row ${i}: select1 `, row.querySelector('.select1').value); console.log(`row ${i}: select2 `,row.querySelector('.select2').value);
})
}
</script>
You have two IDs which have the same name. Change the ID property to have different names for both select elements like <select id="soflow1"> && <select id="soflow2"> and refer to each element as soflow1 or soflow2 in your Javascript. Your JavaScript is referencing two ID elements and causing two dropdowns to open with one call.
IDs should be unique to only one element.
To use the same style across those dropdown elements add a class property which is the same to both select elements like <select id="soflow1" class="myDropdownClass"> && <select id="soflow2" class="myDropdownClass"> and create CSS for .myDropdownClass { //some style }
To put the button underneath the select elements you could do this in your table...
<table>
<tr>
<td><select id="soflow1" class="myDropdownClass" ... /></td>
<td><select id="soflow2" class="myDropdownClass" ... /></td>
</tr>
<tr>
<td colspan="2"><button>text</button></td>
</tr>
</table>
I like to add the event listener to the table since the click will bubble up the dom tree. Then check to see that it was an element with the class "add" that called the event. If it is then clone the row node of the table and append it to the table body. I also placed the button in the table footer so it always stays at the bottom. Hope this helps.
This method also allows you to change the structure of the table without having to rewrite the javascript to correctly climb the dom tree. Added a remove row button just for S&G.
In similar fashion to get the values without having ids on every select element you could use the elements index from a list of solflow elements as a unique identifier and the value.
Since you are creating dynamic elements by cloning the row, either the event listeners for the solflow need to be added to the new select elements or the table can handle the change event in which case you add the change handler once and the solflow change bubbles up no matter when the element was added. In similar fashion a submit button can be created with the table click handler grabbing all the values from the solflow elements in the table and indexing them to the number of solflow elements as either a key value store or as an array of solflow values matching the order in which the elements appear.
<table>
<tbody>
<tr>
<td>
<select class="solflow">
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select class="solflow">
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button class="button add" type="button">Add</button>
<button class="button remove" type="button">Remove</button>
</td>
</tr>
</tfoot>
</table>
<script>
function tableClickHandler(e) {
if (e.target.classList.contains('add')) {
let tbody = this.querySelector('tbody');
let row = tbody.querySelector('tr');
tbody.appendChild( row.cloneNode(true) );
}
if (e.target.classList.contains('remove')) {
var tbody = this.querySelector('tbody');
var row = tbody.querySelectorAll('tr');
if (row.length > 1) {
tbody.removeChild(row[row.length-1]);
}
}
}
function tableChangeHandler(e) {
if (e.target.classList.contains('solflow')) {
let solflows = this.querySelectorAll('.solflow');
let solflow = e.target;
let index = -1;
solflows.forEach(function(el, ind){
if (el === solflow) { index = ind }
});
console.log(index, solflow.value);
}
}
document.querySelector('table').addEventListener('click', tableClickHandler);
document.querySelector('table').addEventListener('change', tableChangeHandler);
</script>
You can use a for loop to loop twice and create two selects. You should move the button outside of the table if you want it to always be under the selects (both added and initial ones) while adding new rows to the table for the selects.
Also, you can not have more than one element with one id. You initially have 2 elements with the id "soflow" and are going to add more when the Add button is clicked.
To count how many selects have been added, you just need a global variable that increase by one each time the for loop inside the function is run.
<div class="container">
<table id="selectTable">
<tr>
<td>
<select id="soflow">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="soflow2">
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<br/>
</td>
</tr>
</table>
<button class = "button" type="button" onClick ="addRow(this)">Add</button>
</div>
<script>
var addedSelects = 0;//total number of dropdowns added
function addRow(btn) {
var table = document.getElementById('selectTable');
var soflow = document.getElementById("soflow2");
var rowCount = table.rows.length;
var row = document.createElement('tr');
table.appendChild(row);
//var element2 = document.createElement("input");
var td = document.createElement('td');
row.appendChild(td);
for(let i = 0; i < 2; i++){
var element2 = document.createElement("select");
//element2.setAttribute("id", "soflow"+(i+1))
//element2.type = "select";
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.add(option1, null);
var option2 = document.createElement("option");
option2.innerHTML = "Option2";
option2.value = "2";
element2.add(option2, null);
td.appendChild(element2);
addedSelects++;
}
}
</script>
This should do the trick
function addRow() {
//Select the table
var table = document.getElementsByTagName('table')[0];
//Append a row
table.innerHTML = table.innerHTML + '<tr>\
<td>\
<select>\
<option>Select an Option</option>\
<option>Option 1</option>\
<option>Option 2</option>\
</select>\
<select>\
<option>Select an Option</option>\
<option>Option 1</option>\
<option>Option 2</option>\
</select>\
</td>\
</tr>';
}
<div class="container">
<table>
<tr>
<td>
<select>
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<select>
<!-- This method is nice because it doesn't require extra div tags, but it also doesn't retain the style across all browsers. -->
<option>Select an Option</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</td>
</tr>
</table>
<button class = "button" type="button" onClick ="addRow()">Add</button>
</div>
The ADD button always stays at the bottom because I moved it out of the table. I removed the id on the select tags, duplicate ids will give you errors, try using document.getElementsByTagName('select')[x] selector and use 0 (where x) to get the first drop down, 1 to get the second... I also just used text instead of creating the elements via JS because their much easier to read, create, and modify in my opinion. If you have any questions just ask.

Dynamically append multiple options selected into one select jquery

I'm trying to add the options selected from one select element into another. I'm guessing it'll be something like this.
var selected = $("#selectWithOptions").append("<option'>" +
options[selectedIndex].value + "</option>");
This does not work.
The logic is pretty straight-forward and you can follow the inline comments in the JS function:
// Fire this function when a dropdown item is selected
$('#dd1').change(function() {
// Grab the text of the selected item
var selectedOption = $('#dd1 :selected').text();
// If it is not already in the second dropdown list, then append it
if( $('#dd2 option').filter(function () { return $(this).text() == selectedOption; }).length <= 0 ) {
$('#dd2').append('<option>'+selectedOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Dropdown 1:
<select id="dd1">
<option selected disabled>Select option</option>
<option>foo</option>
<option>bar</option>
<option>baz</option>
<option>xiyar</option>
</select>
</div>
<div>Dropdown 2:
<select id="dd2">
</select>
</div>
In Javascript(and jQuery), everything is an object. Get the selected option elements using the jquery :selected selector and then append them to the second select element.
I'm using clone() but if you don't want to copy, rather you want to move the elements from one select to the other, then get rid of clone() and that same object will be moved to the other select element.
$('button').on('click',function(e){
var opt = $('#first option:selected').clone();
$('#second').append(opt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="hello">Hello</option>
<option value="world">World</option>
</select>
<select id="second">
</select>
<button>
Copy
</button>

Open the html selected list with a button click

I have created a option list in a webpage where I want to open the select list with a button created with a <div> when a option selected from the list then the selected value comes on the div also.
So here I want the javascript attribute to open the list on button click something like this
document.getElementById('selectedlist').open.
any body have suggestion about this?
Take a look at http://code.google.com/p/expandselect/. I think this is what you want.
Then you can open the select like this.
ExpandSelect("myselect_id")
Here is the simple Javascript code to open(toggle) the select box on clicking the button.
<script type="text/javascript">
function expandSelect(id){
var select_flag = document.getElementById('select_flag').value;
if(select_flag==1){
var select_box = document.getElementById(id);
select_box.size = 1;
document.getElementById('select_flag').value = 0;
}else{
var select_box = document.getElementById(id);
select_box.size = select_box.options.length;
document.getElementById('select_flag').value = 1;
}
}
</script>
<button onclick="expandSelect('select_box')"> Toggle Select Box </button>
<div id="container">
<select name="select_box" id="select_box" >
<option value="">Select</option>
<option value="">option1</option>
<option value="">option2</option>
<option value="">option3</option>
<option value="">option4</option>
<option value="">option5</option>
<option value="">option6</option>
</select>
<input type="hidden" name="select_flag" id="select_flag" value="0">
</div>

How to get the values from a dynamically created select box in fcbk multiple selection?

The html code below is the dynamically created select box with selected values in fcbk autocomplete with multiple selectio, it keeps adding while adding the value in the text box. I want to get the values of this text box and get it added in a textbox as comma separated values. I did the same with fcbk auto complete version 1.8 but now i have no idea with 2.8.
reference - Demo : http://www.emposha.com/demo/fcbkcomplete_2/
Documentation - http://www.emposha.com/javascript/fcbkcomplete.html
<select id="interestedin" class=" hidden" multiple="multiple" name="interstedin[]">
<option id="opt_X1B68LKqUz0w09w2w8gymEoNsgm7Cmz9" class="selected" selected="selected" value="2">Canon‌·Powershot‌·</option>
<option id="opt_GBLgf5byTaH4xlhSiaZh02Ug39ALVNpL" class="selected" selected="selected" value="5">Levis‌·Jeans</option>
<option id="opt_TLywToQcvQ9bcLFmCCSm2vmtQUW9NDEo" class="selected" selected="selected" value="8">Dashing‌·Cars</option>
<option id="opt_vGDDgTGeyQVb6kGb8eaKVSG5qdyTaTfA" class="selected" selected="selected" value="8">Dashing‌·Cars</option>
</select>
I've quickly checked the source code for this plugin but it does not seem to provide such functionnality out-of-the-box. And their documentation is pretty minimal :-/
Her's some jquery code to achieve what you want:
var txtarr =
$('#interestedin option.selected')
.map(function() { return $(this).text(); })
.toArray();
$('#result').val(txtarr.join(','));
assuming you got the followin html:
<select id="interestedin" class=" hidden" multiple="multiple" name="interstedin[]">
<option id="opt_X1B68LKqUz0w09w2w8gymEoNsgm7Cmz9" class="selected" selected="selected" value="2">Canon‌·Powershot‌·</option>
<option id="opt_GBLgf5byTaH4xlhSiaZh02Ug39ALVNpL" class="selected" selected="selected" value="5">Levis‌·Jeans</option>
<option id="opt_TLywToQcvQ9bcLFmCCSm2vmtQUW9NDEo" class="selected" selected="selected" value="8">Dashing‌·Cars</option>
<option id="opt_vGDDgTGeyQVb6kGb8eaKVSG5qdyTaTfA" class="selected" selected="selected" value="8">Dashing‌·Cars</option>
</select>
<input type="text" id="result" size="200" />
Here's a jsfiddle for you to try;
How to execute this code when an item is added/removed:
The plugin offer two callbacks option: onselect / onremove:
// cache jquery selections for re-use
var $resultField = $('#result'),
$selectElement = $('#interestedin');
// the function to build the comma-separated string
var changeFCBKHandler = function(item) {
var txtarr = $selectElement.find('option.selected')
.map(function() { return $(this).text(); })
.toArray();
$resultField .val(txtarr.join(','));
};
// reference the 'changeFCBKHandler' handler for the onselect/onremove callbacks
$selectElement.fcbkcomplete({
...
onselect: changeFCBKHandler,
onremove: changeFCBKHandler
...
});
I've not been able to test this because the plugin only accepts an URL as data-source but it seems it should work.

Categories

Resources