Client-side searching in checkbox value - javascript

I need help.. for now I'm trying to create a client search but I don't know how to compare values from input text to checkboxes.
jsFiddle Example
Example:
jQuery("#searchBox").on("keyup paste", function() {
var value = jQuery(this).val().toUpperCase();
var rows = jQuery(".sp_country");
rows.hide();
if(value === '') {
rows.show();
return false;
}
//need something here to compare values on checkboxes and show does checkedbox who match
});
Here is my check box located
<span class="sp_country">
<input class="cp_country" style="cursor:pointer; display:none;" type="checkbox" name="country" value="Afghanistan"> Afghanistan
</span>

You can use .filter() method:
rows.filter(function() {
return $(this).text().toUpperCase().indexOf(value) > -1;
}).show();
Or in case that you want to compare the input with value of checkboxes:
rows.filter(function(){
return this.children[0].value.toUpperCase().indexOf(value) > -1;
}).show();
You can can also use the jQuery's .find() method for selecting the input descendants.

Try this
$("cp_country").each(function(){
if($(this).val()==("#searchBox").val()){
$(this).parent(".sp_country").show();
}
});
Whole idea is:
iterate through each of the checkbox value
if the value matches with search box value then
show the parent span element

Try this:
$("#searchBox").on("keyup paste", function() {
var value = $(this).val().toUpperCase();
var rows = $(".cp_country");
rows.hide();
if(value === '') {
rows.show();
return false;
}
else{
rows.each(function(){
if($(this).val().toUpperCase().indexOf(value) != -1){
$(this).show();
}
else{ $(this).hide();}
});
}
});

Related

How to keep a stored array of input checkbox value?

