Swapping html table elements (the complete object) in javascript - javascript

EDIT: I just noticed that I'm trying to swap integers because I'm getting the rowIndex. That's not what I want to do. I want to swap objects. However, I don't really know how.
I want to move table elements up and down in a queue by swapping with the element above and the element below respectively. However, my code doesn't work. The following is the JS function for the downButton.
var downButton = document.getElementsByClassName('downButton')[0];
downButton.onclick = function moveDown(currentRow) {
var index = currentRow.parentNode.parentNode.rowIndex;
var nextRow = currentRow.nextElementSibling.parentNode.parentNode.rowIndex;
var temp = index;
index = nextRow;
nextRow = temp;
}
This is the html for the down button:
<button class = "downButton">down</button>
Here's a JSFiddle link for the table: https://jsfiddle.net/Led4b3nw/

Swap innerHTML instead of indexes:
var index = currentRow.parentNode.parentNode;
var nextRow = currentRow.nextElementSibling.parentNode.parentNode;
var temp = index.innerHTML;
index.innerHTML = nextRow.innerHTML;
nextRow.innerHTML = temp;

Related

Keep Javascript constant the same after function is recalled

I am trying to create a dynamic list so when the user performs a search it will repopulate the list. The problem is that I can't seem to make an immutable constant to store the original div content. Every time the function get's called this variable gets reinitialized.
Is there a way to achieve this without using cookies ? Any help is sincerely appreciated. The code is not complete because I couldn't get passed this step but if you think I am totally heading toward the wrong direction please let me know.
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
<script>
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
var newList = '';
var found = false;
function filterPatients(){
var searchQuery = document.getElementById('search');
var query = searchQuery.value;
var listContainer = document.getElementById('patientList');
var patientList = listContainer.getElementsByTagName('li');
for (var i = 0; i < originalList.length; i++){
var link = patientList[i].getElementsByTagName('a');
var link = link[0].text;
/** remove whitespaces for easy comparison **/
link = link.toLowerCase();
query = query.toLowerCase();
link = link.replace(/\s/g, "");
query = query.replace(/\s/g, "");
/** check every character in query **/
if (link.length > query.length && link.substring(0,query.length) == query){
found = true;
newList += '<li>' + patientList[i].innerHTML + '</li>';
}
}
if (found == true){
listContainer.innerHTML = newList;
newList = '';
}
else{
listContainer.innerHTML = "<li>No patient by that name</li>";
}
console.log(frozen);
}
</script>
const originalList = document.getElementById('patientList').getElementsByTagName('li').cloneNode(true);
Make originalList a copy of the element. Currently, you are setting originalList and patientList to be the same list of elements, so changing one will also change the other. Use element.cloneNode(true) to make a deep copy of a DOM element

How to save a HTMLElement (Table) in localStorage?

I've been trying this for a while now and could not find anything online...
I have a project, where tablerows get added to a table. Works fine.
Now I want to save the Table in the localStorage, so I can load it again. (overwrite the existing table).
function saveProject(){
//TODO: Implement Save functionality
var projects = [];
projects.push($('#tubes table')[0].innerHTML);
localStorage.setItem('projects', projects);
//console.log(localStorage.getItem('projects'));
The problem is the Array "projects" has (after one save) 2000+ elements. But all I want is the whole table to be saved to the first (or appending later) index.
In the end I want the different Saves to be listed on a Option element:
function loadSaveStates(){
alert('loading saved states...');
var projects = localStorage.getItem('projects');
select = document.getElementById('selectSave'); //my Dropdown
var length = projects.length,
element = null;
console.log(length);
for (var i = 0; i < length; i++) {
element = projects[i];
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = 'project ' + i;
select.appendChild(opt);
}
}
Can anyone tell me what I am doing wrong?
You can easily do this by jquery, are you interested in this, if yes.. then try following code
For setting the value
$.jStorage.set("projects", $.trim(projects));
For Getting the data
$.jStorage.get("projects");
For deleting the data with key
$.jStorage.deleteKey("projects");
I coose to stay with localStorage, but insted of using an Array I just let the user give every project a name and create a new Item for every Save:
function saveProject(){
//TODO: Implement Save functionality
var pname=prompt("Please enter your project name:","projectname")
var text = $('#mainTable')[0].innerHTML;
//console.log(text);
localStorage.setItem(pname, text);
//console.log(localStorage.key(2));
loadSaveStates();
}
function loadProject(){
var selected = $('#selectSave')[0].selectedIndex
//console.log(selected);
if (localStorage.key(selected) == 'jStorage'){
selected++;
}
var innerHTMLTable = localStorage[localStorage.key(selected)];
//console.log(innerHTMLTable);
$('#mainTable')[0].innerHTML = innerHTMLTable;
updateHandlers();
}
function deleteProject(){
var selected = $('#selectSave')[0].selectedIndex
var pname = $('#selectSave')[0].options[selected].value
$('#selectSave')[0].remove(selected);
localStorage.removeItem(pname);
//console.log(pname);
loadSaveStates();
}

How to get the next element of an array with Jquery onclick

Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});

