Appending to a select leaks memory JavaScript JQuery - javascript

I have a select drop down menu, every time I refresh my page I have to re populate that select drop down. Which is resulting in a memory leak. This is the code any help would be great in refactoring the code. Also I have tried to make another method and calling it before this one, the other method would empty the options array and make it null. That did not help me.
var option = $(document.createElement("option"));
option.attr("value", List.id);
option.text(List.name);
if(List.name.length > maxSize) {
maxSize = List.name.length;
}
this.options.push(option);
//Mark the currently displayed list as the selected option
if (activeListId > 0) {
if (activeListId == List.id) {
option.attr("selected", true);
}
}
}
Toolbar.ListSelect.append(this.options);

It would be very helpful if you included more of the surrounding code so that we could know what is what, but here's my best shot at it given the current situation.
// Reference box
var $box = $('#id-of-select-box');
// Clear select box
$box.empty();
// START LOOP
// Create new option
var $option = $('<option value="'+List.id+'">"'+List.name+'"</option>');
// Append option to select box
$box.append($option);
// END LOOP
//Mark the currently displayed list as the selected option
if (activeListId > 0) {
$box.val(activeListId);
}

I whould suggest to create a new Element, then cut the provided name if exceeds thet maxSize using slice). Later we add the parameter "selected" if there is a match on activeListId and List.id. Latter we append the new option to Toolbar.ListSelect (I suposse it to be the element
var option = jQuery("<option />").attr('value', List.id);
var optionName = List.name.slice(maxSize);
option.text(optionName);
if ( activeListId && activeListId == List.id)
option.attr("selected", true);
option.appendTo(Toolbar.ListSelect)

Related

Javascript - Dynamic Expand/Collapse All

I have a jQuery Tree Report that I am trying to create 'expand/collapse all' buttons for.
The following two pieces of code are fired when the corresponding buttons are pressed and work great:
for (i = 1; i < 100; i++) {
var el = $('#dtt_2597807651112537_table tbody tr')[i - 1];
// store current level
var level = Number($(el).attr('dtt_level'));
// change icon
$(el).find('span.dtt_icon').removeClass('dtt_collapsed_span');
$(el).find('span.dtt_icon').addClass('dtt_expanded_span');
while ($($(el).next()).attr('dtt_level') != null) {
var el = $(el).next();
if ($(el).attr('dtt_level') == (level + 1)) {
// change display
el.removeClass('dtt_collapsed_tr');
el.addClass('dtt_expanded_tr');
} else if ($(el).attr('dtt_level') == level) {
break;
}
}
}
for (i = 1; i < 100; i++) {
// get related table row
var el = $('#dtt_2597807651112537_table tbody tr')[i - 1];
// store current level
var level = Number($(el).attr('dtt_level'));
// change icon
$(el).find('span.dtt_icon').addClass('dtt_collapsed_span');
$(el).find('span.dtt_icon').removeClass('dtt_expanded_span');
while ($($(el).next()).attr('dtt_level') != null) {
var el = $(el).next();
if ($(el).attr('dtt_level') > level) {
// change display
el.addClass('dtt_collapsed_tr');
el.removeClass('dtt_expanded_tr');
// change icon
$(el).find('span.dtt_icon').addClass('dtt_collapsed_span');
$(el).find('span.dtt_icon').removeClass('dtt_expanded_span');
} else if ($(el).attr('dtt_level') == level) {
break;
}
}
};
However, I was wondering if anyone had a nice way to:
1) Get the number of rows that need to be looped through - I just put 100 as a large number to prove my code worked and I don't want to just increase this to an even larger number.
2) Get the class name from the page source - The large number in "dtt_2597807651112537_table" is a report ID generated by the application. This is static for now but I want to eliminate any problems if it changes.
Thanks.
This is all wrong. Well, it's working against how jQuery works, in any case.
jQuery's credo is:
Select elements
Do stuff to them
Drop your loops. You don't need them.
For example. To toggle the icon on all span.dtt_icon in your document, do
var collapsed = true;
$("#dtt_2597807651112537_table span.dtt_icon") // select elements
.toggleClass('dtt_collapsed_span', collapsed) // do stuff to them
.toggleClass('dtt_expanded_span', !collapsed);
or, as a function that can both collapse and expand:
function toggleTree(tree, collapsed) {
$(tree).find("span.dtt_icon")
.toggleClass('dtt_collapsed_span', collapsed)
.toggleClass('dtt_expanded_span', !collapsed);
}
To collapse only the currently expanded ones...
$("#dtt_2597807651112537_table span.dtt_icon.dtt_expanded_span")
.toggleClass('dtt_collapsed_span', true)
.toggleClass('dtt_expanded_span', false);
and so on.
You can boil down your entire code into a few lines that way, and you don't need to write a single loop: Use smart element selection (via jQuery selectors and any of jQuerys find, filter and traversal functions) to single out the elements you want to manipulate and then manipulate them all at once in a single step.
To your second question. There are many ways, pick one:
use known page structure to determine the right table (e.g. $("div.main > table:first") or something to that effect)
use known table contents to determine the right table (e.g. $("table:has(span.dtt_icon)"))
use the table's other classes ($("table.treeReport") maybe?) or for example the table's ID with and a "starts-with" selector ($("table[id^=dtt_]")).
Again it's all about selecting your elements smartly. A dive into the jQuery API documentation, in this case the part about selectors, is recommended.

