I have a couple of checkboxes. when any of them are clickd/checked and the search button is clicked, will grab their values and pass to the url as querystring and refresh the page returning results matching the passed query values.
like this: mysite.com/result.aspx?k="Hospital" OR "Office" OR "Emergency"
I am able to grab the values after 'k='. I have "Hospital" OR "Office" OR "Emergency" captured and stored in a variable. Now I need to reset the checked state of checkboxes based on these values after the page reloads and forgets the previous state of the controls. I couldn't move any further than this. Can someone help me?
var checkedOnes=decodeURI(location.href.match(/\&k\=(.+)/)[1]);
if (value.length == 2) {
$('input[name="LocType"][value="' + value[1] + '"]').prop('checked', true);
}
This is how I am capturing the checkboxes values and passing to the URL:
var checkboxValues = $("input[name=LocType]:checked").map(function() {
return "\"" + $(this).val() + "\"";}).get().join(" OR ");
window.location= url+checkboxValues;
<div class="LocTypeChkBoxesSearch">
<div class="LocTypeChkBoxes">
<input name="LocType" type="checkbox" value="Hospital"/>HOSPITALS
<input name="LocType" type="checkbox" value="Office"/> PHYSICIAN OFFICES
<input name="LocType" type="checkbox" value="Emergency"/>EMERGENCY CENTERS
<input name="LocType" type="checkbox" value="Out-Patient"/>OUT-PATIENT CENTERS
<input name="LocType" type="checkbox" value="Facility"/>FACILITIES
</div>
<div class="searchBtnHolder"><a class="searchButton" href="#" type="submit" ><span>GO</span></a></div>
</div>
I've faced same problem, and my solution is HTML5 Local Storage.
Add an function for colect checkboxes values
function(){
var data = $('input[name=checkboxName]:checked').map(function(){
return this.value;
}).get();
localStorage['data']=JSON.stringify(data);
}
And onload function to check checkboxes
function(){
if(localStorage&&localStorage["data"]){
var localStoredData=JSON.parse(localStorage["data"]);
var checkboxes=document.getElementsByName('checkboxName');
for(var i=0;i<checkboxes.length;i++){
for(var j=0;j<localStoredData.length;j++){
if(checkboxes[i].value==localStoredData[j]){
checkboxes[i].checked=true;
}
}
}
localStorage.removeItem('data');
}
}
It's work fine to me.
You shouldn't need JavaScript for this. You can check the $_GET parameters in your back-end code, and serve the page with the proper form element attributes.
In PHP, for example:
<input name="LocType" type="checkbox" value="Facility" <?php if (isset($_GET['LocType'] && $_GET['LocType'] == 'Facility') { ?> checked="checked" <?php } ?> /> FACILITIES
Try this.
//Split the url parameter value and get all the values in an array
var checkedOnes = decodeURI(location.href.match(/\&k\=(.+)/)[1]).split(" OR ");
//Find all the checkbox with name="LocType" and cache them in local variable
var $checkBoxes = $('input[name=LocType]');
//Loop through the array and find the corresponding checkbox element using filter
$.each(checkedOnes, function(i, val){
$checkBoxes.filter('value=[' + $.trim(val.replace(/\"/g, '')) +']').prop('checked', true);
});
I am splitting the value of k by OR which will give all the values in an array. Next, loop through the array and find the corresponding checkbox by matching its value attribute and set its checked property to true using prop method.
Related
I'm using DataTables with server-side processing to display tens of thousands rows. I need to filter these data by checkboxes. I was able to make one checkbox which is working fine, but I don't know how to add multiple checkboxes to work together. I found similar solution here, but my skills doesn't allow me to modify it to my needs:( Here is what I have tried..
My index.php:
Statuses:<br>
<input type="checkbox" id="0" onclick="myCheckFunc()" name="statuses">Open<br>
<input type="checkbox" id="1" onclick="myCheckFunc()" name="statuses">Closed<br>
<input type="checkbox" id="2" onclick="myCheckFunc()" name="statuses">Solved<br>
<script>
var idsa = 5;
$('input[name=statuses]').click(function(){
idsa = [];
$('input[name=statuses]:checked').each(function() {
idsa.push($(this).attr('id'));
});
idsa = idsa.join(",");
console.log("idsa fcia: " + idsa);
$('#example').DataTable().ajax.reload();
});
</script>
The idsa variable is initially set to 5, which means all statuses(no checkbox checked) then send to server side script with it's format(d) function (this part is working fine). This is how I modify sql query in server side script:
if ($_GET['idsa'] == 5){
$idsa = "0,1,2";
} else { if (isset($_GET['idsa'])) {
$idsa = "('" . str_replace(",", "','", $_GET['idsa']) . "')"; }
}
$whereAll = "STATUS IN ($idsa)";
EDIT:
Now after click on first of these three checkboxes, the data are filtered correctly (Open tickets with status 0), but uncheck don't bring back the initial state with all data. When I click on other two, the data are filtered, but when I uncheck, the data are fitered byt first filter (Open). When I click two or more checkboxes, I get this error:
An SQL error occurred: SQLSTATE[21000]: Cardinality violation: 1241
Operand should contain 1 column(s)
Ok, here is working code:
Status:<br>
<input type="checkbox" id="0" name="statuses">Open<br>
<input type="checkbox" id="1" name="statuses">Closed<br>
<input type="checkbox" id="2" name="statuses">Solved<br>
<script>
var idsa = 5;
$('input[name=statuses]').click(function(){
idsa = [];
$('input[name=statuses]:checked').each(function() {
idsa.push($(this).attr('id'));
});
idsa = idsa.join(",");
console.log("idsa fcia: " + idsa);
if (idsa == '') {
idsa = 5;
}
$('#example').DataTable().ajax.reload();
});
</script>
And in the server-side script:
if ($_GET['idsa'] == 5){
$idsa = "0,1,2";
} else {
$idsa = $_GET['idsa'];
}
$whereAll = "STATUS IN ($idsa)";
The problem was with the server-side part which I grabbed from someone else and there was added another comma. Now it's working fine. Thank you very much for your time.
Try wrapping your STATUS column name into backquotes, that seems to be a MySQL keyword
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;
});
}
});
I have input like this(Looping input form) :
<input id="check_<?php echo $value->id; ?>" value="<?php echo $value->id; ?>" type="checkbox" checked class="check_table get-report-filter">
and hidden input like this :
<input class="hiddenakun" type="hidden" name="hiddenakun" />
this my jquery :
var akun = [];
$('.get-report-filter').each(function() {
$('.get-report-filter').on('click', function() {
akun.push($(this).val());
}
});
my point is, I want to push each array data checked to .hiddenakun, but my code not working, I know it cause every time I write wrong code, datepicker wont work.
You can use .map() along with .get() to create an array of :checked checkboxes values
var akun = $('.get-report-filter:checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
If you want to set the value of checked event, then bind an event handler
var elems = $('.get-report-filter');
elems.on('change', function() {
var akun = elems.filter(':checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
});
Note, datepicker wont work. it's due to syntax error.
Try this:
$('.get-report-filter').each(function(){
if($(this).is(':checked'))
{
akun.push($(this).val());
}
});
// It will push the checked checkbox values to akun
You need more strict checker finder. Not all checkbox, but checked checboxes. For this purpose you can use pseudo class finder
$('.get-report-filter:checked').each
Find info here
https://api.jquery.com/checked-selector/
I have a list of products, each individual product has a checkbox value with the products id e.g. "321". When the products checkbox is checked (can be more than 1 selected) i require the value to be collected. Each product will also have a input text field for defining the Qty e.g "23" and i also require this Qty value to be collected. The Qty text input should only be collected if the checkbox is checked and the qty text value is greater than 1. The plan is to collect all these objects, put them in to a loop and finally turn them in to a string where i can then display the results.
So far i have managed to collect the checkbox values and put these into a string but i'm not sure how to collect the additional text Qty input values without breaking it. My understanding is that document.getElementsByTagName('input') is capable of collecting both input types as its basically looking for input tags, so i just need to work out how to collect and loop through both the checkboxes and the text inputs.
It was suggested that i use 2 if statements to accomplish this but i'm new to learning javascript so i'm not entirely sure how to go about it. I did try adding the if statement directly below the first (like you would in php) but this just seemed to break it completely so i assume that is wrong.
Here is my working code so far that collects the checkbox values and puts them in a string. If you select the checkbox and press the button the values are returned as a string. Please note nothing is currently appended to qty= because i dont know how to collect and loop the text input (this is what i need help with).
How can i collect the additional qty input value and append this number to qty=
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '/urlcheckout/add?product=', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + input_obj[i].value + '&qty=' + '|';
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
}
else {
alert('There is no checked checkbox');
}
}
<ul>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="311">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="321">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="98">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="javascript:checkbox_test()">Add selected to cart</button>
My answer has two parts: Part 1 is a fairly direct answer to your question, and Part 2 is a recommendation for a better way to do this that's maybe more robust and reliable.
Part 1 - Fairly Direct Answer
Instead of a second if to check for the text inputs, you can use a switch, like so:
var boxWasChecked = false;
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
switch(input_obj[i].type) {
case 'checkbox':
if (input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
boxWasChecked = true;
url = url + input_obj[i].value + ',qty=';
} else {
boxWasChecked = false;
}
break;
case 'text':
if (boxWasChecked) {
url = url + input_obj[i].value + '|';
boxWasChecked = false;
}
break;
}
}
Here's a fiddle showing it working that way.
Note that I added variable boxWasChecked so you know whether a Qty textbox's corresponding checkbox has been checked.
Also, I wasn't sure exactly how you wanted the final query string formatted, so I set it up as one parameter named product whose value is a pipe- and comma-separated string that you can parse to extract the values. So the url will look like this:
urlcheckout/add?product=321,qty=10|98,qty=5
That seemed better than having a bunch of parameters with the same names, although you can tweak the string building code as you see fit, obviously.
Part 2 - Recommendation for Better Way
All of that isn't a great way to do this, though, as it's highly dependent on the element positions in the DOM, so adding elements or moving them around could break things. A more robust way would be to establish a definitive link between each checkbox and its corresponding Qty textbox--for example, adding an attribute like data-product-id to each Qty textbox and setting its value to the corresponding checkbox's value.
Here's a fiddle showing that more robust way.
You'll see in there that I used getElementsByName() rather than getElementsByTagName(), using the name attributes that you had already included on the inputs:
checkboxes = document.getElementsByName('checked-product'),
qtyBoxes = document.getElementsByName('qty'),
First, I gather the checkboxes and use an object to keep track of which ones have been checked:
var checkedBoxes = {};
// loop through the checkboxes and find the checked ones
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
counter++;
checkedBoxes[checkboxes[i].value] = 1; // update later w/ real qty
}
}
Then I gather the Qty textboxes and, using the value of each one's data-product-id attribute (which I had to add to the markup), determine if its checkbox is checked:
// now get the entered Qtys for each checked box
for (i = 0; i < qtyBoxes.length; i++) {
pid = qtyBoxes[i].getAttribute('data-product-id');
if (checkedBoxes.hasOwnProperty(pid)) {
checkedBoxes[pid] = qtyBoxes[i].value;
}
}
Finally, I build the url using the checkedBoxes object:
// now build our url
Object.keys(checkedBoxes).forEach(function(k) {
url += [
k,
',qty=',
checkedBoxes[k],
'|'
].join('');
});
(Note that this way does not preserve the order of the items, though, so if your query string needs to list the items in the order in which they're displayed on the page, you'll need to use an array rather than an object.)
There are lots of ways to achieve what you're trying to do. Your original way will work, but hopefully this alternative way gives you an idea of how you might be able to achieve it more cleanly and reliably.
Check the below simplified version.
document.querySelector("#submitOrder").addEventListener('click', function(){
var checkStatus = document.querySelectorAll('#basket li'),
urls = [];
Array.prototype.forEach.call(checkStatus, function(item){
var details = item.childNodes,
urlTemplate = '/urlcheckout/add?product=',
url = urlTemplate += details[0].value + '&qty=' + details[1].value;
urls.push(url)
});
console.log(urls);
})
ul{ margin:0; padding:0}
<ul id="basket">
<li class="products"><input type="checkbox" value = "311" name="item"><input type="text"></li>
<li><input type="checkbox" value = "312" name="item"><input type="text"></li>
<li><input type="checkbox" value = "313" name="item"><input type="text"></li>
</ul>
<button id="submitOrder">Submit</button>
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>