I have an image and name displaying in a new div. However, I have run into a problem where the next time a person enters name and picture and presses save, their userDiv shows their name plus the previous users name. For example, there are two users: User 1 and User 2. When I select all users and loop through the results the names are logging differently. User one shows up as "User 1", but User 2 shows up as "User 1 User 2". From a quick look around I think it is because innerHTML gets all content from the parent div, but I'm not sure.
var htmlStr="";
var theID;
var theName;
var thePhoto;
var len = results.rows.length;
console.log(len);
for(var i = 0; i < len; i++){
theID = results.rows.item(i).id;
console.log(theID);
theName = results.rows.item(i).username;
htmlStr += theName;
console.log(theName);
thePhoto = results.rows.item(i).imagepath;
console.log(thePhoto);
var imageHold= new Image();
imageHold.src = thePhoto;
console.log("this is the src:"+imageHold.src);
var userDiv = document.createElement("div");//Create the div
userDiv.innerHTML=htmlStr;
userDiv.appendChild(imageHold);
document.getElementById('showUsers').appendChild(userDiv);//append it to the document
userDiv.style.display = 'block';
Remove var htmlStr=""; and declare it within the loop on each iteration. So change
htmlStr += theName;
to
var htmlStr = theName;
and this should resolve your issue
Related
I made a search event handler in my HTML which takes the input and makes the search request to flickr's photo.search by appending the value after "&text=" to search by text. This then displays 7 relevant photos to the search term.
I've added a click event handler to then insert the details to my HTML file to display in a modal when the user clicks on a photo and then display the photo by setting the modal css to display. The issue comes when I try to display the photo's title under the image.
Search button event handler:
//search button function
function searchButton_handler(){
let input = $("#textInput").val();
let htmlStr = "";
$.get(SEARCH_REQ + "&text=" + input, function(data){
nrequest = data.photos.photo.length;
for (let i = 0; i < data.photos.photo.length; i++){
let photoID = data.photos.photo[i].id;
let photoTitle = data.photos.photo[i].title;
let photoObj = {"file": photoID, "title": photoTitle};
search_photos.push(photoObj);
getSizes(photoObj, photoID, photoTitle);
}
});
}
Get sizes from flickr:
//access getSizes array from flickr
function getSizes(photoObj, photoID){
let getSizeReq = GETSIZES_REQ + photoID;
$.get(getSizeReq, function(data){
let photoURL = data.sizes.size[2].source;
photoObj.full = data.sizes.size[data.sizes.size.length-3].source;
photoObj.file = photoURL;
display_search(search_photos);
});
}
Display search results:
//display photos returned from search
function display_search(search_photos){
let htmlStr = "";
for (let i = 0; i < search_photos.length; i++){
htmlStr += `<figure data-full="${search_photos[i].full}"><img src="${search_photos[i].file}" alt="${search_photos[i].title}" width="150" height="150"><figcaption>${search_photos[i].title}</figcaption></figure>`;
}
$("#item2").html(htmlStr);
$('figure').each(function(index){
$(this).click(function(){
$("#modal-container").css("display", "block");
$("#modal-content").attr("src", $(this).attr("data-full"));
})
});
}
Can somebody help me? I've tried everything I could think of and console logging it either returns undefined or an error. Any help would be appreciated, Thanks!
I've been trying to convert this section of script to jQuery instead of vanilla javascript, but I'm not sure how to loop through the elements with jQuery. Basically, I'm grabbing a data attr value from each field to be used as an error message that displays near the field.
This is all inside a click event on the submit button, FYI
What's the jQuery way?
//Set some variables
var invalidFields = $(form).querySelectorAll(':invalid'),
errorMessages = $(form).querySelectorAll('.error-message'),
parent;
// Remove any existing messages
for (var i = 0; i < errorMessages.length; i++) {
errorMessages[i].parentNode.removeChild(errorMessages[i]);
}
//Get custom messages from HTML data attribute for each invalid field
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
//Display custom messages
for (var i = 0; i < invalidFields.length; i++) {
parent = invalidFields[i].parentNode;
parent.insertAdjacentHTML('beforeend', '<div class='error-message'>' +
invalidFields[i].validationMessage +
"</div>");
}
I converted your code one-to-one to jQuery. But there might be other ways, when i will know where form, setCustomValidity and validationMessage is coming from.
var $form = $(form);
// Remove any existing messages
$(".error-message", $form).remove();
// Get custom messages from HTML data attribute for each invalid field
$(".sdForm-input", $form).each(function() {
var message = $(this).attr('data-ErrorMessage');
// i don't know where the 'setCustomValidity' function is coming from
// this is a custom function
$(this)[0].setCustomValidity(message);
});
// Display custom messages
$(":invalid", $form).each(function() {
// i don't know where 'validationMessage' is comig from
// this is a custom property
$(this).parent().append("<div class='error-message'>" + $(this)[0].validationMessage + "</div>");
});
You can simple replace this.
var fields = form.querySelectorAll('.sdForm-input');
for (var i = 0; i < fields.length; i++) {
var message = $(fields[i]).attr('data-ErrorMessage');
$(fields[i]).get(0).setCustomValidity(message);
}
Replace with jQuery way
var fields = form.find('.sdForm-input');
$.each(fields, function(index, el){
var message = $(el).attr('data-ErrorMessage');
$(el).setCustomValidity(message);
});
I want to get the values that were entered by the user from the window prompts, and let them display in paragraph tags on by html page. I thought using document.getElementById("idName").innerHTML would work, but it doesn't show the values that were entered by the user.
Here is the code I have on my JavaScript page. I have called the methods that need to execute on the page. :
var players = [];
var numberOfMoves = 0;
var currentPlayer = 0;
getPlayerNames(); //Get player names
setPlayerInformation(); //Set the names of the players in paragraph tags with id playerOneInformation and playerTwoInformation
function getPlayerNames()
{
players[0] = window.prompt("Please Enter Player 1: ", "");
players[1] = window.prompt("Please Enter Player 2: ", "");
}
function setPlayerInformation()
{
document.getElementById("playerOneInformation").innerHTML = players[0];
document.getElementById("playerTwoInformation").innerHTML = players[1];
}
i
HTML
<div id="notApprovedUsers">
</div><button onclick="approveUsers()">Approve</button>
</div>
i like to get checked users in parameter userList to work with.
here is javascript there me generating list with users and checkboxes.
i like to approve just the checked one's of course!
JavaScript
function getNotAssignedUsers() {
server.getUsersByGroup("1eb33e30-c355-467f-af3c-e7d0b4a1fgt5").then(function (userDetails) {
debugger;
for (var i = 0; i < userDetails.length; i++)
{
var vorname = userDetails[i].firstName;
var nachname = userDetails[i].lastName;
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = "0"+i;
document.getElementById("notApprovedUsers").appendChild(newCheckBox);
var newElement = document.createElement('div');
newElement.id = i;
newElement.className = "notApprovedUsers";
newElement.innerHTML = vorname + " " + nachname;
document.getElementById("notApprovedUsers").appendChild(newElement);
}
});
}
HERE in userList I need to read just a checked users..
function approveUsers(userList)
{
var user1 = document.getElementById("00").checked;
var user2 = document.getElementById("01").checked;
var user3 = document.getElementById("02").checked;
alert(user1 || user2 || user3);
}
You want something like this then. There may be errors as I havent tested
var names = [];
$('input[type=checkbox]:checked').each(function(index, value){
var name = $(value).next("div").html();
names.push(name);
});
Then do something with the names array
Edit - See jsfiddle http://jsfiddle.net/vpg3r/3/
I think the best solution for you here is to use jQuery. You can use something like:
$('#notApprovedUsers input[type=checkbox]:checked')
to get all the elements that are checked, and work with them.
I've created a JSFiddle for you to demonstrate how to implement the behavior that I'm describing. You can see it in this link.
In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?
You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}
jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});