jQuery append not completing before next statement? - javascript

I have a survey-type form that's being populated from a web database on the client. I can populate the questions fine, but then I try to go through and trigger the click event where there is an existing answer (edit scenario), I'm finding that the new elements are not yet in the DOM so this doesn't work. Here's the code:
$(function() {
var db = openDatabase(...);
db.transaction(function(tx) {
tx.executeSql("select ....", [surveyId], function(tx, results) {
var items = "", answers = [];
for (var i = 0; i < results.rows.length; i++) {
var id = results.rows.item(i).id;
items += "<div><input type='radio' name='q-" + id + "' id='q-" + id + "-1' /><label for='q-"+id+"-1'>Yes</label><input type='radio' name='q-" + id + "' id='q-" + id + "-2' /><label for='q-"+id+"-2'>No</label></div>";
if (result.rows.item(i).answer) {
answers.push('#q-'+id+'-'+results.rows.item(i).answer);
}
}
$('#questions-div').append(items);
$.each(answers, function(i, e) { $(e).click(); });
});
});
});
Any tips how I can make this work, or better generally?

I think here:
answers.push('#q-'+id+'-'+result);
You meant to push this:
answers.push('#q-'+id+'-'+result.rows.item[i].answer);
Otherwise you're getting '#q-XX-[object Object]' as a selector, where I think you're after the 1 or 2 version of '#q-XX-1'.

I suspect this is actually a race condition. My bet is that if you execute your each statement after a tiny delay, things will work as expected. Is so, the reason for this is that you can't be 100% sure when the browser will actually get around to updating the DOM when you programmaticallly insert new elements. I'm not sure what the best solution would be: if you were attaching events, I'd say you should do it at the same time you are building the elements; but if you are triggering the clicks, I'm leaning toward just continually testing for the existance of the elements and then triggering the clicks as soon as you know they are there.

So I came up with a solution:
I replaced the line items += "<div> ...." with
var item = "<div><input type='radio' name='q-" + id + "' id='q-" + id + "-1' ";
if (results.rows.item(i).answer == 1) item += "checked ";
item += "/><label for='q-"+id+"-1'>Yes</label><input type='radio' name='q-" + id + "' id='q-" + id + "-2' ";
if (results.rows.item(i).answer == 2) item += "checked ";
item += "/><label for='q-"+id+"-2'>No</label></div>";
items += item;
... which means I no longer need the answers array or to trigger click events on the radio buttons.
I was hoping for something a bit neater, but this seems to work OK. Thanks #Nick Craver & #Andrew for helping me arrive at it!

Related

Enable/Disable an HTML Element With Dynamically Generated Names/Tags

