I have a div that is being used as a dialog with jQuery's .dialog(). This div has a select box with options. The options the user has already selected are displayed on the main page. They can remove options from the main page and can open the dialog multiple times to add more options.
I populate the select box with all possible options on page load, but then when I open the dialog box I use jQuery's hide() to hide the options that the user has already selected and are displayed on the main page. This adds the CSS display:none; to the element in question, which IE ignores on <option> tags and displays anyway.
I can easily enough call remove() instead and remove it from the DOM. However, if the user selects some options, them removes them on the main page, then opens the dialog again to select more options, the options are no longer in alphabetical order, the options that were removed from the DOM and put back in it are now at the bottom since I used .append().
Is there any way to get IE to hide <option> tags? Or is there a better way to do this? Or is there a way to insert in alphabetical order simply?
If you need to remove it from the DOM, you could store the options in an array. One array (or object) for each option list. Then removing options from the list itself is reversable. You can always rebuild the select menu again from the array. Just populate the array once the dom-ready event fires.
Demo online: http://jsbin.com/avuru
$(function(){
// Define variables to be used throughout this code
var colors = [];
var list = $("select[name='colors']");
var btnRestore = $("button[name='restore']");
var btnRemove = $("button[name='remove']");
// Cycle through each option, adding its value and text to our collection
$("option", list).each(function(i, o){
colors.push({ 'key':$(this).val(),'val':$(this).text() });
});
// Remove any remaining options, and add collection back into dropdownlist
$(btnRestore).click(function(){
$("option", list).remove();
for (var i = 0; i < colors.length; i++) {
$("<option>").val(colors[i].key).text(colors[i].val).appendTo(list);
}
});
// Remove first option from list - used to test 'Restore' functionality
$(btnRemove).click(function(){
$("option:first", list).remove();
});
});
I would clone the list of options before modifying it and keep the original around. That way you can reinsert it clean by replacing the modified one with the orignal.
Related
So I have a widget that needs to be able to run multiple times within the same webpage. I have a dropdown with a list of names, and an Update button. Using:
updateBtn.onclick = function() {
var selected = document.getElementById("list");
var selectedCompany = selected.options[selected.selectedIndex].text;
getData(selectedCompany);
}
I'm searching the whole webpage for the first instance of the 'list' drop-down box.
How can I search so I find the value of the drop-down within the same instance of the widget instead?
If you attach the event listener to all instances of the button, you can use this to search up the document tree to get your parent container. Since this will reffer to the button you clicked.
Or, attach a unique attribute like data-button="firstOne" data-button="secondOne" if your system allows for that.
Loose example
var selected = this.parentNode.querySelector('#list');
Let me know if I misinterpreted your question in any way.
I have a button that is cloning an element on the page each time the user clicks it. It is duplicating a select list for them to choose another option.
However, its cloning the whole element including the option that was selected so all of the new ones appended have a default value which I dont want.
globalLocales = $("<div />").append($('[name=localeID]:first').clone()).html();
$('select').select2();
Is there a way I can remove the selected option during the cloning process so it doesn't carry over to the new element?
I tried using .removeProp('selected') in the append as well as .prop('selected',false); but that didn't work for me
One way to fix the proble is to select a nonexistent value:
$("<div />").append($('[name=localeID]:first').clone().val(-1)).html();
Or you can find selected option and remove selected attribute:
$("<div />").append($('[name=localeID]:first').clone()
.find(':selected').removeAttr('selected').end()).html();
but this is a little clumsy.
you can remove the selected attribute with this code.
$('[name=localeID] option:selected').removeAttr('selected');
Need to clone select box from previous one ( ie, add select box 'n' number of time from the previous one )
But when I added each time, all the previously selected options should not be available in the cloned select box list.
$('.field_select_box_list').each(function(){
$(this).find('option:selected').remove();
});
This code removes the parent select boxes selected option too.. but I want remain them to have the selected option.
any help.
Your clone code can just do something like
$('el').clone().find('option:selected').remove().end()
The .end() causes the selector to return to being $('el') rather than the filtered option:selected selector, so you can continue running things like .appendTo() etc without needing to break the chain.
I think you need use one select_box original, hidden it. Then you can remove with select_box second not hidden or add more element from select_box original.
I am new to jQuery so please go easy, I have a form that will represent an Advanced Search. Users will be able to add rows to refine their specific search.
Each row has 3 elements: A Checkbox & 2 x Select boxes.
As can be seen in the fiddle I am using jquery to clone the row and place the cloned row after the last row.
Everything is working fine except visually I would like the checkbox to use Bootstrap-Switch http://www.bootstrap-switch.org/
And the select boxes to use Selectize https://github.com/brianreavis/selectize.js
Now, when I clone the row with these plugins not active, everything works.
I have NO idea how to re-render or re activate them once a new row is inserted.
Is this something that is plugin specific? Or kind of universal to jquery?
I have read HEAPS of answers on here about similar things but I cannot seem to get it right.
Here is the jquery snippet:
$adSearchForm = $('#adSearchForm');
$adSearchForm.on('click', 'button, input, select, option', function (event) {
console.log("Button Clicked", event)
});
$('#addSearchRow').click(function(event){
$('[data-content=adSearch-3]:first').clone().insertAfter('[data-content=adSearch-3]:last');
// $('.searchByField,.searchOperator').selectize({refreshItems: true});
// $('[data-toggle=switch]').bootstrapSwitch({refreshItems: true});
});
Here is the fiddle, hope its ok. http://jsfiddle.net/CkVQr/6/
Thankyou very much for your help.
Cheers
Plugins change your HTML
There are two major problems you may not be fully aware of with your code:
Whenever you do a .clone() it merely deep clones your DOM element subtree, but not any event handlers bound to cloned elements.
Your .selectize() plugin changes HTML of your form quite considerably, converting input elements to other things. So whenever you clone your already converted select filter row, and subsequently want to run .selectize() on it again, this particular plugin won't find any suitable input elements to convert. Hence it won't work. Everything will just look as it should but won't work.
What can be done?
The main idea is that whenever you clone your search filter row, you have to clone your original HTML and not after it was converted using your plugins.
HTML Templates to the rescue
One of the possibilities is to change you page (and functionality) a bit and put your search filter row in a template and always use that. When you create your first row, you should read the template (and cache it) and add+convert it on your page. When you'd add an additional row, just use the same cached template and add+convert it again.
HTML template
<script id="filterRow" type="text/x-template">
<!-- Your filter rown HTML goes in here -->
</script>
Some Javascript
var cachedTemplate = cachedTemplate || $("#filterRow").html();
...
$('#addSearchRow').click(function(evt) {
var newRow = cachedTemplate.clone(); // clone for reusability
newRow.insertAfter('[data-content=adSearch-3]:last');
newRow.selectize();
...
});
I have a Magento Website. I have two js files, one written in Prototype an one in jQuery.
I have two select elements, with about 10 options. From jQuery I'm changing the first select's attribute "selected" (an some more). In Prototype I have a class that creates dependencies between two select elements.
If I click on the first select element and choose an option with the mouse, on the second select element will appear only the options that are linked to the option I choosed in the first select element. This is allready done in prototype.
The idea is that I want to do the click/trigger automatically from jQuery. The first select change it's selected option. But the second select element display all the options (and should display only the options linked to the first select element).
On the Prototype file I have some Event Observers, and I guess that these observers are not triggered from jQuery:
var select_el = $('select_' + id);
...
Event.observe(select_el, 'change', this.update.bindAsEventListener(this));
Event.observe(select_el, 'swatches:change', this.update.bindAsEventListener(this));
...
update: function(event) { ...
So I need somehow to trigger these events from jQuery, or to set an autocheck in Prototype.
Please tell me what should I do.
I've read on stackoverflow that events from Prototype can't be triggered from jQuery. There should be a way to do that. I just haven't found it.
I've tried jQuery functions like:
jQuery("option[value='" + checkedId +"']").attr("selected","selected").parent().focus();
jQuery("option[value='" + checkedId +"']").parent().trigger("onchange");
jQuery("option[value='" + checkedId +"']").parent().trigger('change');
Where the "parent()" is the first select element. The first select element changes as I want, but the second select element should automatically change after the first select is changed. And this never happens. It works only if I click with the mouse on the select and choose manually an option. I want to do this from jQuery, without being necessary to manually click on the desired option.
Thanks for reading this, and now just give me a fix for this problem.
Regards.