How to remove element on second click - javascript

I need to add elements to container on a first click and delete it on a second one. I guess I'm trying to make it super hard while there is a more elegant and clear solution. Fiddle Link
I was thinking of arrays to create a 1st array for clicked elements and the 2nd one for elements that are already in a container. Then filter the first array through the second one and delete those (unmatched) elements from my container.
var click = +$(this).data('clicks') || 0; // Check if contacts cliked first time
if (click % 2 == 1) { // 2nd click
fruits.splice($.inArray(name, fruits), 1); // Remove Name from an array
$(".test .single").each(function (index, elem) {
compArr.push($(this).text());
});
keyArr = fruits.filter(i => compArr.indexOf(i) !== -1);
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here
} else { // 1st click
fruits.push(name);
$('.test textarea').css({
'font-size': '12px',
'border': '0'
}).prop('placeholder', '').before('<span class="single">' + name + '></span>');
$('textarea').val('');
}
$(this).data('clicks', click + 1);
For me, this part doesn't work properly. But I would love to hear any of your suggestions even if the entire logic is wrong. Thanks!
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
}

I've managed to fix it. Added this code:
let deleteSingle = $('.single');
for (let i = 0; i < deleteSingle.length; i++) {
for (let j = 0; j < arrayNewKeys.length; j++) {
if (deleteSingle[i].innerHTML.includes(arrayNewKeys[j])) {
deleteSingle.eq(i).addClass('a');
break;
} else {
deleteSingle.eq(i).removeClass('a');
}
}
}
$('.styleContacts:not(.a)').remove();
if ($('.test > .single.a:only-child')) {
$('.single.a').removeClass('a');
}
Instead of this:
var i = 0;
for (; i < keyArr.length; i++) {
$(".name").each(function () {
$(".single:not(:contains('" + keyArr + "'))").remove();
});
} // I guess problem is here

Related

Click in JS loop undefined

I have an interation loop on which I need to click on every element:
var spans = document.getElementsByClassName('span')
for (var i = 0; i < spans.length; i += 1) {
i.click(function() {
console.log("Clicked")
});
}
I get i.click is not a function error. ¿What am I missing?
Thanks!
i is the index, not the element. This is how you would fix your code:
var spans = document.getElementsByClassName('span')
for (var i = 0; i < spans.length; i += 1) {
spans[i].click(function() {
console.log("Clicked")
});
}
But 'click' also doesn't take a callback. This is how your code should look like in 2022:
const spans = document.getElementsByClassName('span')
for (const span of spans) {
span.click();
console.log("Clicked")
}

How to keep duplicates from being added to an array

var reservations = [];
function addReservation() {
//Gets Input from textboxes.
var nameChosen = document.getElementById("txtName").value;
var roomChosen = document.getElementById("selRoom").value;
//adds input into the array.
reservations[reservations.length] = roomChosen + " ";
reservations[reservations.length] = nameChosen + " ";
//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {
if (document.getElementsByName("Day[]")[i].checked) {
reservations.push(document.getElementsByName("Day[]")[i].value);
}
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
if (document.getElementsByName("Time[]")[i].checked) {
reservations.push(document.getElementsByName("Time[]")[i].value);
}
}
}
How do I ensure that if the time and day cannot be added twice to the array?
Or easier yet, How do I ensure that the same name cannot be added twice to the array?
Test if the item is in the array first
if (!item in array) { array.push(item); }
I think that you are looking for a way to break out of the for loop after you hit the first match. One way to do this is to set i to the termination condition inside the if statement, which will exit the loop.
//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {
if (document.getElementsByName("Day[]")[i].checked) {
reservations.push(document.getElementsByName("Day[]")[i].value);
i = document.getElementsByName("Day[]").length
}
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
if (document.getElementsByName("Time[]")[i].checked) {
reservations.push(document.getElementsByName("Time[]")[i].value);
i = document.getElementsByName("Time[]").length
}
}

JavaScript Arrays - Iteration Trouble