I have a table in HTML where the ID is dynamically generated from a row counter:
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option onclick=\"sphereSelect()\" value=\"sphere\">Sphere</option>"
+ "<option onclick=\"cylinderSelect()\" value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude" + rowCount + "\"</td>"
+ "<td><input type=\"text\" name=\"maxAlt\" id=\"maxAltitude_" + rowCount + "></td>"
+ "</tr>"
I need maxAltitude to become disabled for input when sphere is selected. When cylinder is selected, it should become enabled for input.
Every example I find is pretty simple but requires knowing exactly what the ID is, where in my code it is dynamically generated. This is an example of what I'm finding:
$(#maxAltitude).prop("disabled", true);
How can I do this when maxAltitude will be something more like: maxAltitude_10? There may be 1-n rows in a table, and I need to specifically disable the max altitude in the row where the dropdown select was changed.
I've tried jQuery and javascript but can't seem to find a good way to do this:
<option onclick="shapeSelect()" value="sphere">Sphere</option>
<option onclick="shapeSelect()" value="cylinder">Cylinder</option>
function shapeSelect() {
var shapeSelects = document.getElementsByName("shapeSelect");
var maxAlts = document.getElementsByName("maxAlt");
for(var i = 0; i < shapeSelects.length; i++) {
switch(shapeSelects[i].value) {
case "sphere":
maxAlts[I].disabled = True;
break;
case "cylinder":
maxAlts[i].disabled = False;
}
}
}
With the above code I get: SyntaxError: unexpected token: identifier whenever shapeSelect() is fired.
I've modified the code as follows:
<table class="myTable" id="myTable"></table>
$(table).find('tbody').append("<tr>name=\"tableRow\"</tr>"
+ "<td>"
+ "<select id=\"shapeSelect_" + rowCount + "></td>"
+ "<option value=\"sphere\">Sphere</option>"
+ "<option value=\"cylinder\">Cylinder</option>"
+ "</select>"
+ "</td>"
+ "<td><input type=\"text\" id=\"altitude_" + rowCount + "\"</td>"
+ "<td><input class=\"maxAltitudeInput\" type=\"text\" id=\"maxAltitude_" + rowCount + "\" disabled></td>"
+ "</tr>"
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
And still nothing happens when I change the shape selector dropdown.
EDIT:
Apologies on the naming mismatches. My dev machine is on an airgapped network and I was hand jamming the post here on Stack Overflow. The rowCount variable was being created and incremented in another function. I was trying to only put relevant code in the post for brevity.
I was missing a class from shapeSelector. That was the missing link. It works now!
jQuery actually makes this really easy by binding this to whichever element triggered an event.
For instance, instead of writing a generic function for when that value changes, you could use jQuery to bind an event listener to them:
$('#myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
}
You'll notice a few things in this snippet:
The element we are binding the listener to is the table, not the individual row. That's because the row is dynamic, and we don't want to have to keep adding listeners every time we add a row. Instead we add it to the parent which is stable, but then we specify that we are interested in its children that match ".shapeSelector"
The listener relies on class names, not IDs, since we want to match multiple copies of them, not just a specific one. So you'd need to add those class names or a similar way of matching more than one item
Inside the callback function that runs, you'll notice a couple uses of this. jQuery has bound that to the element that triggered the event listener, in this case, the <select> control. So when we use this, we have to think of it from that perspective. We can get its value by $(this).val(), we can find its parentt with $(this).parent(), etc. In this case, I'm travelling up to the nearest tr, then from there down to that tr's input that I want to disable. You'd need to adjust a little depending on your dom.
Also note that this is a DOM element, not a jQuery result. That's why when we want to run more jQuery commands on it, we have to put it in $() again.
That's how I'd approach it. We don't have your entire code here, so you'll have to adjust a bit, but hopefully that pushes you off in the right direction.
EDIT
To be honest, there were a lot of naming mismatches and things that didn't line up. For instance, you were attempting to append onto a tbody tag, but that tag didn't exist. You were using a rowCount variable, but didn' ever set that up or increment it. The select tag sill didn't have the class name you were trying to use.
I suggest you look at your code piece by piece, ask yourself what you're telling the browser to do, and then do that instruction in your mind to make sure the computer can do it.
HTML:
<table class="myTable" id="myTable"><tbody></tbody></table>
JavaScript:
var rowCount = 0;
function addRow(){
$('.myTable tbody').append(`<tr name="tableRow">
<td>
<select class="shapeSelector" id="shapeSelect_${rowCount}">
<option value="sphere">Sphere</option>
<option value="cylinder">Cylinder</option>
</select>
</td>
<td><input type="text" id="altitude_${rowCount}" /></td>
<td><input class="maxAltitudeInput" type="text" id="maxAltitude_${rowCount}" disabled></td>"
</tr>`);
rowCount++;
}
$('.myTable').on('change','.shapeSelector',function(){
var shouldDisableInput = $(this).val() === 'sphere';
$(this).closest('tr').find('.maxAltitudeInput').attr('disabled',shouldDisableInput);
});
addRow();
addRow();
addRow();
https://jsfiddle.net/32vnjq81/

LocalStorage element not corresponding with visual element after moving

I created a note-taking front end page which saves the data from text field into the localStorage. The problem occurs when the user deletes one field using the Delete button, which corresopndents to DeleteT function.
For example if we have three textareas with id txt1, txt2, txt3 they apper with the sames names in the localStorage. After the user deletes for example txt2 using the Delete button, in the local Storage the left ones are txt1 and txt3 but on the next reload there are two textareas with id txt1 and txt2 because in the localStorage the number of textareas is saved by key AllNum. The data from txt3 in the localStorage should go to txt2 in the DOM on the page.
The problematic functions:
// Deletes textelemnt
function DeleteT(num) {
localStorage.removeItem("txt" + num);
localStorage.removeItem("h" + num);
console.log('del');
i=i-1;
var now = localStorage.getItem("AllNum");
if((now-1)<0){
now=0;
localStorage.setItem("AllNum", (0));
}else{
localStorage.setItem("AllNum", (now-1));
}
$("div.textarea" + num).remove();
}
//Loads all the text elemnts with a for loop until the number of areas is reached
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea' + i + '"><input onkeyup="save()" id="h' + i + '"></input><textarea onkeyup="save()" id="txt' + i + '"></textarea></br><button onClick="cut(txt' + i + ')" class="f b">Cut</button> <button onClick="copy(txt' + i + ')" class="f b">Copy</button> <button onClick="speak(txt' + i + ')" class="f b">Speak</button> <button onClick="download(' + i + ')" class="f a">Save</button><button onClick="textFull(' + i + ')" class="f">Fullscreen</button> <button onClick="DeleteT(' + i + ')" class="f">Delete</button> </div>');
document.getElementById('txt' + i).innerHTML = localStorage.getItem("txt" + i);
document.getElementById("h" + i).setAttribute('value', localStorage.getItem("h" + i));
}
}
}
https://codepen.io/abooo/pen/NoqOXX?editors=1010
To experience the problem create three textareas using the + button. Then Enter data in the them. After this delete the latter. Finally reload the page and make sure the two textreas appeared. You can see the data from the second one is missing replaced with null value. How to fix this issue?
The result
LocalStorage values
The value "AllNum" only stores total number of items; it does not contain any information about which items were there before reloading. So in first load, if you add 3 items and remove the 2nd, your local storage will have "AllNum" equal 2, and the next time it loads, your load() function will iterate from 1 to 2, looking for data of text1 and text2. That's why only 1st item displays correctly.
Another problem that you might notice after fixing the above issue is that the iteration is not good for unique id; a simple test can prove it: you add 3 items, remove the 2nd - now you have text1 and text3 in localStorage, and AllNum is 2. If you add one more, the newest item will have id as 3 and all its data will be written on top of the existing text3 and h3.
2 suggestion for your code:
Use something else as unique id instead of iteration number. Use Math.random(), for example.
Store all your unique ids in localStorage, not AllNum. Rewrite your code to add and delete unique ids from localStorage.
A small example of how to modify the 2 function add() and save():
function add() {
var newId = Math.random();
// your render logic here. Replace i with newId
save(newId);
}
function save(newId) {
localStorage.setItem("txt" + newId, document.getElementById('txt' + a).value);
localStorage.setItem("h" + newId, document.getElementById('h' + a).value);
var allIds = JSON.parse(localStorage.getItem('AllIds'));
allIds.push(newId);
localStorage.setItem("AllIds", JSON.stringify(allIds));
}