Jquery mobile interfering with javascript filling select box

I am trying to fill an html select box programmatically using javascript. I have found that although my code is working, jquery mobile is interfering with what displays in the select box. I am setting the selected option, which is working, but the value displayed in the select box is the wrong value. It isn't changing from what I had it originally filled as from the html.
I am linking in: "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css". Is there anyway to get around the jquery? I can't just remove the jquery css. That would break everything on my site, and I don't have time to redo it all.
Here is a jsfiddle of the problem: http://jsfiddle.net/RjXRB/1/
Here is the my code for reference:
Here is my javascript function that fills the select box:
function printCartList(newCart){
// newCart is an optional parameter. Check to see if it is given.
newCart = newCart ? newCart : "a_new_cart_was_not_provided_12345abcde";
// Create a cart list from the stored cookie if it exists, otherwise create a new one.
if($.cookie("carts") != null){
carts = JSON.parse($.cookie("carts"));
}
else{
selectOption = new Object();
selectOption.value = "newuniquecartid12345abcde";
selectOption.html = "***New Cart***";
carts = new Object();
carts.size = 1;
carts.option = new Array();
carts.option[0] = selectOption;
}
// Get the select box
var select = document.getElementById("select_cart");
// Get the number of options in the select box.
var length = select.options.length;
// Remove all of the options in the select box.
while(select.options.length > 0){
select.remove(0);
}
// If there is a new cart, add it to the cart.
if(newCart != "a_new_cart_was_not_provided_12345abcde"){
selectOption = new Object();
selectOption.value = newCart;
selectOption.html = newCart;
carts.option[carts.size] = selectOption;
carts.size++;
}
// Save the cart in a cookie
$.cookie("carts",JSON.stringify(carts));
// Populate the select box
for(var i = 0; i < carts.size; i++){
var opt = document.createElement('option');
opt.value = carts.option[i].value;
opt.innerHTML = carts.option[i].html;
if($.cookie("activeCart") == carts.option[i].value && newCart != "a_new_cart_was_not_provided_12345abcde"){
// Set the selected value
alert(carts.option[i].value);
opt.selected = true;
// I tried changing the value of a p tag inside the default option, but that didn't work
document.getElementById("selectHTML").innerHTML = carts.option[i].html;
}
if(opt.value == "dd"){alert("hi");};
select.appendChild(opt);
}
}
Here is my html:
<form method="POST" name="cartSelectForm" action="home.php">
<select name="cartList" id="select_cart" data-mini="true" onchange="submitCartForm()" data-icon="false">
<option value="newuniquecartid1234567890"><p id="selectHTML">*** New Cart ***</p></option>
</select>
</form>
Any help would be greatly appreciated.
I know this question is about a month old, but I stumbled upon it because I was having the exact same issue. I eventually fixed it by doing this:
After programmatically setting the value, I manually fired the change event on that select box. I guess it forced jQuery mobile to update all of it's enhanced markup related to that element. Slightly annoying, but fortunately very easy to work around.
$("#country").val("US");
$("#country").change();
Hope that helps somebody.

changing text for a selected option only when its in selected mode

I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});

Convert jQuery script to standalone javascript

