0

I am trying to use checkboxes to filter page content. I got it to hide content when I check the box, but it does not show all content again when unchecked. Any help would be greatly appreciated. Thank you in advance.

$(document).ready(function() {
$('input').change(function(){
    $('input').each(function(){
        var checked;
        if (checked = $(this).attr('checked'));
        var reclessons = $('li[data-rec='+$(this).data('rec')+']');
        checked ?  reclessons.show('slow'): reclessons.hide('slow');
    });
    var unchecked=0;
    if(unchecked=0){$('li').show('slow');}
});
});
3
  • 1
    Just a recommendation, give the filtering checkboxes their own class and select them by that instead of selecting all inputs. Commented Oct 8, 2013 at 17:12
  • 2
    Neither of your if statements have == Commented Oct 8, 2013 at 17:14
  • The first is short hand, the second is a mistake Commented Oct 8, 2013 at 17:32

3 Answers 3

1

This is the basis for what you want. Note the prop for checked.

http://jsfiddle.net/stevemarvell/kEkdy/

<input type="checkbox" data-target="thing1" checked="1"/>
<div id="thing1">Thing 1</div>
<input type="checkbox" data-target="thing2" checked="1"/>
<div id="thing2">Thing 2</div>

With this jquery:

$(document).ready(function() {
    $('input[type=checkbox][data-target]').change(function() {
        var checked = $(this).prop('checked');
        var target = $(this).data('target');
        $('#' + target).toggle(checked);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

.attr() method doesn't return a boolean value, also = is assignment, you don't compare the values, you should use == or === operator for comparison.

var $ch = $('input[type=checkbox]');
$ch.change(function() {
    // show/hide the related `li` element
    $('li[data-rec='+$(this).data('rec')+']').toggle(this.checked);
    // show all `li` elements if there is no checked checkbox 
    if ( $ch.filter(':checked').length === 0 ) {
       $('li').show();
    } 
});

8 Comments

you should really use .prop("checked")
@stevemarvell Why? .prop('checked') returns value of the .checked property i.e this.checked. There is no difference.
But for the fact that .prop() is made for the job and .checked is an undocumented feature.
@stevemarvell Actually .prop() doesn't belong to any standard. It's just a (helper) method of the jQuery object, w3.org/TR/2012/WD-html5-20121025/…
Lots of what are being used are documented helper functions.
|
0

Here I used cuisines for my checkbox items. The following code snippet gives the logic for checkboxes filtering. handleCuisineChange is the function that contains the logic. The length of for loop is 8 since the number of cuisines (the number of checkbox items) I have taken here is 8. Replace the cuisines here with your checkbox data. Apply this logic and your checkbox items are ready for filtering.

Inside axios I used my own backend API getCuisine and port number 7000.

handleCuisineChange=(cuisine_id)=>
    {
        const {cuisineArray}=this.state; //an empty array declared in constructor
       
        if (cuisineArray.indexOf(cuisine_id) == -1)
        {
            cuisineArray.push(cuisine_id);
        }
        else
        {
            var index=cuisineArray.indexOf(cuisine_id);
            cuisineArray.splice(index,1);
        }    

        const {cuisineArray2}=this.state; //an empty array declared in constructor
        let i=0;
        for (i=0;i<8;i++)
        {
            if(cuisineArray[i]==undefined)
            {
                cuisineArray2[i]=cuisineArray[0];
            }
            else
            {
                cuisineArray2[i]=cuisineArray[i];
            }
        }

        this.props.history.push(`/checking3?cuisine_id1=${cuisineArray2[0]}&cuisine_id2=${cuisineArray2[1]}&cuisine_id3=${cuisineArray2[2]}&cuisine_id4=${cuisineArray2[3]}&cuisine_id5=${cuisineArray2[4]}&cuisine_id6=${cuisineArray2[5]}&cuisine_id7=${cuisineArray2[6]}&cuisine_id8=${cuisineArray2[7]}`);
        let filterObj={cuisine_id1:cuisineArray2[0],cuisine_id2:cuisineArray2[1],cuisine_id3:cuisineArray2[2],cuisine_id4:cuisineArray2[3],cuisine_id5:cuisineArray2[4],cuisine_id6:cuisineArray2[5],cuisine_id7:cuisineArray2[6],cuisine_id8:cuisineArray2[7]};
        axios(
            {
                method:'POST',
                url:`http://localhost:7000/getCuisine`,
                headers:{'Content-Type':'application/json'},
                data:filterObj
            }
        )
        .then(res=>
            {
                this.setState({restaurants:res.data.restaurants});
            })
        .catch(err=>console.log(err))
    }

render()
    {
        const {restaurants}=this.state;
        return(
            
                <div>
                   
                            <input type="checkbox" name="cuisines" id={"1"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > North Indian </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines"  id={"2"} onChange={(event) => this.handleCuisineChange("2")}  />
                            <span className="checkbox-items" > south indian </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"3"} onChange={(event) => this.handleCuisineChange("3")}  />
                            <span className="checkbox-items" > chinese </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"4"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > fast food </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"5"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > Street food </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"6"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > American </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"7"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > Italian </span> <div style={{display: "block"}}> </div>
                            <input type="checkbox" name="cuisines" id={"8"} onChange={(event) => this.handleCuisineChange("1")}  />
                            <span className="checkbox-items" > Mexican </span> <div style={{display: "block"}}> </div>
                </div>
       )
  } //render end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.