Loop throught checkboxes and delete hidden copies javascript - javascript

Ok so, im trying to create a loop and a loop inside that loop. The point is to create a remove function. I have a list of users and copies of those same users hidden. Purpose of copies is show them on clicking 'online' link or 'offline' link or 'all'. When i want to remove a user i made a checkbox for each user, by clicking the checkbox, it pushes that element into an array. then when i click minus it removes that user and loops thru the hidden copies and removes the ones match the id. It works fine for one user, or if i check/select users from the bottom of the list going up, then it loops thru the array perfectly fine and removes all copies from DOM. But if i do it the normal way by selecting per say the first user on the list then second then third etc, it will only loop thru the first user element. but in console, it shows that the array has the users i pushed into, and it will actually loop thru that first element the amount of times as how many users i pushed into it.
Someone pointed out to not using duplicate ids and i knew that, but i didnt know how else to get this done, i tried using title, name, but cant use classes cuz i have multiple classes on the elements. Im mindfckd as to why it works if i select elements backwards. this is a isolated example from my project, so it only has one class and i dont have hidden copies. this is just so someone helping can better see what im tryin to do. the visible copies need to dissapear by checking only one copy but it has the same bug, html doesnt seen to show parent div..
http://codepen.io/Pagnito/pen/vmLOvj?editors=1010
function minus() {
$('.fa-minus').click(function() {
if ($('.chBox').is(':checked')) {
var div = $(':checked').closest('div');
var dib = div.next();
$(checkedArr).each(function(i, iteM) {
console.log(checkedArr)
var ch = iteM;
var chkd = $(ch).attr('id')
console.log(chkd)
console.log('hi' + i)
$('.g').each(function(index, item) {
var ite = $(item).attr('id')
if (ite == chkd) {
$(item).remove();
var dib = div.next('#acc');
$(dib).remove();
}
})
})
var dib = div.next('#acc');
$(dib).remove();
$(':checked').closest('a').remove();
checkedArr = [];
}
})
}
<div class="list-group hidden-xs-down streams">
<div class="g" class="free"><input class="chBox" type="checkbox" name="user">Free</div>
<div class="g" id="ninja"><input class="chBox" type="checkbox" name="user">ninja</div>
<div class="g" id="big"><input class="chBox" type="checkbox" name="user">big</div>
<div class="g" id="free"><input class="chBox" type="checkbox" name="user">Free</div>
<div class="g" id="ninja"><input class="chBox" type="checkbox" name="user">ninja</div>
<div class="g" id="big"><input class="chBox" type="checkbox" name="user">big</div>
<div class="g" id="free"><input class="chBox" type="checkbox" name="user">Free</div>
<div class="g" id="ninja"><input class="chBox" type="checkbox" name="user">ninja</div>
<div class="g" id="big"><input class="chBox" type="checkbox" name="user">big</div>
</div>

Related

Remove repeated after 1st occurrence

