I have many inputs with class filter:
<ul>
<li>
<a><input class="filter" name="filter[manufacturer][]" type="checkbox"> Other (18)</a>
</li>
<li>
<a><input class="filter" name="filter[manufacturer][JOBY]" type="checkbox"> JOBY (2)</a>
</li>
<li>
<a><input class="filter" name="filter[manufacturer][Beurer]" type="checkbox"> Beurer (1)</a>
</li>
<li><a>
<input class="filter" name="filter[manufacturer][Obreey Products]" type="checkbox"> Obreey Products (1)</a>
</li>
</ul>
And i need to loop every input with JavaScript or JQuery and call cl.facetFilter(name, name2) function if input checkbox is checked:
For example if checkbox name is filter[manufacturer][JOBY] and input is checked, i need to call:
cl.facetFilter('manufacturer', 'JOBY');
If checkbox name filter[manufacturer][] and input is checked, i need to call:
cl.facetFilter('manufacturer', '');
Thanks for help
You can do:
$(".filter:checked").each(function() {
var name = $(".filter").attr("name");
name = name.split("[");
name[1] = name[1].substring(0, name[1].length - 1);
name[2] = name[2].substring(0, name[2].length - 1);
cl.facetFilter(name[1], name[2]);
});
Demo: http://jsfiddle.net/tymeJV/MfAsA/ -- I logged the results rather than call a func in the demo.
At its simplest I'd suggest, albeit untested:
$('.filter').each(function () {
var self = this;
if (self.checked && self.name) {
var names = self.name.match(/\[(.+)\]/)[1].split('][');
c1.facetFilter(names[0],names[1]);
}
});
JS Fiddle demo.
Note, in the demo I'm, obviously, using a different function-name and also setting the checkboxes to be checked (for the purposes of demonstration).
References:
each().
JavaScript Regular Expressions.
String.match().
String.split().
This jQuery should do what you need:
$('.filter:checked').each(function(index, elem) {
elem = $(elem);
var result = elem.attr('name').match(/\[[a-zA-Z0-9 ]*\]/g);
if (result.length == 2) { // Sanity check
cl.facetFilter(result[0], result[1]);
}
});
The :checked portion of the selector should filter out any unchecked input boxes, and the regex match should pick out the values in the two sets of brackets. If that notation isn't necessary, though, I would advise a simpler formatting (e.g. filter|manufacturer|JOBY) so you could do a simple .split() on the separator character.
Some icky string manipulation, but this will call the function with the correct parameters when you check the relevant box:
$('.filter').click(function(e){
if($(this).is(':checked')){
$name = $(this).attr('name');
$names = $name.split('[');
$attr1 = $names[1].replace(']', '');
$attr2 = $names[2].replace(']', '');
console.log('cl.facetFilter(\''+$attr1+'\', \'' +$attr2+'\')');
}
});
If you're loading the document with some boxes already checked, then the $('.filter:checked').each(function() {... syntax will get you there.
JSFiddle link
$("input.filter:checked").each(function() {
var parts = /\[(.*)\]\[(.*)\]/g.exec(this.name);
cl.facetFilter(parts[1], parts[2]);
});
Related
I am creating an A/B test variant using VWO.
The website has a list with checkboxes laid out like so;
<ol>
<li>
<label>
<input class="checkBox" type="checkbox">
<p class="checkBoxAnc">Text to grab</p>
</label>
</li>
</ol>
There is an apply button, when this is clicked I want it to cycle through all of the inputs. If checked is true then I need to grab the text from the class "checkBoxAnc" (p element) and concatenate it to a variable.
I have tried the following:
var self= $(this);
//This is referring to the input that the user has clicked, so class '.checkBox'
self.next() // This doesn't work as element's do not match
self.nextUntil('.checkBoxAnc') // Same issue as .next()
var checkBoxSibling = self.parent().find('.checkBoxAnc').text();
// This returns an empty string
When trying to find the parent type this is being returned as 'undefined' rather than 'label'
Are there any other techniques to access '.checkBoxAnc'?
Something like this...
var foo = '';
$('input[type=checkbox]:checked').map(function() {
foo += $(this).next().text(); // value your looking for
}).get();
https://jsfiddle.net/cmac_/8w7vghbt/
There is a list of checkboxes, that change on container li click.
Here is one for example, and the rest of them are the same (except for a few id's and classes , that dynamically change like #lips here)
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="lips" checked="checked">
<label for="Lips..." class="lips">
Lips
</label>
</li>
on click, .filtercheck gets class of .checkchecked (if it helps)
there is also a list of links
<div class="collectionurls">
<a class="colurls colurl1" href="/collections/lips"></a>
<a class="colurls colurl2" href="/collections/face-lips"></a>
<a class="colurls colurl3" href="/collections/face-cheeks"></a>
</div>
I'm trying to compare checkbox id, when .lifilter is clicked to that list of urls, pick one that has all the checked id's, add it to current domain, and redirect page there.
For example: Let's say, #face is already checked, site visitor clicks on #lips. Script checks .colurls for face and lips. In our case, finds .colurl2, gets its href, adds to curdomain, and redirects page to domain.com/collections/face-leeps
There is a pretty long script of forming these id's and classes, but i got really stuck here.
$(document).ready(function(){
var curdomain = document.domain;
//id's and classes forming code
$('.lifilter').click(function(){
//compare ids to hrefs
var addurl = // that class attr('href')
var curdomain = curdomain + addurl;
window.location = curdomain;
});
});
I'm pretty new to js, and have no clue where to go from here. And there is most likely a syntax error where i'm combining vars.
Help a noob out plz
Seems like a strange way to do the navigation, but I would do this like so:
Build an array of jQuery attribute contains selectors, using all the checked checkboxes and Array.map()
Join those selectors together and apply the resulting multiple attribute selector
Check how many results you get. Once you have narrowed-down to one result, you have enough information to redirect.
There's a running snippet below. It doesn't actually redirect, but shows the redirect location, or the number of possible results.
$(".filtercheck").on("click", function() {
//build an array of jQuery contains selectors
var selected = $(".filtercheck:checked").get().map(function(item) {
return '[href*="' + item.id + '"]';
});
//join the selectors into a continuous string
var selector = selected.join('');
//run the jQuery selectors
var result = $(".collectionurls " + selector);
//if there is one result you can successfully navigate
if (result.length === 1) {
var href = result.attr("href");
$("#result").val(href);
//window.location = href; //uncomment to redirect
}
else {
$("#result").val(result.length + " results");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="face" checked>
<label for="face" class="face">
Face
</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="lips">
<label for="lips" class="lips">
Lips
</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="cheeks">
<label for="cheeks" class="cheeks">
Cheeks
</label>
</li>
</ul>
<div class="collectionurls">
<a class="colurls colurl1" href="/collections/lips"></a>
<a class="colurls colurl2" href="/collections/face-lips"></a>
<a class="colurls colurl3" href="/collections/face-cheeks"></a>
</div>
<input id="result" />
From what I'm gathering, you'll need to go through the checked checkboxes on your page and concatenate them together. The easiest way may be with map. You mentioned that the checked checkboxes get the class checkchecked, so:
var url = '/collections/' + $('.checkchecked').map(function (index, element) {
return this.id;
}).join('-');
However, the order of the items in the URL will depend on the order in the document. For instance, if the lips checkbox comes before the face checkbox in document order, the url will be '/collections/face-lips', but if the opposite is true, it will be '/collections/lips-face'.
If there needs to be a defined order, sort the array returned by map:
var parts = $('.checkchecked').map(function (index, element) {
return this.id;
}).sort(); // This will sort them alphabetically
var url = '/collections/' + parts.join('-');
If you have a preset order, store that order in a separate array:
var order = [ 'face', 'cheeks', 'lips' ];
var parts = $('.checkchecked').map(function (index, element) {
return this.id;
}).sort(function (a, b) {
return order.indexOf(a) - order.indexOf(b);
}); // This will sort by separate "order"
var url = '/collections/' + parts.join('-');
I have following code
<li>
<input type="checkbox" value="1" class="filter" name="Bedroom">
<a id="1" href="javascript:void(0)" class="filter1"> Bedroom </a>
</li>
<li>
<input type="checkbox" value="7" class="filter" name="Living Room">
<a id="7" href="javascript:void(0)" class="filter1"> Living Room </a>
</li>
<li>
<input type="checkbox" value="6" class="filter" name="Corridor">
<a id="6" href="javascript:void(0)" class="filter1"> Corridor </a>
</li>
</ul>
java script
<script>
var id='';
jQuery('.filter').click(function(){
jQuery('.filter').each(function(){
if(jQuery(this).attr('checked'))
{
id+=jQuery(this).val()+',';
}
});
alert(id);
jQuery.get('<?php echo $this->getUrl('some url') ?>',{cat:id},function(data){
jQuery('#id').html(data);
});
});
</script>
Suppose I checked a checkbox I am getting the id of that check box.
id+=jQuery(this).val()+',';
How to remove the the id of element on unchecking a checkbox from id variable ?
I am trying to make an ajax call,When I click on the check boxes then I should get
a url containing the ids of the checkboxes example .../?cat=7%2C7%2C6%2C
and on unchecking the check boxes those check boxes ids should not be present
You will be creating duplicate ids in the list, an easy solution is to recreate the id string every time like
var id;
var $checks = jQuery('.filter').change(function () {
id= $checks.filter(':checked').map(function () {
return this.value;
}).get().join(', ');
console.log(id);
});
Demo: Fiddle
If I understand your question correctly, below is the javascript that you are looking for:
var id='';
$('.filter').click(function(){
id='';
$('.filter').each(function(){
if(this.checked)
{
id+=$(this).val()+',';
}
});
alert(id);
});
I think the key is to re-initialize the id variable to blank, so you do not keep adding values to it.
jsFiddle for working example
Don't use a String, but use an array:
var ids = new Array();
For the check don't use the click event, but the change event:
$(".filter").change(function() {
if ($(this).prop("checked") == true) {
// Add the id to the list
ids.push($(this).attr("id")); // Note the attribute, not the val()!
} else {
var index = -1;
$.each(ids, function(idx, value) {
if (value == $(this).attr("id")) index = idx;
});
ids.splice(idx, 1); //Remove the id
}
}
Consider another approach.
var ids = [];
jQuery('.filter').change(function(){
ids = []; // Reinitialize array
jQuery('.filter:checked').each(function(){
ids.push(this.value);
});
alert(ids.join(',')); // Stringifies your array, using a comma as a separator.
});
// You have access to ID's in outer scope as well!
Some may consider it a "performance hit" by reinitializing every time,
but seeing as you only have very few checkboxes, I see no problem.
Your original question text was:
How to remove the id of element on unchecking a checkbox?
Answer:
jQuery('.mySelector').each(function() {
jQuery(this).removeAttr('id');
}
You may test this snippet on any website that loads jQuery, i.e. jquery.com - open in browser, hit F12 and paste this into the console (and watch it destroy the whole CSS ;) ):
$('div').each(function() { $(this).removeAttr('id'); }
Update:
From reading your updated question, i believe what you are asking for is pretty much covered by the answers above.
My two cents: id was (and still is) amiguous in your question context, better names for the variable would be ids, csvIdString, concatenatedCheckboxIds, or whatever describes the variable best in its context (following Clean Code Philosophy)
I am using javascript to hide some list Items based on the user role.
I am getting the role from a list item's text(). When I am comparing the $("#activeUser").text() value against a string, it is not working.
HTML Block that I am using in my javascript to get the text() value of a list item.
<ul class="pull-right breadcrumb">
<li>Home <span class="divider">/</span> </li>
<li id="activeUser" class="active"> <?php echo ucfirst($_SESSION['sewafs_user_role']); ?> </li>
</ul>
Javascript
$(document).ready(function () {
var testRole = $("#activeUser").text();
//This block of code works
role = 'Guest';
if (role == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
//This doesn't work why?
if (testRole == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
But if I see the value of the var testRole using alert it prints Guest.
I tried converting the testRole value into string using testRole.toString() / string(testRole) method, but nothing helped.
Please let me know, where I am going wrong. Thanks.
The problem seems to be extra white-spaces in the value that you receive from $("#activeUser").text()
Solution:
You must trim the value and then use it for comparison as:
var testRole = $("#activeUser").text().trim();
OR
var testRole = $.trim($("#activeUser").text());
OR
var testRole = $("#activeUser").text();
testRole = $.trim(testRole);
Any of the above will work.
More info on jQuery trim at this link.
Whitespace test:
If you want to test if you are getting extra white spaces, then try below javascript code:
alert("-" + $("#activeUser").text() + "-");
If you get "" then you dont have whitespaces in your received value.
But if you get spaces after < or before >, then these are white spaces, that are spoiling your party.
Try trimming the string, with $.trim($("#activeUser").text());
There seem to be whitespaces in your element.
You need to trim white spaces at start and end of the string:
var testRole = $("#activeUser").text().replace(/^\s+|\s+$/g,'');
You can see why here: http://jsfiddle.net/AfUZR/1/
Demo
$(document).ready(function () {
var testRole = $("#activeUser").text().trim();
//This doesn't work why?
if (testRole == "Guest") {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
Man, first what do you must do it, it's write correct selector.
$("#request_history_li").hide();
$("#assign_role_li").hide();
you can write
$("#request_history_li, #assign_role_li").hide();
or you can add the same classes of these Elements, that is correct
<ul>
<li class="same_class 1"></li>
<li class="same_class 2"></li>
</ul>
and
$(".same_class").hide();
ok? next:
As concerns your problem, js loaded earlier than you determine the role of, use
$(document).ready(function(){
......
});
I'm using Zend_Form to output a set group of checkboxes:
<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>
With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:
$("input[#name='user_group[]']").val()
but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?
You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):
$("input[name='user_group[]']:checked")
With those checked items, you can either create a collection of those values or do something to the collection:
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});
I'm not sure about the "#" used in the selector. At least with the latest jQuery, I had to remove the # to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
Now both, items and about work.
Use .map() (adapted from the example at http://api.jquery.com/map/):
var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
return $(domElement).val();
});
With map in instead of each it is possible to avoid the array creation step:
var checkedCheckboxesValues =
$('input:checkbox[name="groupName"]:checked')
.map(function() {
return $(this).val();
}).get();
From the map() page of the docs:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values
get() turns those values into an array.
mhata dzenyu mese. its actually
var selectedGroups = new Array();
$(".user_group[checked]").each(function() {
selectedGroups.push($(this).val());
});
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[#name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:
("input[#name='user_group[]']").each( function() {
alert($(this).val());
});
Of course a better selector is available:
$(':checkbox')
var values = $("input[name='user_group']:checked").map(function(){
return $(this).val();
}).get();
This will give you all the values of the checked boxed in an array.
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
$(document).ready(function(){
$('#btnskillgroup').click(function(){
getCheckedGroups('skills');
});
$('#btncitiesgroup').click(function(){
getCheckedGroups('cities');
});
var getCheckedGroups = function(groupname){
var result = $('input[name="'+groupname+'"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#div'+groupname).html(resultstring);
}else{
$('#div'+groupname).html(" No checkbox is Checked");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Skills:<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<br>
<input type="checkbox" name="cities" value="Pune"> Pune
<input type="checkbox" name="cities" value="Baramati"> Baramati
<input type="checkbox" name="cities" value="London"> London
<input type="submit" id="btnskillgroup" value="Get Checked Skill group">
<input type="submit" id="btncitiesgroup" value="Get cities checked group">
<div id="divskills"></div>
<div id="divcities"></div>