Jquery ID selector doesnt work with a variable

I've read a billion questions like this, but never found an answer yet.
Anyway, when I type
var variableContainingID = "header";
var div = $("#"+variableContainingID);
It returns 'undefined'
But when I type
var variableContainingID = "header";
var div = $('[id^="'+variableContainingID+'"]');
It works fine.
Any ideas why?
UPDATE
var json = '{"divs":['
var children = $(".parent_container > div");
var idArray = [];
var numArray = [];
for (var x=0; x<children.length; x++) {
var eleid = $(children[x]).attr("id");
idArray.push('"'+eleid+'"');
numArray.push(x+1);
}
var idString = idArray.join(",");
var numString = numArray.join(",");
json += idString;
json += '],"number":['+numString+']}';
var obj = JSON.parse(json);
for (x in obj["divs"]) {
var div = $('[id^="'+obj["divs"][x]+'"]');
}
Do you think the double quotes could be throwing it off?
As you wrote in your question:
var div = $("#"+variableContainingID);
var div = $('[id^="'+variableContainingID+'"]');
These two lines are not identical. The first one, will select an element with id of header. The second one,
selects elements that have the specified id with a value beginning exactly with a given string (header).
So if you have an element like this:
<div id="headerHere"></div>
The first one ($("#"+variableContainingID)) can't select it, but the second one ($('[id^="'+variableContainingID+'"]')) can select that element.
This is because you used ^= in your selector. See jQuery API: Attribute Starts With Selector (name^="value").
It's worth to see all attribute selectors in jQuery.
Attribute Selectors in jQuery

randomize selection and output variable to span tag in javascript

I have this javascript code:
var doNewPoll = function(){
var vacationIndex = Math.round(Math.random(myVacations.length));
var dest1 = myVacations[vacationIndex];
var dest2 = myVacations[vacationIndex];
alert(dest1);
alert(dest2);
}
My 2 questions are:
1) How do I make sure my variables dest1 and dest2 are not the same? I want it to pull 2 different options from the myVacations array.
and 2) I can get the alerts to work, but instead of an alert, I want the results for dest1 and dest2 to appear in the document in span tags id'd Span1 and Span2. I'm just having a brain fart on how to do that.
Thanks!
First, use floor, not round, you don't want your index to be the length :
Math.floor(Math.random(myVacations.length));
Then, the easiest to avoid duplicate is just to loop until the second number is different from the first. This means you must build another index, of course :
var index1 = Math.floor(Math.random(myVacations.length));
var index2 = index1;
while (index2==index1) index2 = Math.floor(Math.random(myVacations.length));
var dest1 = myVacations[index1];
var dest2 = myVacations[index2];
To make the document appear in span, the simplest is to start with the elements yet present :
<span id=d1></span>
<span id=d2></span>
And then to fill them :
document.getElementById("d1").innerHTML = dest1;
document.getElementById("d2").innerHTML = dest2;
// I assume span1 and span2 are the id of those elements
var doNewPoll = function(myVacations, span1, span2){
var vacationIndex1 = Math.round(Math.random(myVacations.length));
var vacationIndex2 = null;
do{
vacationIndex2 = Math.round(Math.random(myVacations.length));
} while (vacationIndex2 == vacationIndex);
document.getElementById(span1).innerHTML = myVacations[vacationIndex1];
document.getElementById(span2).innerHTML = myVacations[vacationIndex2];
}

Categories