How can I append to a select drop down that lives on another page?

I'm working on creating a service that allows you to create team or user based challenges. Using HTML 5 specifications to design the page, I've run into a bit of an issue appending to a drop down list that resides in another page. The entirety of functionality lives within two pages, mainly by making AJAX calls to other pages. There's a little function that appends 2 properties of a team to a drop down list, but I can't seem to get it to work properly.
Code:
var teams = $.parseJSON(getAllTeams());
$('#multiPurpose').load('allTeams2.html #teamSelect');
for (i = 0; i < teams.length; i++) {
var team = $.parseJSON(getTeam(teams[i]));
if (team.ownerID === userID) {
$(
"<option value='" + team.teamID + "'>" + team.teamName
+ "</option>").appendTo('#teamSelection');
}
}
}
The #teamSelection is contained within the #teamSelect div. Any help would be great.
Adding a callback function within .load() will solve the problem. Basically, you're telling it to load everything within that div before running the for loop.
$('#multiPurpose').load(
'allTeams2.html #teamSelect',
function() {
for (i = 0; i < teams.length; i++) {
var team = $.parseJSON(getTeam(teams[i]));
if (team.ownerID === userID) {
$(
"<option value='" + team.teamID + "'>"
+ team.teamName + "</option>")
.appendTo('#teamSelection');
}
}
});

JavaScript selectAll\deselectAll checkboxes function doesn't work on IE8

