When a new button is created it isn't being picked up by the rest of the code
var topics = ["dog", "cat", "pangolin", "snake", "bird", "emu", "cow", "hedgehog"]
$(document).ready(function () {
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
});
$("button").click(function() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function(response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
});
});
What I'm trying to do is when the user creates a new button, that button will then work like the premade buttons. The premade buttons are supposed to display a few gifs.
What is happening is that after I create the new button, clicking on that button won't even console log the id of that new button.
Your event listener $("#btnAddSubmit").click worked only with already created buttons. That is means your new buttons will be without this listener. If you want to add listeners to the new buttons, you must do something like:
// We are create event listener as a function for convenient use
var onButtonClick = function () {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
// Your code here...
}
}
$("#btnAddSubmit").click(function() {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// We are remove all button's listeners and at once add new
$("button").off('click').on('click', onButtonClick);
});
// And this code will add your listener as it was originally
$("button").off('click').on('click', onButtonClick);
Be cearful if your buttons have another event listeners. If it exists, you connot use .off(). In that case is correct way will be add listener for a new specific button's id.
Based on your question and the js code provided, i guess this is because the newly added button doesn't get the event.
All events are attached to the dom on page load. The new buttons that are injected to the DOM doesn't get the events. jQuery already did the bindings to DOM elements before the new code was injected. To solve this you have to use '.on() method in jQuery
Something like this
$(document).on('click','your_button_class_here',function(){
dosomething();
});
You're using the ready callback, so all of this runs when the DOM is ready. However, you don't actually create the new button until this ready callback has already run! So when you try to add callbacks with $("button").click(function(){}), you are trying to add that callback to all the buttons on the DOM... but some of the buttons you want to add it to do not exist yet. They won't exists until that first button's click callback is executed! So the first button you make will have the callback attached, but the new ones will not.
Maybe try something like this? I expect something will be wrong with how the value of this works on your click callback, but I think it's a nudge in the right direction.
$(document).ready(function () {
$("#btnAddSubmit").click(function () {
var newAnimal = $("#addInput").val();
topics.push(newAnimal);
newAnimal = newAnimal.toLowerCase();
$("#buttons").append('<button id="gif' + newAnimal + '">' + newAnimal + '</button>');
// be wary of what the value of `this` refers to! it might refer to
// the `this` of the scope in which it was defined!
function gifCallback() {
var currentGif = this.id;
if (this.id != "submit") {
currentGif = currentGif.replace("gif", "");
currentGif = currentGif.toLowerCase();
var topicNum = topics.indexOf(currentGif);
var myUrl = "https://api.giphy.com/v1/gifs/search?q=" + topics[topicNum] + "&api_key=oaPF55NglUdAyYKwDZ0KtuSumMrwDAK9&limit=15";
$.ajax({
method: "GET",
url: myUrl,
}).then(function (response) {
console.log(currentGif);
console.log(response);
$("#gifLocation").empty();
var gifURL = response.data[0].images.fixed_width.url;
console.log(response.data.length);
var gifNum = response.data.length
for (var i = 0; i < gifNum; i++) {
$("#gifLocation").append('<div id=gifDiv' + i + '></div>');
gifURL = response.data[i].images.fixed_width.url;
var gifRateId = "gifRate" + i;
var ratingLocString = '<p id="' + gifRateId + '"></p>'
var ratingLoc = $(ratingLocString);
var rating = response.data[i].rating;
var gifRating = "Rating: " + rating;
$("#gifDiv" + i).append(ratingLoc);
$("#" + gifRateId).text(gifRating);
var gifId = "gif" + i;
var gifImage = $('<img class=gif id=' + gifId + '>');
gifImage.attr("src", gifURL);
$("#gifDiv" + i).append(gifImage);
}
});
console.log(currentGif);
}
};
// reference the new button by its ID and add your desired callback
$("#gif").click(gifCallback)
});
});
When I edit panels name I want to update div content, that will have tab-pane name.
I tried to get the value and change it "onchange", but
I think I did something incorrectly.
http://jsfiddle.net/agata666/5zLmtqby/139/
var $foo = $(".tab-pane");
var $newPanelDefault = $foo.clone();
var hash = 1;
$(".add").on("click", function() {
var $newPanel = $newPanelDefault.clone();
var hashClass = 'zone-panel-' + generateHash();
$newPanel.find(".panel").data('hash', hashClass).attr("href", "#" + (++hash)).text("Zone " + hash);
$newPanel.attr("id", "tab" + hashClass);
var nextTab = $('.tabs li').size()+1;
$('<li class="' + hashClass + '">Zone ' + hash + ' <i class="fas fa-pencil-alt pencil"></i></li>').appendTo('.tabs');
$($newPanel).appendTo('.tab-content');
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
});
var panelDefault = document.querySelectorAll('.panel-default');
var exTabFirst = document.querySelectorAll('.exTabFirst');
var exTabSecond = document.querySelectorAll('.exTabSecond');
var addZoneButton = document.getElementById('add');
function generateHash() {
return Math.random().toString(16).substr(-5);
}
addZoneButton.addEventListener('click', function () {
var randomNumber = generateHash();
panelDefault.innerHTML = 'panel panel-default foo template ' + randomNumber;
exTabFirst.innerHTML = 'exTabFirst ' + randomNumber;
exTabSecond.innerHTML = 'exTabSecond ' + randomNumber;
});
$(".pencil").click(function() {
$(".nav-tabs li.active").attr('contenteditable',$(".nav-tabs li.active").attr('contenteditable')==='true'?'false':'true' );
});
Could you help me?
Alright, so i have textbox where I enter grades, and then they're saved in localstorage and i can see them under my textbox. But if I want to add more text boxes in which i can add more grades, and they will be saved in localstorage but they will be in another array or something how i can do that? I will be grateful for any help.
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var gradeID = "grade-" + i;
$('#gradeList').append("<b id='" + gradeID + "'>" + localStorage.getItem(gradeID) + "</b>, ");
}
$('#clear').click(function () {
localStorage.clear();
});
$('#gradeEntryForm').submit(function () {
if ($('#gradeInput').val() !== "") {
var gradeID = "grade-" + i;
var gradeMessage = $('#gradeInput').val();
localStorage.setItem(gradeID, gradeMessage);
$('#gradeList').append("<b class='task' id='" + gradeID + "'>" + gradeMessage + "</b>, ");
var grade = $('#' + gradeID);
task.slideDown();
$('#gradeInput').val("");
i++;
}
return false;
});
$('#gradeList').on("click", "b", function (event) {
self = $(this);
gradeID = self.attr('id');
localStorage.removeItem(gradeID);
self.remove();
});
});
DEMO
You can set dynamic id to your LocalStorage keys which you can relate to your generated TextBoxes
Something like below
localStorage['grade_' + some_id] = value;
You could use the following example:
document.getElementById("addGrade").onclick = function() {
var gradeCell = document.getElementById("gradeCell");
var input = document.createElement("input");
input.type = "number";
var br = document.createElement("br");
gradeCell.appendChild(input);
gradeCell.appendChild(br);
}
EXAMPLE
I want that user to see an alert whenever he doesn't enter proper Google address (or select from suggestion box) on dynamically added text areas. How can I perform that?
I have tried the following code.
I want that when I add new divs at runtime the auto-complete method should apply on that input field and when the user clicks submit button without selecting any suggested address it should display an alert.
Please help me where am I wrong in my code?
function updateNames() {
var rows = $(".clonedInput");
var index = 0;
rows.each(function () {
var inputFields = $(this).find("input");
inputFields.each(function () {
var currentName = $(this).attr("name");
$(this).removeClass("hasDatepicker");
$(this).removeClass("hasTimepicker");
$(this).attr("name", currentName.replace(/\[(.*?)\]/, '[' + index + ']'));
});
var textareaFields = $(this).find("textarea");
textareaFields.each(function () {
var currName = $(this).attr("name");
$(this).attr("name", currName.replace(/\[(.*?)\]/, '[' + index + ']'));
var places = new google.maps.places.Autocomplete(currName);
var a = places.getPlace();
if (a == null) {
alert('Please Select a valid location');
}
else { }
var currId = $(this).attr("id");
$(this).attr("id", currId.replace(/\[(.*?)\]/, '[' + index + ']'));
});
var numberSpan = $(this).find("span.taskNumber");
numberSpan.html(index + 1);
index++;
});
}
I have created a Check box JQuery Plugin, but when i want to get the value of the check box when selected the check box value always returns false. I have taken out the plugin and used the check box in a raw state but still returns false when check box is selected.
JAVASCRIPT
function DialogWindowDragMediaItems(userPageType, imageParams, idParams) {
idParams = idParams.replace(/~/g, "|")
var divBGContainer = $("<div/>");
var lengthVideos = imageParams.split("~").length - 1;
var divInfoText1 = $("<div/>"); ;
$(divBGContainer).append(divInfoText1);
$(divInfoText1).text("What would you like to do with the videos selected?");
$(divInfoText1).attr("class", "videosselecteddraginfo");
var checkBox1 = $("<input type='checkbox'/>");
$(divBGContainer).append(checkBox1);
$(checkBox1).genCheckBox({ name: 'copymedia', text: 'Move and Copy', checked: true });
$(checkBox1).attr("id", "copymediamoveandcopy");
var checkBox2 = $("<input type='checkbox'/>");
$(divBGContainer).append(checkBox2);
$(checkBox2).genCheckBox({ name: 'copymedia', text: 'Move and Delete' });
var buttonMove = GetDialogWindowButton("Move Items", "DestroyDialogWindowHideTransparent('DialogWindowDragMediaItemsAddID'); WebForm_DoCallback('MainPageControl1','dragmediatomedia~" + userPageType + "~" + idParams + "~' + $('#copymediamoveandcopy').is(':checked'),null,null,null,true)");
CreateGenericWindowDialog($(divBGContainer), "DialogWindowDragMediaItemsAddID", 500, "images/mainpage/dialogwindow/titleimageaddmedia.png", "Move Items", "Cancel", buttonMove, true);
}
function CreateGenericWindowDialog(content, id, width, imageUrl, title, buttonText, button, destroyAndHideTransparent) {
var divContainer = $("<div/>");
$("body").append(divContainer);
$(divContainer).attr("class", "divaddvideomediacontrolcontainer");
$(divContainer).attr("id", id);
var divInnerContainer = $("<div/>");
$(divContainer).append(divInnerContainer);
$(divInnerContainer).attr("class", "divaddvideomediainnercontrolcontainer");
$(divInnerContainer).css("width", width + "px");
var divTopLeftCornerContainer = $("<div/>");
$(divInnerContainer).append(divTopLeftCornerContainer);
$(divTopLeftCornerContainer).attr("class", "divgenericwindowtopleftcorner");
var divTopCenterCornerContainer = $("<div/>");
$(divInnerContainer).append(divTopCenterCornerContainer);
$(divTopCenterCornerContainer).attr("class", "divcentergenericwindow");
$(divTopCenterCornerContainer).css("width", width - 16 + "px");
var divTopRightCornerContainer = $("<div/>");
$(divInnerContainer).append(divTopRightCornerContainer);
$(divTopRightCornerContainer).attr("class", "divgenericwindowtoprightcorner");
var imageTitle = $("<img/>");
$(divTopCenterCornerContainer).append(imageTitle);
$(imageTitle).attr("class", "imagetitledialogwindow");
$(imageTitle).attr("src", imageUrl);
var divTitleContainer = $("<div/>");
$(divTopCenterCornerContainer).append(divTitleContainer);
$(divTitleContainer).attr("class", "divgenericwindowtitlecontainer");
$(divTitleContainer).text(title);
var divControlsContainer = $("<div/>");
$(divInnerContainer).append(divControlsContainer);
$(divControlsContainer).attr("class", "divgenericwindowcontrolscontainer");
$(divControlsContainer).css("width", width - 6 + "px");
$(divControlsContainer).append($(content));
var divBottomLeftCornerContainer = $("<div/>");
$(divInnerContainer).append(divBottomLeftCornerContainer);
$(divBottomLeftCornerContainer).attr("class", "divgenericwindowbottomleftcorner");
var divBottomCenterContainer = $("<div/>");
$(divInnerContainer).append(divBottomCenterContainer);
$(divBottomCenterContainer).attr("class", "divbottomcentergenericwindow");
$(divBottomCenterContainer).css("width", width - 16 + "px");
var divBottomRightCornerContainer = $("<div/>");
$(divInnerContainer).append(divBottomRightCornerContainer);
$(divBottomRightCornerContainer).attr("class", "divgenericwindowbottomrightcorner");
if (destroyAndHideTransparent) {
$(divBottomCenterContainer).append(GetDialogWindowButton(buttonText, "DestroyDialogWindowHideTransparent('" + id + "')"));
}
else {
$(divBottomCenterContainer).append(GetDialogWindowButton(buttonText, "DestroyDialogWindow('" + id + "')"));
}
if (button != null && button.length > 0) {
$(divBottomCenterContainer).append(button);
}
CenterGenericControl(id);
$(divContainer).show();
}
function GetDialogWindowButton(text, linkCall) {
var linkCancel = $("<a/>");
$(linkCancel).attr("class", "linkgenericdialogbutton");
$(linkCancel).attr("href", "javascript:" + linkCall);
$(linkCancel).css("marginTop", 14 + "px");
$(linkCancel).css("marginRight", 10 + "px");
var divCancel = $("<div/>");
$(linkCancel).append(divCancel);
$(divCancel).attr("class", "divlinkaddmediaurlbuttontext");
$(divCancel).text(text);
return linkCancel;
}
JQUERY CHECKBOX PLUGIN
(function($) {
$.fn.genCheckBox = function(settings) {
var def = {
height: 15,
width: 15
};
settings = $.extend(def, settings)
$(this).attr("name", settings.name);
$(this).css("display", "none");
$(this).prop("checked", settings.checked);
var divContainer = $("<div style='clear:left;float:left;padding:10px;'/>");
$(divContainer).insertAfter(this);
var span = $("<span class='checkbox' style='float:left'/>");
if (settings.checked) {
$(span).css("background-position", "0px 17px");
}
else {
$(span).css("background-position", "0px 0px");
}
$(divContainer).append(span);
//$(span).attr("name", settings.name);
var div = $("<div style='float:left;margin-left:10px;disply:block'/>");
$(div).insertAfter(span);
$(div).text(settings.text);
$(span).click(function() {
var position = $(this).css("background-position");
if (position == '0px 0px') {
$(".checkbox").css("background-position", "0px 0px");
var el = document.getElementsByName(settings.name);
for (var i = 0; i < el.length; i++) {
var input = el[i];
$(input).prop("checked", false);
}
$(this).css("background-position", "0px 17px");
var checkBox = $($(this).parent()).prev();
$(checkBox).prop("checked", true);
}
});
}
})(jQuery);
I split the code up from the button click event and then i could retrieve the value from the check box. Weird i still don't understand why it shouldn't work first time.
function DialogWindowDragMediaItems(userPageType, imageParams, idParams) {
idParams = idParams.replace(/~/g, "|")
var divBGContainer = $("<div/>");
var lengthVideos = imageParams.split("~").length - 1;
var divInfoText1 = $("<div/>"); ;
$(divBGContainer).append(divInfoText1);
$(divInfoText1).text("What would you like to do with the videos selected?");
$(divInfoText1).attr("class", "videosselecteddraginfo");
var checkBox1 = $("<input type='checkbox'/>");
$(divBGContainer).append(checkBox1);
$(checkBox1).genCheckBox({ name: 'copymedia', text: 'Move and Copy', checked: true, id: 'copymediamoveandcopy' });
var checkBox2 = $("<input type='checkbox'/>");
$(divBGContainer).append(checkBox2);
$(checkBox2).genCheckBox({ name: 'copymedia', text: 'Move and Delete' });
var buttonMove = GetDialogWindowButton("Move Items", "");
CreateGenericWindowDialog($(divBGContainer), "DialogWindowDragMediaItemsAddID", 500, "images/mainpage/dialogwindow/titleimageaddmedia.png", "Move Items", "Cancel", $(buttonMove), true);
//$(buttonMove).attr("href", "javascript:DestroyDialogWindowHideTransparent('DialogWindowDragMediaItemsAddID'); WebForm_DoCallback('MainPageControl1','dragmediatomedia~" + userPageType + "~" + idParams + "~' + $('#copymediamoveandcopy').is('checked'),null,null,null,true)");
$(buttonMove).attr("href", "javascript:MoveItemsClick('" + userPageType + "','" + idParams + "')");
}
function MoveItemsClick(userPageType, idParams) {
var booleanValue = $('#copymediamoveandcopy')[0].checked;
DestroyDialogWindowHideTransparent('DialogWindowDragMediaItemsAddID');
WebForm_DoCallback('MainPageControl1', 'dragmediatomedia~' + userPageType + '~' + idParams + '~' + booleanValue, null, null, null, true);
}