Is it possible for this jQuery code to run as a standalone javascript? This is the only javascript I'd like to use in my project so I'd prefer not to load the entire jquery library just for this 1k script.
//chris coyier's little dropdown select-->
$(document).ready(function() {
//build dropdown
$("<select />").appendTo("nav.primary");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("nav select");
// Populate dropdowns with the first menu items
$("div#brdmenu ul li a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav.primary select");
});
//make responsive dropdown menu actually work
$("nav.primary select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
I've tried to find previous answers but most questions are for converting to jquery and not vice-versa :)
It is obviously possible to do those things in straight javascript, but there is no way (that I am aware of) to automatically do that conversion. You will have to go through line by line and do the conversion yourself.
Here is something similar to market's answer. I'm assuming you want to get all the links in UL elements inside the brdmenu element. If you only want the first link on the LI elements, just adjust the loop that gets them.
Also, this is not a good idea. Using select elements for links went out of fashion a long time ago, users much prefer real links. Also, when navigating the options using cursor keys in IE, a change event is dispatched every time a different option is selected so users will only get to select the next option before being whisked away to that location. Much better to add a "Go" button that they press after selecting a location.
The main change is to use an ID to get the nav.primary element, which I assume is a single element that you should be getting by ID already.
function doStuff() {
function getText(el) {
return el.textContent || el.innerText;
}
var div, link, links, uls;
// Use an ID to get the nav.primary element
var navPrimary = document.getElementById('navPrimary');
// Create select element and add listener
var sel = document.createElement('select');
sel.onchange = function() {
if (this.selectedIndex > 0) { // -1 for none selected, 0 is default
window.location = this.value;
}
};
// Create default option and append to select
sel.options[0] = new Option('Go to...','');
sel.options[0].setAttribute('selected','');
// Create options for the links inside #brdmenu
div = document.getElementById('brdmenu');
uls = div.getElementsByTagName('ul');
for (var i=0, iLen=uls.length; i<iLen; i++) {
links = uls[i].getElementsByTagName('a');
for (var j=0, jLen=links.length; j<jLen; j++) {
link = links[j];
sel.appendChild(new Option(getText(link), link.href));
}
}
// Add select to page if found navPrimary element
if (navPrimary) {
navPrimary.appendChild(sel);
}
}
window.onload = doStuff;
It's only 28 lines of actual code, which is only 10 more than the original, doesn't require any supporting library and should work in any browser in use (and most that aren't).
Have a go with this.
The one thing I'm leaving out is $(document).ready, but there are a number of solutions for that available on stackoverflow. It's a surprisingly large amount of code!
But the other functionality:
// build the dropdown
var selectElement = document.createElement('select');
var primary = document.getElementsByClassName('primary')[0];
// create a default option and append it.
var opt = document.createElement('option');
var defaultOpt = opt.cloneNode(false);
defaultOpt.selected = true;
defaultOpt.value = "";
defaultOpt.text = "Go to...";
selectElement.appendChild(defaultOpt);
// populate the dropdown
var brdmenuUl = document.getElementById('brdmenu').getElementsByTagName('ul')[0];
var listItems = brdmenuUl.getElementsByTagName('li');
for(var i=0; i<listItems.length; i++){
var li = listItems[i];
var a = li.getElementsByTagName('a')[0];
var newOpt = opt.cloneNode(false);
newOpt.value = a.href;
newOpt.text = a.innerHTML;
selectElement.appendChild(newOpt);
}
// now listen for changes
if(selectElement.addEventListener){
selectElement.addEventListener('change', selectJump, false);
}
else if(selectElement.attachEvent){
selectElement.attachEvent('change', selectJump);
}
function selectJump(evt){
window.location = evt.value;
}
primary.appendChild(selectElement);​
some notes!
We're not looking specifically for nav.primary, we're just finding the first occurrence of something with class .primary. For best performance, you should add an ID to that element and use getElementById instead.
Similarly with the lists in #brdmenu, we look for the first UL, and the first A inside each LI. This isn't exactly what the jQuery does, if you are going to need to iterate more than one UL inside #brdmenu you can use another for loop.
I think that should all work though, there's a fiddle here

Adding value from one list to another depanding on button clicked

I have two multi lists. In first multi list, i got all the attributes of table by using query then now by selecting one attribute from this list, when i click on "ADD" button i want that copy of this attribute should go into another list.
What i have done is i added javascript onclick function for ADD button in that i got the selected value from first multilist. But now I am not getting how to put that value in to second multi list?
What i have done in java script function is:
var index=document.getElementById("List1").selectedIndex;
var fieldval=document.getElementById("List1").options[index].value;
document.getElementById("List2").options[0].value=fieldvalue;
But this is not working. Temporarily I am adding value at first position.
Thanks in advance.
From here:
If you want to move an element from the first list to the second:
var index=document.getElementById("List1").selectedIndex;
var elOpt = document.getElementById('List1').options[index];
var elSel = document.getElementById('List2');
try {
elSel.add(elOpt, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOpt); // IE only
}
If you want to add one:
var index=document.getElementById("List1").selectedIndex;
var elOpt = document.getElementById('List1').options[index];
var elSel = document.getElementById('List2');
var elOptNew = document.createElement('option');
elOptNew.text = elOpt.text;
elOptNew.value = elOpt.value;
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew); // IE only
}

Categories