I'm trying to clean up the results presented on my HTML file with Jquery. I want to keep removing words that are repeated more than one time.
A quick example
Accents Australian
Accents English (RP)
Dance Hip Hop
Dance Jazz
It should be output as
Accents
Australian
English (RP)
Dance
Hip Hop
Jazz
My original HTML looks like this
<div role="list" class="skill-items">
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>Australian</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>English (RP)</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Hip Hop</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Jaz</div>
</div>
</div>
I tried my best but I'm not landing in a good place
$('.skill-category').text(function(index, oldText) {
return oldText.replace($(this).parent().next().find('.skill-category').text(), '');
})
Any suggestion?
Please check below working code:
const category = [...document.querySelectorAll('.skill-item > .skill-category')];
const texts = new Set(category.map(x => x.innerHTML));
category.forEach(category => {
if(texts.has(category.innerHTML)){
texts.delete(category.innerHTML);
}
else{
category.remove()
}
})
As per you question and shared HTML above is the working code for the same and if you add more similar things it will help.
Please let me know if you find any issues
Your question can be broken into two problems:
You want to group the elements with the same value for .skill-category
You want to change <div> elements into a list.
Grouping the elements could by done like so:
For every category, take a look at the previous element.
Does it contain the same category? If not, then continue to the next category.
If so, take everything after .skill-category (in your example HTML, that's a single <div>. Cut-and-paste it at the end of the aforementioned previous element.
For the second problem:
Changing an element (<div> to <li>) is not possible. You can create a new <li> and move what's inside the <div> into it. Of course, you'll need a <ul> that wraps the <li>s as well.
Take the .skill-category elements
Find all the content that follows the category (in your case, 1+ <div> elements)
Put the contents of the matched elements into a new <li>.
Put all the <li>s of a single category into a <ul>.
Remove the matched elements (in your case, the <div>(s)) since we've moved all their content to a different node. They're now empty tags and useless.
Put the <ul> after the .skill-category.
// Grouping the results.
$('.skill-category').each(function() {
// Get the previous .skill-item and find the category.
var prev = $(this).parent().prev('.skill-item').find('.skill-category');
// Check if the previous category === this category.
var same = !!(prev.length && prev.text() === $(this).text());
if (!same) {
return; // Do nothing.
}
// Take every element after the category and move it to the
// previous .skill-item.
prev.after($(this).nextAll());
// Then remove the now-empty category.
// All content has been moved to the previous element, after all.
$(this).parent().remove();
});
// Wrapping the contents of a category in a list.
$('.skill-category').each(function() {
var list = $('<ul></ul');
// Find everything after the category.
$(this).nextAll().each(function() {
// Create a <li> and move the child elements to it.
// Then add the <li> to the <ul>.
$('<li></li>').append($(this).contents()).appendTo(list);
}).remove(); // remove the now empty elements.
// Add the list to current .skill-category.
$(this).append(list);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div role="list" class="skill-items">
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>Australian</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Accents</div>
<div>English (RP)</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Hip Hop</div>
</div>
<div role="listitem" class="skill-item">
<div class="skill-category">Dance</div>
<div>Jaz</div>
</div>
</div>

show and hide class based on checkbox value usig Jquery

Hi currently i am developing an filtering application . Please see my html and js code
jQuery(document).ready(function($){
$(".color-label").on("click",function(){
var color_box_val= $(this).find('.color-box').val();
$('.test-li').hide();
$('div:contains('+color_box_val+')').closest('.test-li').show();
});
});
.hidden-color{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<label class="color-label">Red<input type="checkbox" class="color-box" value="red"/></label>
<label class="color-label">Black <input type="checkbox" class="color-box" value="Black"/></label>
<ul>
<li class="test-li">
<div class="test-div">
<p class="hidden-color">red</p>
red poduct
</div>
</li>
<li class="test-li">
<div class="test-div">
<p class="hidden-color">Black</p>
black Product
</div>
</li>
<li class="test-li">
<div class="test-div">
<p class="hidden-color">Blue</p>
blue Product
</div>
</li>
So here what iam doing is when customer click black , then it will show black product . If the customer click both red and black then we need to show both , and if customer didn't tick anything then we need to show all product .
But i stuck in some point . Here how can i show both red and black when the clicked both ? Currently it is showing the result based on newly clicked check box . Also if they untick every thing then i need to show all box . Please suggest .
The first thing I would recommend changing is how you store color data in your list items. Instead of storing them in a hidden paragraph element, why not store them as HTML5 data- attributes?
Once that is done, it is quite simple to do what you intend: which is basically a OR operation, i.e. when red and black are ticked, you want to show items that are red or black.
The logic is as follow:
You listen to the .change() event on all the checkboxes
When this event is fired, you want to collect the values of all these checkboxes, but only if they are checked. This is done by using .filter(':checked') to select for checked checkboxes and .map() to return the array.
Next, you iterate through all the list items. If their data-color values are found in the array, you show them. Otherwise you hide them.
And all this logic is wrapped within a conditional statement that checks if any of the checkboxes are filtered:
If none is checked, we do not want any filtering
If one or more is checked, we perform filtering using the aforementioned filtering logic
Update: I have used .toLowerCase() to convert all your color values to lowercase, since from your question I can see that the values might be optionally capitalised.
See proof-of-concept example below:
jQuery(document).ready(function($) {
// Listen to change event
$('.color-box').change(function() {
// Store checked checkboxes
var $checked = $('.color-box').filter(':checked');
if ($checked.length) {
// Perform filtering if one or more is checked
// Collect ALL values from all .color-box into an array
var colors = $checked.map(function() {
return $(this).val().toLowerCase();
}).get();
// Iterate through each list item and evaluate
$('.test-li').each(function() {
var $t = $(this);
if (colors.indexOf($t.data('color').toLowerCase()) >= 0) {
$t.show();
} else {
$t.hide();
}
});
}
// If nothing is checked, show all list items
else {
$('.test-li').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<label class="color-label">Red<input type="checkbox" class="color-box" value="red"/></label>
<label class="color-label">Black <input type="checkbox" class="color-box" value="Black"/></label>
<ul>
<li class="test-li" data-color="red">
<div class="test-div">
red Product
</div>
</li>
<li class="test-li" data-color="black">
<div class="test-div">
black Product
</div>
</li>
<li class="test-li" data-color="blue">
<div class="test-div">
blue Product
</div>
</li>

jQuery Replicate an existing Div Multiple Times

I am building a search query which gives me results.
I have a template ready for the item inside a hidden div. What I want to do is replicate the template n number of times using jQuery.
So For example:
I search for flights and I get 5 search results, I need to replicate the below div template 5 Times
<div id="oneWayFlightElement" class="displayNone">
<div id="flightIndex1" class="flightDetailElement boxShadowTheme">
<div id="flightDetailsLeftPanel1" class="flightDetailsLeftPanel marginBottom10">
<div class="fullWidth marginTop10">
<span id="flightPriceLabel1" class="headerFontStyle fullWidth boldFont">Rs 9500.00</span><hr/>
<div id="homeToDestination1" class="flightBlockStyle">
<span id="flightNumberFromHome1" class="fontSize16">AI-202</span><br/>
<span id="flightRouteFromHome1" class="fontSize26">PNQ > DEL</span><br/>
<span id="flightDepartTimeFromHome1" class="fontSize26">Depart: 10.00 AM</span><br/>
<span id="flightArrivalTimeFromHome1" class="fontSize26">Arrive: 12.00 PM</span><br/>
</div>
<div id="destinationToHome1" class="flightBlockStyle">
<span id="flightNumberToHome1" class="fontSize16">AI-202</span><br/>
<span id="flightRouteToHome1" class="fontSize26">PNQ > DEL</span><br/>
<span id="flightDepartTimeToHome1" class="fontSize26">Depart: 10.00 AM</span><br/>
<span id="flightArrivalTimeToHome1" class="fontSize26">Arrive: 12.00 PM</span><br/>
</div>
</div>
</div>
<div id="flightDetailsRightPanel1" class="flightDetailsRightPanel textAlignRight marginBottom10">
<img src="images/flightIcon.png" class="marginRight10 marginTop10 width40"/><br/>
<button class="marginRight10 marginBottom10 width40 bookNowButtonStyle">Book Now</button>
</div>
</div>
</div>
Inside this div for 5 times
<div id="searchFlightResultDiv" class="fullWidth" style="border:solid">
</div>
Is there a better way to do that rather than string appending in jQuery?
Thanks,
Ankit Tanna
You'll need to wrap your template div (#flightIndex1) in a container with a unique id attribute. Then, you take the contents of that container (a template for a single record), and append it to your results div (#searchFlightResultDiv) using some type of loop based on the number of results received.
Basically,
HTML:
<!-- Here's your template -->
<div class="displayNone" id="oneWayFlightElement">
<!-- This id (singleResult) is important -->
<div id="singleResult">Result</div>
</div>
<!-- Container for the results -->
<div id="results"></div>
Javascript:
//Get the number of results.
//This can be sent from your API or however you're getting the data.
//For example, in PHP you would set this to $query->num_rows();
var count = 5;
//Start a for loop to clone the template element (div#singleResult) into div#results 'count' times.
//This will repeat until the number of records (count) has been reached.
for (i = 1; i <= count; i++) {
//Append the HTML from div#thingToRepeat into the #results.
$('#results').append($('#singleResult').clone());
}
Here's a JSFiddle to show you how it works. You can play with it and tweak it if necessary.
I can't in good conscious complete this post without telling you the downsides of this. Doing it this way is majorly frowned upon in the web development community and is super inefficient. It may be good for practice and learning, but please do take a look at and consider a javascript templating framework like moustache or handlebars. It does this same thing but way more efficiently.
Hope this was helpful!
function populateResult(resCount) {
resCount = typeof resCount === 'number' ? resCount : 0;
var res = [];
var templateEle = $('#oneWayFlightElement');
for(var i = 0; i < resCount; ++i)
res.push(templateEle.clone().removeAttr('id class')[0]);
$('#searchFlightResultDiv').html(res);
}
populateResult(5);
We use an array res to hold the DOM elements as we loop and finally sets it to the target div using html method. We don't need a JQuery object here as the html method accepts any array like object. In this way we can minimize browser reflows. Here is the JSFiddle

Am using Push() array was used am trying to use for select a list from drop down menu and post that list into a span?

HTML section
div to show the values
<div class="lef rightCol n">
<span class="para"> add-on Services(Optional)</span>
<div class="new">
<ul>
</ul>
</div>
</div
div that contain drop down
<div class="rightCol n mar ">
<span id="at1" class="spn">Click here to add add-on Services</span>
<ul id="ad1" class="drpdwn">
<li><input type="checkbox" id="ck1" value="1"><a id="a1">Drop Shadows</a></
li>
<li><input type="checkbox" id="ck2" value="2"><a id="a2">Reflections</a> <
li>
<li><input type="checkbox" id="ck3" value="6">General Spotting</a></li>
</ul>
I have tried this slide down while click
jQuery
slide down while click at1(Span)
this is the try for show on span on new div
here where should i use Push() most of them force me to use i don't know how and for what
var ots = [];
$('#at1,#at2,#at3,#at4,#at5,#at6').click(function(){
$(this).next('.drpdwn').stop().slideToggle();
}),
$('#ck1').click(function()
{
option=$('#a1').text();
$('.new ul').append('<li><span id="span1" alt="1" ></span></li>');
$('#span1').html(option).addClass('surr');
ots.push({id: 1});
}),
$('#ck2').click(function()
{
option=$('#a2').text();
$('.new ul').append('<li><span id="span2" alt="1" ></span></li>');
$('#span1').html(option).addClass('surr');
ots.push({id: 2});
}),
now i moved some value to array ots while append now the question is how to retrieve the newly created span's alt atrribute using array..?am using like these its not working clearly
some function
var f = $('.new span').length;
ad=o;
cs=o;
for(i=1;i<=f;i++)
{
$.each(this.opt, function() {
$.each(this, function(name, value) {
cs=eval($( "#span"+value).attr("alt"));
console.log(name + '=' + value);
ad+=cs;
console.log("ad: "+ad);
})
})
}
it shows ad as Nan and every time i click those id's it created like 1 then 1,2 then 1,2,3 like this help me out every time select check box it plays like this.!
push method is used to add new item in an array...so in your code push() was obivously used to push items to array(though i cannot find push methods in your question...so wouldn't be able to explain in your case)
docs
ex:
var sports = ["soccer", "baseball"];
sports.push("football", "swimming");

Mootools Click Event Problem

This peace of code works for the first click. but then it seems to not be able to get new ID from next click. the idea behind it is to show one piece of a form and with click on a button it hides first and shows second part. any idea what im doing wrong?
i guess it has something to do with "this" but from my understanding it should get the id from the second link also.
window.addEvent('domready', function()
{
$('page_2').slide('hide');
$('page_3').slide('hide');
$('page_4').slide('hide');
$('page_5').slide('hide');
var togglePrefix = 'toggle_', boxPrefix = 'page_', emptyPrefix = '';
var links = $('submit_box').getElements('a');
links.addEvent('click', function(e)
{
e.stop();
var id = $(this.get('id').replace(togglePrefix,emptyPrefix));
var id_new = parseInt($(this).get('id').replace(togglePrefix, emptyPrefix)) + 1;
var next = ('page_'+id_new);
var id_old = $(this.get('id').replace(togglePrefix,boxPrefix));
$(id_old).set('slide', {duration: 'long', transition: 'linear'});
$(id_old).slide('out');
$(next).slide('in');
});
});
the html follows this pattern:
<div id="page_1">
<div id="inhalt-gewinn">
<div id="gewinn_bild"></div>
<div id="gewinn_form">
<form id="gewinnspiel" name="gewinnspiel" method="post" action="<?=$_SERVER[PHP_SELF]; ?>">
<div id="input_box">
<div><input type="radio" name="frage1" value="Kamille" /><span>Kamille</span></div>
<div><input type="radio" name="frage1" value="Kaktus" /><span>Kaktus</span></div>
<div><input type="radio" name="frage1" value="Krokus" /><span>Krokus</span></div>
</div>
<div id="submit_box"><a id="toggle_1" class="frage">nächste Frage...</a></div>
</div>
<div id="gewinn_werbung"></div>
</div>
</div>
If I understand the example, you've got a bunch of divs with id page_1, page_2 and so on. In every div is a div with the id "submit_box". When you wrote $('submit_box').getElements('a') it will add the event only to the first div cause an id has to be unique. You cant have more then one element with a unique id in the page. So to get your example work change the id to a classname and use $$('div.submit_box a').
The use of ID´s multiple times on the page ruined the code!
After fixing this it worked fine

Categories