I am trying to fill an array with strings, the elements that will be added are the HTML of the clicked <\li>, im probably filling it correctly.
My problem is when the user clicks on the checked link again, i want to remove this item from the array
Here is a code sample:
$(document).ready(function(){
var chosen = [];
var chosenCounter = 0;
find("ul").find("li").click(function(){
var checkBox = $(this).find("img").first();
var checkBoxSrc = checkBox.attr("src");
if(checkBoxSrc == "images/unchecked.png"){
checkBoxSrc = "images/checked.png";
checkBox.attr("src",checkBoxSrc);
checkBox = "";
checkBoxSrc = "";
var temp = this.outerHTML;
chosen[chosenCounter] = temp;
chosenCounter ++;
}
if(checkBoxSrc == "images/checked.png"){
checkBoxSrc = "images/unchecked.png";
checkBox.attr("src",checkBoxSrc);
checkBox = "";
checkBoxSrc = "";
for (var j =0; j<=chosen.length; j++){
var tempRemove = this.outerHTML;
chosen.splice( chosen.indexOf( tempRemove ), 1 );
tempRemove = '';
}
}
});
});
I have been trying all functions and ways i found on internet .. but the results doesn't works well, i would be very thankful for a correction and explanation.
Thanks all in advance.
I've gone through an rewritten the code to work much better. There were a number of issues but here is the fixed version that I tested.
Your original code had an if statement and then another if statement. You needed an if and then an else if.
Notice when finding the child element I just use $('img', this) instead of the find operator and first().
Use ID instead of HTML
For debugging there is a console.log statement in there. Remove this so it works in IE.
To add an element to an array use push
No need to loop over splice to remove the item. Just call splice once.
$(document).ready(function () {
var chosenIDs = [];
$("ul li").click(function () {
var checkBox = $('img', this);
var checkBoxSrc = checkBox.attr("src");
var id = $(this).attr('data-id');
console.log(id + ' ' + chosenIDs.length + ' ' + checkBoxSrc);
if (checkBoxSrc == "images/unchecked.png") {
checkBoxSrc = "images/checked.png";
checkBox.attr("src", checkBoxSrc);
chosenIDs.push(id);
}
else if (checkBoxSrc == "images/checked.png") {
checkBoxSrc = "images/unchecked.png";
checkBox.attr("src", checkBoxSrc);
chosenIDs.splice(chosenIDs.indexOf(id), 1);
}
});
});
Related
I have a server that dynamically(asp.net ) generate webpages that I can't alter.
On all pages I would like to capture all buttons clicked.
In JSFiddle https://jsfiddle.net/forssux/aub2t6gn/2/ is an example..
$(".checkout-basket").click (function ()
The first alert shows the 3 possible values,
but not the chosen item..
$(".button.button-dl").click(function ()
In jsfiddle this part doesn't get executed
Strangely on my real webpage I get the button clicked...but when I put it in the If then construction it fails to console.log the chosen item..
I hope somebody can explain me how to get these..
Kind Regards
Guy Forssman
//$("div.detail-info,table.checkout-basket").click(function () {
// var knopje = $(this).attr("class")//.split(" ");
// console.log(knopje + " knopje was clicked");
// if(knopje.indexOf("detail-info") > -1) {
// console.log("div class detail-info is clicked");
// }
// else if (knopje.indexOf("checkout-basket") > -1) {
// console.log("table class checkout-basket is clicked");
// }
// else {
// alert ("er is op iets anderes gedrukt");
// }
// capture click on download button in checkout-basket page
$(".checkout-basket").click (function () {
basket =[];
item="";
str = $(this).text();
str = str.replace(/\s\s+/g, ' ');
var str = str.match(/("[^"]+"|[^"\s]+)/g);
console.log("Array ",str);
for(var i=0;i<str.length;i++){
if(str[i] === "verwijder"){
console.log("Item= ",str[i+1]);
item = str[i+1];
basket.push(item);}
}
console.log("Basket contains ",basket);
//console.log("idValBasket ",idVal);
var test = idVal.replace(/\$/gi, "_").slice(0,-6);
console.log("test ",test);
var element = test.substr(test.length - 2)-1;
console.log("element ",element);
element=element-1;
item = basket[element];
console.log("Item finaal is ",item);
});
$(".button.button-dl").click(function () {
var addressValue = $(this).attr('href');
console.log("addresValue Basket",addressValue );
var re = /'(.*?)'/;
var m = addressValue.match(re);
console.log (" m basket is ",m);
if (m != null)
idVal = (m[0].replace(re, '$1'));
console.log("idVal Basket",idVal);
});
//This section captures the download in the detail page
$(".button").click(function () {
var downloadItem = document.getElementsByTagName("h1")[0].innerHTML
console.log("addresValue detail",downloadItem );
});
I never use click function, use on(*event*,...) instead:
$(".checkout-basket").on("click", function (){ /* CODE */ });
Check if visually there are a layout over the a layuot (a div, span, etc.)
Maybe a strange question and maybe i got it wrong, but why do you use push ?? if you want to delete an item ? btw also the example isn't working so maybe that is your problem
I am using this code :-
function makeDirectionTabs() {
alert('sdfsf');
jQuery('.adp-warnbox').remove();
jQuery('#adp-placemark').parent().remove();
jQuery('.adp-legal').remove();
var i = 0;
jQuery('#fullDirections .adp > div').each(function () {
i = i + 1;
alert(i + jQuery(this).html());
directionContent = jQuery(this).html();
jQuery('#tab' + i).append(directionContent)
});
}
I got div elements in tab1 , tab2 etc.. with alert
But when I remove alert from this code I did not get div elements in tabs Why ?
What I am leaving .. Where Am I wrong ?
Please help Me.
Main problem :-
Loop running fast and html() function is not working. When I use alert in loog then loop stay for alert and html() works. Please tell me resoin or solution for this.
Strange because cannot see any asynchronous request anywhere. But usually, you should use the index param of each loop. See if its changing anything:
function makeDirectionTabs() {
jQuery('.adp-warnbox').remove();
jQuery('#adp-placemark').parent().remove();
jQuery('.adp-legal').remove();
jQuery('#fullDirections .adp > div').each(function (i) {
directionContent = jQuery(this).html();
jQuery('#tab' + i).append(directionContent)
});
}
Please see if this helps:
function makeDirectionTabs() {
alert('sdfsf');
jQuery('.adp-warnbox').remove();
jQuery('#adp-placemark').parent().remove();
jQuery('.adp-legal').remove();
var i = 0;
var $divs = jQuery('#fullDirections .adp > div');
for(var i=0; i < $divs.length ; i++){
directionContent = jQuery($divs[i]).html();
jQuery('#tab' + i).append(directionContent)
}
}
I have this section of code that saves a list item on click to localStorage based on the list item's id number. On a different page I am then able to load whatever list items were saved.
var save1075 = $('#store-1075').get(0);
$('#store-1075').on('click', function () {
var storeStorageKey1075 = $(this).attr('id');
localStorage.setItem('storeStorageKey1075', $(this).attr('id'));
localStorage.setItem('storeStorageKey1075', this.innerHTML);
});
if ( localStorage.getItem('storeStorageKey1075') ) {
save1075.innerHTML = localStorage.getItem('storeStorageKey1075');
}
var storeStorageKey1075 = $(this).attr('id');
if ( localStorage.getItem('storeStorageKey1075') ) {
storeStorageKey1075 = localStorage.getItem('storeStorageKey1075');
}
Right now I have to repeat that chunk of code for every individual id number and I'm trying to instead make the id number a variable that loops through all possible id numbers when clicked but only saves the id of that specific one. Maybe something along the lines of this:
var id = //some sort of loop or array of possible ids.
var save = $('#store-'+id).get(0);
$('#store-'+id).on('click', function () {
var storeStorageKey = $(this).attr('id');
localStorage.setItem('storeStorageKey', $(this).attr('id'));
localStorage.setItem('storeStorageKey', this.innerHTML);
});
if ( localStorage.getItem('storeStorageKey') ) {
save.innerHTML = localStorage.getItem('storeStorageKey');
}
var storeStorageKey = $(this).attr('id');
if ( localStorage.getItem('storeStorageKey') ) {
storeStorageKey = localStorage.getItem('storeStorageKey');
}
Each of the list items has the same prefix of "store-" and the numbers are in no specific order but randomly generated each time a new store location is created.
The obvious thing to do is to add a class but you could also:
var elems = $( "[id^='store']")
elems.on( "click", function() {//Save html on click
localStorage.setItem( this.id, this.innerHTML );
});
//Retrieve html
elems.each( function() {
var html = localStorage.getItem( this.id );
if( html ) {
$(this).html( html );
}
});
This loops over all keys that begin with storeStorageKey:
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
if (/^storeStorageKey/.test(key)) {
var item = localStorage.getItem(key);
// do something with item
}
}
Instead of using a prefix in the id I'd suggest adding a class to indicate that an item is storable:
<div class="storable" id="store-1234">...</div>
then you can use the class to select all the storable things in one go:
$('.storable').on('click', function () {
var storeStorageKey = $(this).attr('id');
...
});
I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:
How to I undo .detach()?
But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:
function MMtoggle(IDnum) {
var rowID = "row" + IDnum;
var jRow = '#' + rowID;
thisMMbtn = $(jRow).find(".addMMbtn");
var light = false;
var that = this;
if (light == false) {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
$(this).unbind("click");
light = true;
}
);
}
else {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
thisMM = thisRow.find(".mmCell");
SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
$(this).unbind("click");
light = false;
}
);
}
}
MMtoggle(g.num);
A fiddle of the problem is here: http://jsfiddle.net/pScJc/
(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)
Looking at your code I don't think so you need detach for what you are trying to achieve.
Instead try this code.
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var $mmCell = thisTxt.find('.mmCell');
if($mmCell.length == 0){
$mmCell = $('<div class = "mmCell prep"></div>')
.appendTo(thisTxt).hide();
}
$mmCell.toggle();
//$(this).unbind("click");
}
);
Demo
I have following jQuery code
$('a.editpo, a.resetpass').click(function(event){
event.preventDefault();
var urlToCall = $(this).attr('href');
var hyperlinkid = '#'+$(this).attr('id');
var targetId = $(this).attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = $(this).html();
/*Todo: refactor or shorten the following statement*/
if((currentLink=='Edit' && $('#resetuserpassform_'+targetId).is(':visible'))
||
(currentLink=='Reset Pass' && $('#account-home-container-'+targetId).is(':visible'))
||
($(targetTdDiv).html() =='')
){
$.ajax({
url:urlToCall,
success: function(html){
$(targetTdDiv).html(html);
$(targetTrDiv).show();
}
});
}else{
$(targetTrDiv).hide();
$(targetTdDiv).html('');
}
});
The editpo and resetpass are classes applied on hyperlinks in column of table, namely Edit and Reset Pass, clicking these load up the form in a table row, ids for the respective tr and td is targetTrDiv and targetTdDiv. I am not good at JS and specially jQuery, but would still be interested in any optimisations.
But I am especially interested in reducing the condition statement.
First, you can optimize the following code:
var urlToCall = $(this).attr('href');
var hyperlinkid = '#'+$(this).attr('id');
var targetId = $(this).attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = $(this).html();
to:
var wrappedSet$ = $(this);
var urlToCall = wrappedSet$.attr('href');
var hyperlinkid = '#'+wrappedSet$.attr('id');
var targetId = wrappedSet$.attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = wrappedSet$.html();
EDIT: Also, you could remove the currentLink=='Edit' && and currentLink=='Reset Pass' && code snippets, because you can be sure that the right links were clicked using the class selector that you are using in your jQuery click handler (a.editpo, a.resetpass).
If you do that the codition statement will stays like this:
if(($('#resetuserpassform_'+targetId).is(':visible'))
||
($('#account-home-container-'+targetId).is(':visible'))
||
($(targetTdDiv).html() =='')
){
/* AJAX call goes here */
}
Besides, and hopefully I'm wrong, it's very unlikely that the condition statement can be more optimized. The reason for concluding this is that you want to much specificity that is likely impossible to achieve in other way.
Hope it helps you.