I have a input checkbox that act as a category filter. I want to store only those values of input checkboxes in an array that are checked in a var checkedAttr. Then do a test if any of the already existing values match any in the array and if it does delete it. The problem I'm having is that... when an input checkbox is clicked, it will store it as many times as the $each loop goes or input checkboxes there are, in this case (three times). I also noticed when unchecking more than one, then rechecking the same one, it will add the values as many times as the $each loop goes and will somehow bypass deleting from the array. I just want to simply add (checked values) / delete (unchecked values) from the array every time the user checks or unchecks.
Here's a jsfiddle.
HTML:
<div id="category-list">
<h1>Categories</h1>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>
jQuery:
var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
if($(this).is(':checked')) // checked
{
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
$('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
{
checkedAttr.push(value); // add value to array
console.log("checkedAttr:", checkedAttr);
}
else // if it does match...
{
checkedAttr.splice(i, 1);// remove it from array
console.log("checkedAttr:", checkedAttr);
}
});
// check which attributes are checked and store in 'checkedAttr' array
//$('input[name=filter]').each(function(i, item){
//});
}
else // unchecked
{
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
Check it Brother its working as you want
var checkedAttr = [];
$('#category-list :checkbox').change(function()
{
checkedAttr = [];
$('#category-list :checkbox').each(function(i, item){
if($(item).is(':checked'))
{
checkedAttr.push($(item).val());
}
});
console.log("checkedAttr:", checkedAttr);
});
You can also check it in JSFiddle
https://jsfiddle.net/xdrLra77/
You can do it simply with a mapcall
var checkedAttr = [];
$('#category-list :checkbox').change(function() {
checkedAttr = $('#category-list :checked').map(function(){
return $(this).val();
}).get();
console.log(checkedAttr);
});
(Updated jFiddle)
(Edit: better yet, put the condition in the jQuery selector)
Edited
var checkedAttr = []; // array for checked attributes
//first load, see what is checked
$('#category-list :checkbox').each(function(){
if($(this).is(':checked')) // checked
checkedAttr.push($(this).val())
})
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
var position = checkedAttr.indexOf($(this).val());
if($(this).is(':checked')) // checked
{
if(position == -1){ // dnot exist in array, add
checkedAttr.push($(this).val());
console.log("checkedAttr:", checkedAttr);
}else{ // exist in array, do nothing
//do nothing
}
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
else // unchecked
{
if(position == -1){ // dont exist in array, do nothing
//do nothing
}else{ // exist in array, remove
checkedAttr.splice(position,1);
console.log("checkedAttr:", checkedAttr);
}
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
You can get the checked elements by using $('.categories:checked'). Then you may iterate through those values to get the actual values
var checkedValues= $('.categories:checked');
var valuesArray=[];
$.each(checkedValues, function(checkedValue){
valuesArray.push(checkedValue.value)
}
Use $.inArray:
if (index === -1 && $(this).is(':checked')) {
checkedAttr.push(value); // add value to array
console.log("added:", checkedAttr);
} else if (index !== -1 && ! $(this).is(':checked')) {
checkedAttr.splice(index, 1);// remove it from array
console.log("removed:", checkedAttr);
}
Amended fiddle: https://jsfiddle.net/o1rmz1o1/4/

Check for partial match in JavaScript if statement

I've got elements set up something like this:
<div class="cat" data-cat="example-cat, test-cat, test-category">
...
</div>
<div class="cat" data-cat="test-category">
...
</div>
<div class="cat">
...
<div class="cat" data-cat="example-cat, test-category">
...
</div>
<div class="cat" data-cat="test-category, one-more-cat">
...
</div>
</div>
Using JavaScript, I need to check each bit of text between commas for a match with a user selected value. For example, if the user selected "test-cat," I need to check each div to see if data-cat matches the selection. If it does, I need to add class="active" to each matching div.
Part of the trick is that if the user selects test-cat, a div with a data-cat of test-category should not return positive. Only exact matches should be consider matches.
I had already set up a complex filtering system with support for multiple filters, but the client wants to be able to set multiple categories per div, which is making this tricky. I have a script set up to show matches if the attribute is an exact match, and I'll be trying to modify this to work as I need it to:
$(document).ready(function() {
var changedOnce = false;
$("#filters select").change(function() {
$(".cat").each(function() {
$(this).attr("data-match", "true");
$(this).removeClass("open");
});
$("#filters select").each(function() {
var filter = $(this).attr("name");
var value = $(this).val();
$(".cat").each(function() {
if ($(this).attr("data-match") === "false") {
return true;
}
var attr = $(this).attr("data-" + filter);
var childAttr = $(this).find(".cat").attr("data-" + filter)
if ((typeof attr !== typeof undefined && attr !== false) || (typeof childAttr !== typeof undefined && childAttr !== false)) {
if ($(this).attr("data-" + filter) === value || $(this).find(".cat").attr("data-" + filter) === value || value === "") {
$(this).attr("data-match", "true");
$(this).parents(".cat").attr("data-match", "true");
} else {
$(this).attr("data-match", "false");
return true;
}
} else {
if (value !== "") {
$(this).attr("data-match", "false");
return true;
} else {
$(this).attr("data-match", "true");
$(this).parents(".cat").attr("data-match", "true");
}
}
});
});
});
});
My filters are set up something like:
<div id="filters">
<select name="cat">
<option value="test-cat">Test Cat</option>
<option value="example-cat">Example Cat</option>
...
</select>
...
<select name="nth-filter">
...
</select>
</div>
It's probably not the most elegant solution (I'm no JavaScript master), but it was working, until I made this most recent change. If you need more information, just let me know.
UPDATE: Here's my current script, using .data() and .split() as suggested. I'm having trouble getting the parent category to show as a miss if all its children are misses, but I'll post a separate question for that.
$(document).ready(function() {
$("#filters select").change(function() {
$(".cat").each(function() {
$(this).data("match", true);
$(this).css("opacity", "1");
// $(this).removeClass("open");
});
$("#filters select").each(function() {
var filter = $(this).attr("name");
var value = $(this).val();
$(".cat").not(".primary").each(function() {
if ($(this).data(filter)) {
var match = $(this).data("match");
var attributes = $(this).data(filter).split(", ");
var i = 0;
$(attributes).each(function() {
if (value && attributes[i] !== value) {
match = false;
} else {
match = true;
return true;
}
i++;
});
$(this).data("match", match);
}
if ($(this).data("match") === false) {
$(this).css("opacity", "0.25");
} else {
$(this).css("opacity", "1");
}
});
});
});
});
You can use the String's split function to split the comma-separated values into an array, and then use the Array's indexOf function to check for a match.
var attr = $(this).attr("data-" + filter);
if (attr && (attr.split(/[\s*,\s*]+/).indexOf() >= 0)) {
Note: I left out this part of the check: attr !== false. attr should either be a String or undefined, so it will never be false. Did you mean to check if it is the string "false"?
Also, when you call the following:
var childAttr = $(this).find(".cat").attr("data-" + filter)
You should be aware that .attr() will return the value of the first matched element, and from your markup it looks like there could be multiple matched elements.

jQuery multiple select option search results

I have 5 selection boxes and I want to get all option selected values into a variable like this: val+val+val+val
Below you can see my code, but it's not full working because if I have nothing selected I get +++++
if($('select').attr("selectedIndex") == 0) {
var allVariables = $("select option:selected").map(function(){
return this.value
}).get().join("+");
}
What am I missing?
It was returning empty values because your select option headers still represent a user selection, they just have no value. So add in a check for a value before you return it:
$('.find').click(function(e){
var Scat = $('#Scat option:selected').val();
var allVariables = $("select option:selected").map(function(){
if(this.value!=""){ //only return if we have a value
return this.value;
}
}).get().join('+');
alert(allVariables);
if(Scat == ""){
alert("Choose a Category");
} else {
// do something else
};
});

Displaying array from values in a dynamic div

Im would like to know how can I get the values from the div span and create a array() with which I could later on create a query to the database. Im trying to figure it somehow out but I just can't.
HTML
<form>
<span class="input-component"><input type="text"/><a href=#></a></span>
</form>
<br><br>
<div id="numcontainer">
<span class="containernum"></span><br>
</div>
Java script
jQuery(function($) {
var values = [];
$('#numcontainer').on('click', 'a.js-delete', function(e) {
$(this).prev().remove(); // the <span>
$(this).next().remove(); // the <br>
$(this).remove(); // the <a> itself
});
$('form input[type=text]').change(fileChangeHandler);
function fileChangeHandler() {
var form = $(this).closest('form');
}
var form = $(this).closest('form');
$('form .input-component input').on("propertychange keyup input paste",addInput);
onlyNums($('form .input-component input'));
function addInput() {
var remainingChars = $(this).val().length;
if (remainingChars == 24) {
if ($('.containernum').text() == '') {
$('.containernum').text($(this).val());
} else {
$('#numcontainer').append('<span class="containernum">'+$(this).val()+'</span><a class="js-delete href=#>[X]</a><br>');
}
$(this).val(''); // does empty the text input
$('.containernum').each(function(index){
// Your code
console.log( $(this).html() );
});
values.push($(this).val());
console.log(values);
}
}
function onlyNums($elem){
$elem.keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
}
});
Example jsFiddle
Thanks for your time
You want to store values; why not use hidden inputs? Instead of creating spans with the same class, create input elements with the same name.
<div id="numcontainer">
<input type="hidden" name="myNums" value="305" />
<input type="hidden" name="myNums" value="49" />
</div>
Then, when you want to get the values you would just need to do something like this:
var values = [];
$("#numcontainer input:hidden[name='myNums']").each(function() {
values.push( $(this).val() );
});
If your values aren't related, you just name them something different.
$('span.containernum').html()
OR
$('span.containernum').text()
would do the trick. You will got the html string that you can implode or do whatever you want.
See https://stackoverflow.com/a/1910830/2806497 for the difference between the two functions.

How to hide the parent of an unchecked checkbox?

I have a set of random/dynamic generated div checkboxes:
<div>A1 <input type='checkbox' name='A[]' value='A1'> </div>
<div>A2 <input type='checkbox' name='A[]' value='A2'> </div>
<div>A3 <input type='checkbox' name='A[]' value='A3'> </div>
<div>B1 <input type='checkbox' name='B[]' value='B1'> </div>
<div>B2 <input type='checkbox' name='B[]' value='B2'> </div>
<div>C1 <input type='checkbox' name='C[]' value='C1'> </div>
What I am trying to do is when the user:
checks any A then the others will hide (entire div) but all A will still show.
unchecks a checkbox, then all A, B, C will show again.
This is because I am preventing the user from checking a mix of options.
PS:
You can provide a solution that might need me to modify the generated output of checkboxes.
try this fiddle
$("input[type=checkbox]").on("change", function() {
var thisName = $(this).attr("name");
if($(this).is(':checked')){
$(':checkbox').parent().hide();
$('input:checkbox[name|="'+thisName+'"]').parent().show();
} else {
$(':checkbox').parent().show();
}
});​
Try this one,
$('input:checkbox').click(function(){
if($(this).attr('checked') == 'checked'){
$('input:checkbox').parent('div').hide();
$('input:checkbox[name="'+$(this).attr('name')+'"]').parent('div').show();
}else{
if(!$('input:checkbox[checked="checked"]').length){
$('input:checkbox').parent('div').show();
}
}
})
​
Demo: http://jsfiddle.net/muthkum/uRd3e/3/
You can use some JQuery traversing to hide the non-matching elements:
// add the event handler
$("input[type=checkbox]").on("change", function() {
// get whether checked or unchecked
var checked = $(this).prop("checked") === true;
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the name of the clicked element (eg, "A[]")
var thisName = $(this).prop("name");
// get the grandparent element
$(this).parent().parent()
// get all the checkboxes
.find("input[type=checkbox]")
// filter to only the ones that don't match the current name
.filter(function(i, e) { return e.name != thisName; })
// hide or display them
.css("display", checked ? "none" : "");
});
you can simple do it like this
$('input[type=checkbox]').change(function () {
if ($(this).attr('checked')) {
var Name = $(this).prop("name");
$('div').filter(function(){
return $(this).find('input[type=checkbox]').prop("name") != Name;
}).hide();
}
else
{
$('input[type=checkbox]').attr('checked',false);
$('input[type=checkbox]').parent('div').show();
}
});​
Live Demo
Try code bellow:
$(":checkbox").click(function() {
var identifier = $(this).val().substring(0, 1);
$("input[type='checkbox']").each(function() {
if ($(this).val().indexOf(identifier) != -1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
if ($("input:checked").length == 0) {
$("input[type='checkbox']").parent().show();
}
});
You can try on jsFiddle
This will hide all other checkbox types when FIRST of a type is checked and show all the other checkbox types when ALL of the checked box type are unchecked:
$("input:checkbox").on("change", function() {
// get the name attribute
var nameAttr = $(this).prop("name");
// check how many checkbox inputs of that name attribute are checked
var checkedLength = $("input:checkbox[name=\"" + nameAttr + "\"]:checked").length;
// if 0, display other checkbox inputs, else if 1 hide all of the rest
if(checkedLength == 0) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().show();
}else if(checkedLength == 1) {
$("input:checkbox[name!=\"" + nameAttr + "\"]").parent().hide();
}
});
Overwhelmed by choice! Here's a plain JS version that just disables members of the non–selected groups.
I think that's better than hiding them so users can see the other options after they've selected one. Otherwise, to see the other options again, they must deselect all checkboxes in the group.
Note that div is a parent of the inputs, the listener passes a reference to the element and the related event object, modify as required.
<script>
function doStuff(div, evt) {
var checked, el, group, j, inputs, name, re;
var t = evt.target || evt.srcElement;
if (t.nodeName && t.nodeName.toLowerCase() == 'input' && t.type == 'checkbox') {
inputs = div.getElementsByTagName('input');
name = t.name;
// Set checked to true if any input with this name is checked
group = document.getElementsByName(name);
j = group.length;
while (j-- && !checked) {
checked = group[j].checked;
}
// Loop over inputs, hide or show depending on tests
for (var i=0, iLen=inputs.length; i<iLen; i++) {
el = inputs[i];
// If name doesn't match, disable
el.disabled = checked? (el.name != name) : false;
}
}
}
</script>
<div onclick="doStuff(this, event)">
<div>A1 <input type='checkbox' name='A[]' value='A1'></div>
<div>A2 <input type='checkbox' name='A[]' value='A2'></div>
<div>A3 <input type='checkbox' name='A[]' value='A3'></div>
<div>B1 <input type='checkbox' name='B[]' value='B1'></div>
<div>B2 <input type='checkbox' name='B[]' value='B2'></div>
<div>C1 <input type='checkbox' name='C[]' value='C1'></div>
</div>
Thanks guys, especially dbaseman (get me ideal) :
ok, Here is my code after referring from you all.
$("input[type=checkbox]").on("click", function() {
var sta = $(this).is(":checked"); sta=(sta==true?1:0);
if(sta==1){
var thisName = $(this).prop("name"); thisName=thisName.replace("[]","");
$("div input[type=checkbox]:not([name^=" + thisName + "])").parent().hide();
}else{
var num = $("[type=checkbox]:checked").length;
if(num==0){
$("div input[type=checkbox]").parent().show();
}
}
});
so far code able is performing as what i need.
Ps: i am still weak on jquery travelling part
Ps: Edited on re-opening all checkboxes part
Thanks once again!

Categories

Resources