function createList() {
var list = '';
var listID;
$.each(obj_JSON.colors, function(index, value) {
listID = "clr_" + index;
list = list + "<div id=" + listID + " alt='" + obj_JSON.colors[index].name + "'></div>"
clrList.html(list);
updateListColours(listID);
});
}
function updateListColours(x) {
$('#' + x).css({"background-color":"rgb(255, 0, 0)", "height":"25px", "width":"25px"});
}
When I watch it get created. The first div gets the style applied to it. Then the second gets created and the style is wiped from the first div and applied to the second and it goes on until the list is complete...
Why is this happening and how can I apply the style to each div? Expecting answer that shows i've done something really stupid as usual
Because this line clrList.html(list);, you are removing the previous element then add new created.
Instead, do it with:
$.each(obj_JSON.colors, function(index, value) {
listID = "clr_" + index;
list = "<div id=" + listID + " alt='" + obj_JSON.colors[index].name + "'></div>"
clrList.append(list);
updateListColours(listID);
});
There's a much easier solution:
function createList() {
$.each(obj_JSON.colors, function() {
var d = document.createElement('div');
d.setAttribute("alt",this.name);
d.className = "listcolour";
clrList.appendChild(d);
// ^ assumes `clrList` is a DOM node, not a jQuery object
});
}
And CSS:
.listcolour {
width: 25px;
height: 25px;
background-color: #f00;
}
Related
I have a function that Creates new items and allows you to Delete, Update and Save the inputs on these items using localStorage
However, if I have more than one item and then update and save the changes, those changes are applied over all items.
The problem is encountered at the $(".save").click(function() but I'm not sure I have set up my .items with a proper array.
Since I use localStorage the working code can be found in the pen below:
https://codepen.io/moofawsaw/pen/NoBQKV
window.localStorage.clear();
//create localStorage item
if (!localStorage.getItem("_storage")) {
localStorage.setItem("_storage", "");
}
//set data to localStorage function
function saveData() {
localStorage.setItem("_storage", $("#content").html());
}
// Open the create dialgoue:
$(".add").on("click", function() {
$(".create").toggle();
});
//Save the entered inputs and post the item:
$(".post").click(function() {
var id = $(".createtext").val();
var createtitle = $(".createtitle").val();
var item = "";
if (id[0]) {
for (var i = 0; i < id.length; i++) {
item += "<div>" + id[i] + "</div>";
}
} else {
item = "<div>Click update to add a card</div>";
}
$("#content").append(
'<div class="item">' +
'<div class="title">' +
createtitle +
"</div>" +
"<div class='text'>" +
id +
"</div>" +
'<button class="delete">Delete</button>' +
'<button class="update">Update</button>' +
"</div>"
);
$(".createtitle").val("");
$(".createtext").val("");
$(".create").toggle();
saveData();
});
//Close out of creating a new item
$(".close").click(function() {
$(".createtitle").val("");
$(".createtext").val("");
$(".create").toggle();
});
//Get inputs and open edit window to update the items:
$("#content").on("click", ".update", function() {
var item = $(this).closest(".item");
$(".updatetext").val(
$(this)
.closest(".item")
.find(".text")
.text()
);
$(".updatetitle").val(
$(this)
.closest(".item")
.find(".title")
.text()
);
$(".edit").toggle();
});
//Save changes and update the items (error:changes all items when clicked):
$(".save").click(function() {
var id = $(".updatetext").val();
var title = $(".updatetitle").val();
var item = "";
if (id[0]) {
for (var i = 0; i < id.length; i++) {
item += "<div>" + id[i] + "</div>";
}
} else {
item = "<p>Click edit to add a card</p>";
}
$(".item").each(function() {
$(this).html(
'<div class="title">' +
title +
"</div>" +
"<div class='text'>" +
id +
"</div>" +
'<button class="delete">Deleted(2)</button>' +
'<button class="update">Updated(2)</button>'
);
});
$(".updatetext").val("");
$(".updatetitle").val("");
$(".edit").toggle();
saveData();
});
//Discard any of these changes:
$(".discard").click(function() {
$(".updatetext").val("");
$(".updatetitle").val("");
$(".edit").toggle();
});
//Delete an item:
$("#content").on("click", ".delete", function() {
$(this)
.closest(".item")
.remove();
saveData();
});
$(function() {
if (localStorage.getItem("_storage")) {
$("#content").html(localStorage.getItem("_storage"));
}
});
Point is, you call .each() in your update callback.
$(".item").each(function() {
$(this).html(
'<div class="title"> ....'
);
});
This literally means "Find all DOM elements with item class and replace their contents with given html.
But you need to replace contents of the one specific element, on which Update button was clicked. To do so, you need to persist that element somehow.
One of the ways to do that with minimum changes to your code - introduce a variable in a scope available for both update and save functions. But in your case it would be a global variable, and those are not generally a good idea.
So I'd suggest to wrap all your code into a function (like $(function() {});.
Then you can introduce a local variable:
$(function () {
// define it
var $selectedItem;
// assign a value in the update click callback
$('#content').on('click', '.update', function () {
$selectedItem = $(this).closest('.item');
// ...
});
// read the value in the save click callback
$('.save').click(function () {
// ...
$selectedItem.html('...');
// ...
});
});
Example: https://codepen.io/anon/pen/GzXaoV
I have a bunch of products that will be loaded(append-ed) to the page when the user loads the page the first time. I use a $.post() call to the database and then append the data as a number of divs into a container.
$(function() {
var profile_looks = $('#profile_looks');
$.post("apples.php", function(json) {
var looks = $.parseJSON(json);
profile_looks.prepend(
(some code here)
)
}); // close $.post()
After these products are loaded, I want the products to change background color on hover.
var product_tags = $('.product_tags');
product_tags.mouseenter(function() {
$(this).css('background-color', 'white');
});
}); // close $(function()
However step 2 does not work, meaning when I mouseover the product_tags, they do not change. Why aren't the product_tags div responding to the function call?
Full code below
$(function() {
var profile_looks = $('#profile_looks');
$.post("apples.php", function(json) {
var looks = $.parseJSON(json);
var page_post = "";
$.post('oranges.php', function(products_data) {
var products_display = $.parseJSON(products_data);
for(i = 0; i < looks.length; i++) {
var fruits = products_display[i];
for(var key in fruits) {
var test = "<div class='product_tags' style='color:" + "black" + "' >" + "<span class='type' style='font-weight:600'>" + key + "</span>" + " " + "<span class='title'>" + fruits[key] + "</span>" + "</div>";
var mega = mega + test;
}; // the 2nd for-loop finishes, and re-runs the first for-loop
}; // b=0 timer loop finishes
profile_looks.prepend(
"<div class='look'>" + "<div class='look_picture_container'>" +
"<img src='" + "user_pictures/" + username_cookie + "/" + looks[i][0] + "'>" +
"<div class='heart'>" +
"<img src='" + "../function icons/hearticon black.png" + "'>" +
"<div class='heartcount'>" +
"</div>" +
"</div>" +
"<div class='product_tags_container' style='background-color:" + looks[i][3] + "' >" + mega + "</div>" +
"</div>" + // class="look_picture_container"
"<div class='post_description'>" +
looks[i][1] +
"</div>" + // class= "post_description"
"</div>"); // class="look"
var mega = "";
}
}); // for the $.post(displayproducts.php)
}) // for the $.post(displaylooks.php)
var product_tags = $('.product_tags');
product_tags.mouseenter(function() {
$(this).css('background-color', 'white');
});
product_tags.mouseleave(function() {
$(this).css('background-color', 'transparent')
});
}); // end of $(function()
It doesn't work because the elements doesn't exist yet when you try to bind the events to them.
You can use delegated events, which you bind to an existing element where the elements will end up:
profile_looks.on('mouseenter', '.product_tags', function() {
$(this).css('background-color', 'white');
}).on('mouseleave', '.product_tags', function() {
$(this).css('background-color', 'transparent')
});
Your data is arriving asynchronously, while you're creating the "hover rule" (attaching the event handlers) synchronously.
This means that when you write:
var product_tags = $('.product_tags');
product_tags.mouseenter(function() {//...
product_tags is a collection of elements that exist right after you dispatch the async POST calls. (The answer to these POSTs didn't arrive yet at this point, so the DOM you want to attach to was not generated either.)
To fix this, trigger the attaching of these mouseenter event handlers after the async answer has arrived (from the same callback you're using to work with the returned data), and you've set up the DOM you need to work with.
Note: the other answers bring up good points about delegating your event handlers via an already existing container using jQuery's .on(), which might prove to be a cleaner, more declarative solution.
As product_tags are dynamically generated elements, you need to use .on API to delegate the events for such elements. .on API
Use this
profile_looks.on({
mouseenter: function () {
$(this).css('background-color', 'white');
},
mouseleave: function () {
$(this).css('background-color', 'transparent')
}
}, '.product_tags')
function demo(){
$('.box').slideToggle('fast');
}
$(document).ready(function(){
$.getJSON( "js/JobOpenings.json", function( data ) {
var glrScrlImg = [];
$.each( data.getJobOpeningsResult, function( key, val ) {
var st = "",id,st2= "",st3="",id;
st +="<h4>" + val.JobTitle + "</h4>";
st3 += "<div class='box'>" + val.JobDetails + "</div>";
$("#newsDetails").append("<li onclick='demo()'>" + st+val.JobSector + "<br>" + st3 + "</li>");
$('.box').hide();
});
});
});
I am reading data from a json file. The div with 'box' class is hidden. Currently this code is displaying all div on click of the li. What changes should I make to display only the div corresponding to the clicked li?
Here what we need to do is to find the .box element within the clicked li, so we need to get a reference to the clicked element.
I would use a delegated jQuery event handler with css to initially hide the element
$(document).ready(function () {
$('#newsDetails').on('click', 'li', function () {
$(this).find('.box').toggleClass('hidden');
})
$.getJSON("js/JobOpenings.json", function (data) {
var glrScrlImg = [];
$.each(data.getJobOpeningsResult, function (key, val) {
var st = "",
id, st2 = "",
st3 = "",
id;
st += "<h4>" + val.JobTitle + "</h4>";
st3 += "<div class='box hidden'>" + val.JobDetails + "</div>";
$("#newsDetails").append("<li>" + st + val.JobSector + "<br>" + st3 + "</li>");
});
});
});
with css
.hidden {
display: none;
}
Pass the control to the function and then based on your control slideToggle its respective .box
function demo(ctrl){
$(ctrl).find('.box').slideToggle('fast');
}
$(document).ready(function(){
$.getJSON( "js/JobOpenings.json", function( data ) {
var glrScrlImg = [];
$.each( data.getJobOpeningsResult, function( key, val ) {
var st = "",id,st2= "",st3="",id;
st +="<h4>" + val.JobTitle + "</h4>";
st3 += "<div class='box'>" + val.JobDetails + "</div>";
$("#newsDetails").append("<li onclick='demo(this)'>" + st+val.JobSector + "<br>" + st3 + "</li>");
$('.box').hide();
});
});
});
Or add a class to li and attach an event handler like below instead of writing inline onclick as below:
$("#newsDetails").append("<li class="someclass"'>" + st+val.JobSector + "<br>" + st3 + "</li>");
and then instead of function demo() write this
$('#newsDetails').on('click','.someclass',function(){
$(this).find('.box').slideToggle('fast');
});
UPDATE
Method 1:
function demo(ctrl){
$('#newsDetails').find('li.box').hide('fast'); //hide all the .box
$(ctrl).find('.box').slideToggle('fast');
}
Method 2:
$('#newsDetails').on('click','.someclass',function(){
$('#newsDetails').find('li.box').hide('fast'); //hide all the .box
$(this).find('.box').slideToggle('fast');
});
UPDATE 2:
Method 1:
function demo(ctrl){
$('#newsDetails').find('li.box').not($(ctrl).find('.box')).hide('fast'); //hide all the .box
$(ctrl).find('.box').slideToggle('fast');
}
Method 2:
$('#newsDetails').on('click','.someclass',function(){
$('#newsDetails').find('li.box').not($(ctrl).find('.box')).hide('fast'); //hide all the .box except this
$(this).find('.box').slideToggle('fast');
});
You should structure your html (which is missing from the question!) so that the div and li are "connected" in some way (maybe the div is child of li, or they have same class, ecc).
Right now the line
$('.box').slideToggle('fast');
is applied to all element with class '.box' in your page. You want to be more selective there, that's where the way you structure the html comes into play.
Here's an example: http://jsfiddle.net/owe0faLs/1/
I have a jQuery extension method to create custom animated drop-down select lists based on this answer. Using this method on a page with one drop-down works perfectly:
The extension method is as follows:
$.fn.extend({
slidingSelect: function (options) {
var select = $(this);
var selector = select.selector;
var width = $(selector).width();
var selectedValue = select.val();
if (selectedValue === "undefined")
selectedValue = select.find("option:first").val();
console.log($(selector + " option:selected").text());
var divToggle = $("<div class='SelectorToggle SelectorToggle-defualt'>" + $(selector + " option:selected").text() + "<button style='float: right; width: 20px' id='ddlImgBtn'></button></div>")
.attr({ id: select.attr("id") + "Toggle" })
.css({ width: select.width() + 20 })
.click(function () {
$(selector + "Toggle").toggleClass("SelectorToggle-defualt");
$(selector + "Toggle").toggleClass("SelectorToggle-pressed");
$(selector).slideToggle("fast");
}).insertBefore(select);
var optionCount = $(selector + " option").length;
if (optionCount < 5) {
select.attr("size", optionCount);
}
else {
select.attr("size", 5);
}
select.addClass("drop-down-selector");
$(selector).css({ 'width': select.width() + 20, 'position': 'absolute', "z-index": '9999' });
select.change(function () {
divToggle.html($(selector + " option:selected").text() + "<button style='float: right; width: 20px' id='ddlImgBtn'></button>");
$(selector + "Toggle").toggleClass("SelectorToggle-defualt");
$(selector + "Toggle").toggleClass("SelectorToggle-pressed");
$(selector).slideToggle("fast");
});
}
});
I call it as follows:
$("#LanguageSelector").hide().slidingSelect();
I am however having endless issues getting it to work on a page with multiple drop-downs. My dropdowns are dynamically created as part of a DataTable solution with server-side processing. The drop-downs in the footer:
If i call the following:
$("select").hide().slidingSelect();
then somehow all drop-downs on the page create the custom control:
if I attempt to call the extension method on each element individually:
$("select").hide().each(function(index) {
$(this).slidingSelect();
});
I also tried to call the extension method individually as the drop-downs are created (to just one of them):
$('#RelatedCasesGrid tfoot th').each(function () {
var col = $(this).html();
//..........
else if (col === "ComplaintTypeName") {
$(this).html(GetDropDownInput(col, caseId));
var element = $(this).find("select");
element.hide().slidingSelect();
}
The method GetDropDownInput(col, caseId) creates the drop-downs as follows:
function GetDropDownInput(col, id) {
var control;
$.ajax({
method: "GET",
dataType: "json",
async: false,
url: "/OATS/Api/GetColumnItems/" + id + "?column=" + col
}).done(function (data) {
control = "<select id='selector' class='table-filter-input-drop-down-list'><option value='' disabled selected>Filter by</option>"
for (var i = 0; i < data.length; i++) {
control += "<option col-type=" + data[i].Type + " value='" + data[i].Name + "'";
if (data[i].Selected) {
control += "selected='selected'";
}
control += ">" + data[i].Name + "</option>";
}
control += "</select>";
});
return control;
}
The result of this:
From: http://www.w3schools.com
The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
But your ajax method create the same id for all selects: "selector". Change this method to create unique id (value of 'col' parameter seems be ok for this purpose), and then call:
$("#your_unique_id").hide().slidingSelect();
I am showing number counter in one of my section. When I add new betslips to the container the numbers are displaying correctly. However, when I delete any of the row the counter is not getting updated. For example if there are 3 rows numbered 1, 2 and 3 and if I delete row number 2 the updated values are 1 and 3. Infact the counter should reset to 1 and 2.
Here is my JS code
Adding the betslip rows
function createSingleBetDiv(betInfo) {
var id = betInfo['betType'] + '_' + betInfo['productId'] + '_' + betInfo['mpid'],
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b>' + singleBetNumber + '. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'] + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
Function to remove betslip
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function decreaseBetSlipCount() {
var length = $("#racingBetSlipCount").text().length,
count = $("#racingBetSlipCount").text().substring(1, length-1),
text;
count = parseInt(count);
if (!isNaN(count)) count--;
if (count == 0) text = noSelections;
else text = count;
$("#racingBetSlipCount").text('(' + text + ')');
}
This could be done using only CSS, e.g:
DEMO jsFiddle
HTML:
<div id="bets">
<div class="bet"> some content</div>
<div class="bet"> some content</div>
<div class="bet"> some content</div>
</div>
CSS:
#bets {
counter-reset: rowNumber;
}
#bets .bet {
counter-increment: rowNumber;
}
#bets .bet::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
All row number will be updated automatically when adding/removing any row.
You can manage to do that with following steps;
Enclose bet no with span,
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '<span>. ' + betInfo['horseName'] + '</b></p>');
and I assume you have aouter div called "your_div"
Call below function after every increase and decrease event
function updateBetNo() {
var counter = 1;
$("#your_div .bet_no").each(function(i, val) {
$(this).text(counter);
counter++;
});
}
Make the betNumber findable:
$(leftDiv).append('<p class="title"><b><span class="singleBetNumber">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
After an insert or delete renumber:
$('.singleBedNumber').each(function(idx, el) {
$(el).html('' + (idx + 1));
});
The first problem I see is that $("#racingBetSlipCount") is likely not selecting what you think it is. Since #racingBetSlipCount is an id selector it will only select one item.
To me you need to wrap the betnumber in something accessible so you can update it without having to parse through the title.
So first you would update the creation of the betTitle:
$(leftDiv).append('<p class="title"><b><span class=\'betNum\'>' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
Then you can loop through each and update the number appropriately.
var count = 1;
$.each($(".betNum"), function(){
$(this).html(count++);
});