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)
Related
I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});
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 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]);
});
I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});
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>