I have a Webscript (.js file) developed for an Alfresco application. It handles a button that displays a form aimed at selecting members which have subscribed to an Alfresco space, in order to send them a mail.
All the checkboxes are generated dynamically with the subscribers names.
You can check any member you want and you also have a special checkbox that enables you to select or deselect all the members.
This specific checkbox works properly on Chrome and Firefox.
However, when you check it on Internet Explorer 8, none of the members are selected or deselected, whether they names are check or not.
Here is the code sample of the form generation and of the onClick functions triggered when you check the checkbox :
updateMembersList : function TS_updateMembersList(containerId)
{
var div = Dom.get(containerId);
div.innerHTML = "<div class=\"memberDiv\">" +
"<input type=\"checkbox\" id=\"selectDeselectAllCb\" checked=\"true\" onchange=\"YAHOO.Bubbling.fire('selectDeselectAllChanged')\" class=\"memberCb\"/>" +
"<label for=\"selectDeselectAllCb\" class=\"memberLabel\">" +
this.msg('label.selectDeselectAll') + "</label>" +
"</div>";
for (var i=0; i<this.members.length; i++)
{
var member = this.members[i];
var avatar = Alfresco.constants.URL_CONTEXT + "/components/images/no-user-photo-64.png";
if (member.authority.avatar && member.avatar != "")
{
avatar = Alfresco.constants.PROXY_URI + member.authority.avatar + "?c=force";
}
div.innerHTML += "<div class=\"memberDiv\">" +
"<input type=\"checkbox\" id=\"cb_" + member.authority.userName + "\" checked=\"true\" onchange=\"YAHOO.Bubbling.fire('selectDeselectMemberChanged')\" class=\"memberCb\"/>" +
"<label for=\"cb_" + member.authority.userName + "\" class=\"memberLabel\">" +
member.authority.firstName + " " + member.authority.lastName + "</label>" +
"</div>";
}
},
selectDeselectAllChanged: function selectDeselectAllChanged(){
var selectDeselectAllCb = Dom.get('selectDeselectAllCb');
var checked = selectDeselectAllCb.checked;
console.log("Select All");
var cbs = YAHOO.util.Selector.query("input[id^='cb_']");
for (var i=0, j=cbs.length; i<j; i++)
{
var cb = cbs[i];
cb.checked = checked;
}
},
selectDeselectMemberChanged: function selectDeselectMemberChanged(){
var selectDeselectAllCb = Dom.get('selectDeselectAllCb');
var cbs = YAHOO.util.Selector.query("input[id^='cb_']");
var firstChecked;
if (cbs[0] != null){
firstChecked = cbs[0].checked;
}
for (var i=0, j=cbs.length; i<j; i++)
{
var cb = cbs[i];
if (cb.checked === firstChecked){
continue;
}
else{
selectDeselectAllCb.checked = false;
return;
}
}
selectDeselectAllCb.checked = firstChecked;
},
At the beginning, I thought that the query wasn't supported by IE8, but it's not the case.
Such a syntax is supported by IE7 and more recent versions.
Try removing console.log("Select All"); and replace it with Alfresco.logger.debug("Sellect All");
IE doesn't like console object.
Also, run your code on jslint - if you have an invalid json there somewhere, IE stops.
Also, try running IE in developer mode - set it up to show you script errors and you'll know where it stops.
I've solved the problem. I've replaced the onchange event handler by an onclick event handler. Indeed, onchange has a random behaviour on Internet Explorer, whereas onclick works fine in most of the case.
Thanks for the help.

Programmatically creating <DIV>s and problems arise

I am new to javascript and have written a piece of code (pasted below). I am trying to build a little game of Battleship. Think of that game with a grid where you place your ships and start clicking on opponents grid blindly if it will hit any of the opponents ships. Problem is I need to get a function called with the ID of the DIV to be passed as a parameter. When the DIV is programmatically created like below, what will work. This? : --///<.DIV id='whatever' onclick='javascript:function(this.ID)' /> .. I saw sth like that somewhere .. this inside html :S
the js code is: (there are two grids, represented by the parameter - who - ... size of grid is also parametric)
function createPlayGround(rows, who)
{
$('#container').hide();
var grid = document.getElementById("Grid" + who);
var sqnum = rows * rows;
var innercode = '<table cellpadding="0" cellspacing="0" border="0">';
innercode += '<tr>';
for (i=1;i<=sqnum;i++)
{
var rowno = Math.ceil(i / rows);
var colno = Math.ceil(i - ((rowno-1)*rows));
innercode += '<td><div id="' + who + '-' + i +'" class="GridBox'+ who +'" onmouseover="javascript:BlinkTarget(' + i + ',' + who +');" onclick="javascript:SelectTarget('+ i + ',' + who +');" >'+ letters[colno - 1] + rowno +'</div></td>';
if (i % rows == 0)
{
innercode += '</tr><tr>';
}
}
innercode += '</tr></table>';
grid.innerHTML = innercode;
$('#container').fadeIn('slow');
}
It sounds like what you really want is to get the div element that was just clicked on. If you just want to return the div that was clicked on, all you have to do is use "this":
<div id="whatever" onclick="function(this)"></div>
If you're actually more interested in getting the id of the div clicked on, you can do this:
<div id="whatever" onclick="function(this.id)"></div>
However, it sounds like you just want the id so that you can get the div using getElementById, and the first code snippet will help you skip that step.
Instead of creating the inner html from strings you can create it with jQuery and add event listeners like so:
$("<div></div>")
.click(function(e) {
selectTarget(i, who);
})
.appendTo(container);

Categories