i don't seem to find any way to work this out..so i guess i m going to need some help..
i m making a phonegap application in which i have an sqlite database.I perform a query and get the results in a dynamically created div from the database, the thing is that i want for each record that i extract to make the div that contains it, as a button with an editable role..
for instance lets say that i have a db with these columns id option1 option2 and i have three records..
this means that i will have three divs
i want, each div to be a button so that if user clicks on it to be able to perform a delete (or edit/update) query without being worried about id
for instance, if he selects div2 do perform a query that will delete second record..
my code so far..
for (var i = 0; i < len; i++) {
var test1 = results.rows.item(i).option1;
var d = new Date();
d.setTime(results.rows.item(i).date);
var newLI = document.createElement("LI");
newLI.className = lt;
newLI.id = results.rows.item(i).id;
var container = ("<div id=\"" + results.rows.item(i).id + "\" class=\"test\"><div id=\"text\">option1</div><div id=\"data\">" + test1 + "</div></div>");
newLI.innerHTML = cont;
var gl = document.getElementById("sqltest");
gl.appendChild(newLI);
}
for (var i = 0; i < len; i++) {
var divid = "#" + results.rows.item(i).id;
$(divid).on("click", function () {
alert(divid);
})
}
<ul id="sqltest"></ul>
problem with above code, is that although each div gets the correct id, when i click on it, i always get the same result for instance #1 although i may have 3 divs..
instead of having as a result
div1 alert #1 div2 alert #2
i get
div1 alert #1 div2 alert#1
I've used alert just to simplify it, instead of alert there will be DELETE from SQLDB WHERE id=results.rows.item(i).id;
You are retreiving always the same 'divid' variable, because of the way javascript scope and closures work. This is a very common mistake. You can google "javascript closure infamous loop" to get more information about this.
You should replace your for with this:
for (var i = 0; i < len; i++) {
(function () {
var divid = "#" + results.rows.item(i).id;
$(divid).on("click", function () {
alert(divid);
});
})();
}
That way, the variable divid is declared in different scopes each time.
I didn't understand if that is the only problem you are having.
Related
READ THE EDIT AT THE BOTTOM! :)
I am making a little website where the user can fill in multiple text boxes, and when they come back later, their text boxes come back. (Pretty much a terrible helpdesk system using localstorage).
I have three fields the user can fill out, then when the fields are submitted they should appear below, in a div. Currently i am only able to get the first field to be shown, as i append it to a static div, but i want to append the rest of the fields to the first one. This wouldnt be too hard, but i cant seem to append a child to a div that doesnt have a set ID (without somehow hardcoding it).
I have tried things like
divAId + i.appendChild(divB)
And
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
, but nothing seems to work.
Here is the code in question:
gradStorages = JSON.parse(localStorage.getItem('gradStorages'));
var iFeil = 0;
function feilDivCreate(){
const divF = document.createElement("div");
divF.className = "feilDiv";
divF.id = "feilDivId" + iFeil;
listIdIncrement();
divF.appendChild(document.createTextNode(set1));
textContainer2.appendChild(divF);
iFeil += 1;
}
var iOffer = 0;
var feilIdNumber = "feilId";
function offerDivCreate(){
const divO = document.createElement("div");
divO.className = "offerDiv";
divO.id = "offerDivId" + iOffer;
listIdIncrement();
divO.appendChild(document.createTextNode(set1));
feilIdNumber + iOffer.appendChild(divO);
iOffer += 1;
console.log(feilIdNumber + "TATATATAT");
}
var set1 = "set1 Not Defined";
var set2 = "set2 Not Defined";
var set3 = "set3 Not Defined";
function extract(){
for(let i = 0; i < feilStorages.length; i++){
set1 = feilStorages[i];
set2 = offerStorages[i];
set3 = gradStorages[i];
feilDivCreate();
offerDivCreate();
gradDivCreate(); // same as offerDiv
}
}
(can add more, or make a jsfiddle if needed.)
I need a way to append offerDiv to feilDiv, but its not so simple because feilDiv's id is feilDivId + i where i goes up by one for each new feildiv added.
Any tips for how i can achieve this?
EDIT: Here is a simplified version, showing all the code necessary to understand what im trying to do. https://codepen.io/kossi1337/pen/xxKPRvv
Might be easier to just make a new question with all the new code, but im not too sure if that allowed.. Let me know if i have to change anything about my question :)
In this code:
var divAIdNumber = divAId + i;
divAIdNumber.appendChild(divB);
It seems like you are trying to append an element to the Integer value you just created by adding i to some number. You need to grab the parent node, either via document.querySelector or using jQuery, then append to the parent. The browser has no idea what to do when you try to append markup to a number. It expects a DOM location that it will be appended to.
It should be like this:
var divAIdNumber = divAId + i;
var html = "<div class='" + divAIdNumber + "'> Content here </div>";
var element = document.querySelector(".my-element");
element.appendChild(html);
I am interested in when choosing an option from a drop-down list the value of the selected option that stá visualiando in a < div > that value is captured in a javascript variable. The list referred to originated in an AJAX routine that queries a database. On page php , where there is a div shown above . I need your help to take this value from the list.
Assuming that you meant for your question read the way RightClick explained it in the comments, you need something like this:
window.onload = function() {
var ids = $('.dropdown').map(function(){
return this.id;
}).get();//Get array of ids
var options = document.getElementsByClassName('dropdown');
for(var i = 0; i < options.length; i++) {
var anchor = options[i];
anchor.onclick = function() {
var h = new XMLHttpRequest();
h.open("GET", "/myDB?q="+ids[i], true);//This should be synchronous
h.send();
document.getElementById("responseDiv").innerHTML = h.responseText;
}
}
}
`
Is this possible? Or is there a way to tack on and ID to an existing div?
This is my code. I can't get the code to work using classes, but I found when I used getElementById and changed the div to an ID, that it did. But I have a ton of already posted stuff so it would take forever to go through all those posts and change it manually to an ID.
Can I incorperate JQuery in this and still have it work? I tried that with something I stumbled across but it didn't work so I removed it. I don't remember what it is now though. :S
<div id="imdb" class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnum = document.getElementsByClassName("imdb");
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnum + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
window.onload = imdbdiv();
</script>
Can anyone help. I cannot for the life of me figure this out.
JsFiddle
Your problem was, you were appending the collection returned by document.getElementsByClassName instead of looping through the elements in the collection. You can verify this by looking at the href property of the link in your jsFiddle. You must loop through the values, then access the data in their innerHTML property.
You can use document.querySelectorAll to get a list of all elements matching a certain CSS selector, in your case .imdb. This is more flexible, in case you want to select elements with more than one class. I've pasted the code from the updated jsFiddle below.
function imdbdiv() {
var imdbMain = "http://www.imdb.com/title/",
end = "/#overview-top",
imdbValueDivs = document.querySelectorAll('.imdb'),
length = imdbValueDivs.length,
// Iterator values
i,
newDiv,
newLink;
// Loop over all of your link value containers
for (i = 0; i < length; i++) {
// Create the container
newDiv = document.createElement('div');
// Create the new link
newLink = document.createElement('a');
newLink.href = imdbMain + imdbValueDivs[i].innerHTML + end;
newLink.innerHTML = "My favorite film";
// Add the link to the container,
// and add the container to the body
newDiv.appendChild(newLink);
document.body.appendChild(newDiv);
}
}
window.onload = imdbdiv();
If you have many such divs on your page, then it could be like this:
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<div class="imdb">tt2382396</div>
<script>
function imdbdiv() {
var imdbmain = "http://www.imdb.com/title/";
var end = "/#overview-top";
var idnums = document.getElementsByClassName("imdb");
for (var i =0; i < idnums.length; i++) {
var newdiv = document.createElement("div");
var done = "<a href='" + imdbmain + idnums[i].innerText + end + "'>IMDB</a>";
newdiv.innerHTML = done;
document.body.appendChild(newdiv);
}
}
window.onload = imdbdiv();
</script>
See jsfiddle
UPDATE:
The following string was incorrect:
window.onload = imdbdiv;
Okay, so your question is a little bit unclear.
The way I understood your question is that you have a whole bunch of div elements with class attribute and what you want is to simply copy the class value to the id attribute of the div elements.
If that's correct then try something like this with jquery:
<script>
$(document).ready(function(){
$(".imdb").each(function(imdbDiv){
var classValue = imdbDiv.attr("class");
imdbDiv.attr("id", classValue);
});
});
</script>
I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))
i am using a javascript where in i am creating multiple div (say 5) at runtime, using javascript function, all the divs contain some text, which is again set at runtime, now i want to disable all the divs at runtime and have the page numbers in the bottom, so that whenever user clicks on the page number only that div should get visible else other should get disable, i have created a function, which accepts parameter, as page number, i enable the div whose page number is clicked and using a for loop, i disable all the other divs, now here my problem is i have created two functions, 1st (for adding divs and disabling all the divs except 1st) and writing content to it, and other for enabling the div whose page number is clicked, and i have called the Adding div function on body onload; now first time when i run, page everthing goes well, but next time when i click on any of the page number, it just gets enabled and again that AddDiv function, runs and re-enables all the divs..
Please reply why this is happening and how should i resolve my issue...
Below is my script, content for the div are coming using Json.
<body onload="JsonScript();">
<script language="javascript" type="text/javascript">
function JsonScript()
{
var existingDiv = document.getElementById("form1");
var newAnchorDiv = document.createElement("div");
newAnchorDiv.id = "anchorDiv";
var list = { "Article": articleList };
for(var i=0; i < list.Article.length; i++)
{
var newDiv = document.createElement("div");
newDiv.id = "div"+(i+1);
newDiv.innerHTML = list.Article[i].toString();
newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a> ";
existingDiv.appendChild(newDiv);
existingDiv.appendChild(newAnchorDiv);
}
for(var j = 2; j < list.Article.length + 1; j ++)
{
var getDivs = document.getElementById("div"+j);
getDivs.style.display = "none";
}
}
function displayMessage(currentId) {
var list = {"Article" : articleList}
document.getElementById("div"+currentId).style.display = 'block';
for(var i = 1; i < list.Article.length + 1; i++)
{
if (i != currentId)
{
document.getElementById("div"+i).style.display = 'none';
}
}
}
</script>
Thanks and Regards
Try adding return false; to the page link to prevent the page from being reloaded.
newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+");return false;'>"+(i+1)+"</a> ";
Your page links are reloading the page. You just have to change one line and your script works ok.
// change
newAnchorDiv.innerHTML += "<a href='' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a> ";
//to
newAnchorDiv.innerHTML += "<a href='#' onclick='displayMessage("+(i+1)+")'>"+(i+1)+"</a> ";