I'm building a (very) mini JS framework to use for customizing my eBay listings. I do know how to circumvent their "no remote scripts" policy, and I could use jQuery, but this is really an exercise in getting myself better at JS.
I have a function of the global window object which returns a bunch of methods, like this:
window.iq = (function(){
return {
tag: function(tag) {
return document.getElementsByTagName(tag);
},
map: function(el, attr) {
var arr = [];
el = iq.tag(el);
for (i = 0; i < el.length; i++) {
var x = el[i].getAttribute(attr);
arr.push(x);
}
return arr;
},
// A bunch of others like this
};
})();
I'm having trouble (by which I mean I'm utterly stuck) iterating through an array of data-name attributes and hiding or showing images based on whether there is a match. Here's the function:
iq.click('#mblThumbs img', function(){
var dn = iq.map('img', 'data-name');
for (i = 0; i < dn.length; i++) {
if (this.getAttribute('data-name') === dn[i]) {
iq.fadeOut(200, iq.sel('#mblSlide img:not([data-name="' + dn[i] + '"])'));
iq.fadeIn(200, iq.sel('#mblSlide img[data-name="' + dn[i] + '"]'));
}
}
});
I can cycle through the first two images as many times as my heart desires, but as soon as I click on anything past the second image, the function only continues to work for it, and the subsequent indexes in the array. I'm guessing that this is either a problem with my map method, or maybe something to do with array length? I don't know. I'm flummoxed. Any thoughts or suggested are much appreciated.
FIDDLE: http://jsfiddle.net/h8z7c/
The issue is indeed with your click callback. Your fadeout selector is finding the first image that is not data-name=dn[i], which is always either "one" (if you clicked 2), or "two" (if you clicked 1). You either need to use selAll to grab all of the elements that are not the clicked one, or keep track of which one is currently selected. Here are the two ways of fixing it.
// Make sure they are all hidden
iq.click('#mblThumbs img', function(){
var dn = iq.map('img', 'data-name');
for (i = 0; i < dn.length; i++) {
if (this.getAttribute('data-name') === dn[i]) {
var outs = iq.selAll('#mblSlide img:not([data-name="' + dn[i] + '"])');
for (var j = 0; j < outs.length; j++) {
iq.fadeOut(200, outs[j]);
}
iq.fadeIn(200, iq.sel('#mblSlide img[data-name="' + dn[i] + '"]'));
}
}
});
// Or keep track of the currently selected
var selected = "one";
iq.click('#mblThumbs img', function(){
var dn = iq.map('img', 'data-name');
for (i = 0; i < dn.length; i++) {
if (this.getAttribute('data-name') === dn[i] && dn[i] !== selected) {
iq.fadeOut(200, iq.sel('#mblSlide img[data-name="' + selected + '"]'));
iq.fadeIn(200, iq.sel('#mblSlide img[data-name="' + dn[i] + '"]'));
selected = dn[i];
}
}
});

How to delete 2 rows at a time using JavaScript

How to delete two rows at a time using JavaScript even though only for first row radio button exist?
Something like this:
1st row: (radiobutton) some textfield
2nd row: text field
On click of delete button, both the row should get deleted but the code which I have written is deleting only 1st row not 2nd one.
JavaScript code looks something like this:
function deleteReserveDetails() {
if (!document.forms[0].reserveRadiobutton) {
return;
} else {
var hidValue = parseInt(document.forms[0].Hd1Value.value);
var reserveRows = document.getElementById('reserveTable').getElementsByTagName('tr');
var headerNo = 1;
var radio = eval("document.forms[0].reserveRadiobutton");
if (radio.length == undefined) {
if (radio.checked) {
var hidValue1 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue1;
document.getElementById('reserveTable').deleteRow(headerNo);
}
return;
}
var k = 0;
for (var j = 0; j < radio.length; j++) {
if (radio[j].checked) {
if (j == hidValue - 1) {
var hidValue2 = parseInt(document.forms[0].Hd1Value.value) - 1;
document.forms[0].Hd1Value.value = hidValue2;
}
document.getElementById('reserveTable').deleteRow(j + headerNo);
}
}
}
}
Could you please show me how to modify it to delete 2 rows at a time?

jQuery multiple variables in for loops

This might be simple thing but just can't figure it out.
Let's assume I got fifty similar functions and there's two of them:
var unit = ['red', 'pink']
var unit2 = ['red2', 'red2']
$('#red').click(function() {
if($('#red2').is(':hidden')) {
$('#red2').toggle();
} else {
$('#red2').toggle();}}}
and
$('#pink').click(function() {
if($('#pink2').is(':hidden')) {
$('#pink2').toggle();
} else {
$('#pink').toggle();}}}
and I want to add all these functions in one/two for loops.
I tried this:
for (var i = 0; i < unit.length; i++) {
for (var y = 0; y < unit2.length; y++) {
$('#i').click(function() {
if($('#y').is(':hidden')) {
$('#y').toggle();
} else {
$('#y').toggle();}}}}
.toggle() method detects the visibility of the element itself, there is no need to use if statement, you can use this keyword which refers to the clicked element:
$('#red, #pink').on('click', function() {
// Based on the id property of the clicked element
// this selects #red2 or #pink2 element
$('#' + this.id + '2').toggle();
});
Also note that $('#i') selects an element with ID of i, you should concatenate the strings:
$('#' + i).foo();
You should concatenate strings:
for (var i = 0; i < unit.length; i++) {
$('#' + unit[i])
.attr('data-dst', unit2[i])
.click(function() {
var dst = $(this).attr('data-dst');
$('#' + dst).toogle();
}
}

Categories

Resources