简体   繁体   中英

Filtering JSON using jQuery

I am currently working on a web application and would like to incorporate a filter feature that uses multiple options for the user, this filter then displays data from a JSON array that matches the criteria. I have gotten a fair way but can't seem to get the filtering to work correctly, I think the problem may be with the jQuery .each() method.

I'd really appreciate some help! Here is what I currently have.

Thanks in advance.

HTML file

<html>
<head>
    <title>Test Filter</title>

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="filter.js"></script>

</head>

<body>

    <label for="weather">Gender</label>
    <select id="weather" name="weather">
        <option value="rain">Rain</option>
        <option value="sun">Sun</option>
        <option value="snow">Snow</option>
    </select>

    <label for="distance"></label>
    <select id="distance" name="distance">
        <option value="0-5 miles">0 - 5 miles</option>
        <option value="6-10 miles">6 - 10 miles</option>
        <option value="11-20 miles">11 - 20 miles</option>
        <option value="21-25 miles">21 - 25 miles</option>
    </select>

    <label for="eventtype">Type of event</label>
    <input id="eventtype" name="eventtype" type="text" />
    <a id="calc" href="#" >Submit</a>

    <div id="eventResult"></div>

</body>

JavaScript file

$(document).ready(function() {    

    var obj = {
        "events": [
            {
                "location": "Sheffield",
                "date": "May 13th, 2015",
                "map": "img/leeds_town_hall.jpg",
                "weather": "rain",
                "distance": "0-5 miles",
                "eventtype": "music"
            },
            {
                "location": "Leeds",
                "date": "May 13th, 2015",
                "map": "img/leeds_town_hall.jpg",
                "weather":"sun",
                "distance":"6-10 miles",
                "eventtype":"historical"
            },
            {
                "location": "York",
                "date": "May 13th, 2015",
                "map": "img/leeds_town_hall.jpg",
                "weather":"snow",
                "distance":"11-20 miles",
                "eventtype":"food"
            },
            {
                "location": "Leeds Town Hall",
                "date": "May 13th, 2015",
                "map": "img/leeds_town_hall.jpg",
                "weather":"rain",
                "distance":"21-25 miles",
                "eventtype":"arts"
            },
            {
                "location": "Leeds Town Hall",
                "date": "May 13th, 2015",
                "map": "img/leeds_town_hall.jpg",
                "weather":"sun",
                "distance":"0-5 miles",
                "eventtype":"music"
            },
            {
                "location": "Leeds Town Hall",
                "date": "May 13th, 2015",
                "map": "img/leeds_town_hall.jpg",
                "weather":"snow",
                "distance":"0-5 miles",
                "eventtype":"family"
            }
        ]};


    //Find the value when form is submitted
    $('#calc').click(function(e) {
        e.preventDefault();

        var events = jQuery.grep(obj.events, function(element, index){
            return element.weather && element.distance && element.eventtype; // retain appropriate elements

        });    

        var selectedWeather = $('#weather').val().toString().toLowerCase(); //gender
        var selectedDistance= $('#distance').val().toString().toLowerCase(); //amount
        var selectedEventType = $('#eventtype').val().toString().toLowerCase(); //age

        var distance = "";

        $.each(events,function(k, v){

            if( events[k].weather.toString().toLowerCase() == selectedWeather &&
                events[k].distance.toString().toLowerCase() == selectedDistance &&
                events[k].eventtype.toString().toLowerCase() == selectedEventType){

                distance = events[k][selectedDistance];
            }
        }); 

            //Empty the div
            $('#eventResult').empty();
            //Show the result in div
            var displayText = "Event Type: " + selectedEventType + ", Weather: " + selectedWeather + ", Distance: " + distance + ", Price: element.price-from-json";
            $("#eventResult").append(distance == "" ? "No Results" : displayText);
            return false; //Stop page from reloading
        });
    }); 

Fiddle here:

http://jsfiddle.net/brettwgreen/hfuukpzx/

Main problem is that your clear of the div was inside the loop as Karl-André Gagnon suggested.

    $(document).ready(function() {    

    var obj = {
        "events": [

        {
        "location": "Sheffield",
        "date": "May 13th, 2015",
        "map": "img/leeds_town_hall.jpg",
        "weather": "rain",
        "distance": "0-5 miles",
        "eventtype": "music"
        },

        {
        "location": "Leeds",
        "date": "May 13th, 2015",
        "map": "img/leeds_town_hall.jpg",
        "weather":"sun",
        "distance":"6-10 miles",
        "eventtype":"historical"
        },

        {
        "location": "York",
        "date": "May 13th, 2015",
        "map": "img/leeds_town_hall.jpg",
        "weather":"snow",
        "distance":"11-20 miles",
        "eventtype":"food"
        },

        {
        "location": "Leeds Town Hall",
        "date": "May 13th, 2015",
        "map": "img/leeds_town_hall.jpg",
        "weather":"rain",
        "distance":"21-25 miles",
        "eventtype":"arts"
        },

        {
        "location": "Leeds Town Hall",
        "date": "May 13th, 2015",
        "map": "img/leeds_town_hall.jpg",
        "weather":"sun",
        "distance":"0-5 miles",
        "eventtype":"music"
        },

        {
        "location": "Leeds Town Hall",
        "date": "May 13th, 2015",
        "map": "img/leeds_town_hall.jpg",
        "weather":"snow",
        "distance":"0-5 miles",
        "eventtype":"family"
        }

    ]};


    //Find the value when form is submitted
    $('#calc').click(function(e) {
        e.preventDefault();

        var events = jQuery.grep(obj.events, function(element, index){
        return element.weather && element.distance && element.eventtype; // retain appropriate elements

        });    
        console.log(events);
        var selectedWeather = $('#weather').val().toString().toLowerCase(); //gender
        var selectedDistance= $('#distance').val().toString().toLowerCase(); //amount
        var selectedEventType = $('#eventtype').val().toString().toLowerCase(); //age

        var distance = "";

        //Empty the div -- Moved this up
        $('#eventResult').empty();

        $.each(events,function(k, v){
            console.log(events[k].weather.toString().toLowerCase());
            console.log(events[k].distance.toString().toLowerCase());
            console.log(events[k].eventtype.toString().toLowerCase());
            if( events[k].weather.toString().toLowerCase() == selectedWeather &&
                events[k].distance.toString().toLowerCase() == selectedDistance &&
                events[k].eventtype.toString().toLowerCase() == selectedEventType){

                distance = events[k][selectedDistance];

            }



        //Show the result in div
        var displayText = "Event Type: " + selectedEventType + ", Weather: " + selectedWeather + ", Distance: " + selectedDistance + ", Price: element.price-from-json";

        $("#eventResult").append(distance == "" ? "No Results" : displayText);

        });
    });
return false; //Stop page from reloading
});

change

distance = events[k][selectedDistance];

to:

distance = "Event Type: " + selectedEventType + ", Weather: " + selectedWeather + ", Distance: " + distance + ", Price: element.price-from-json";

and then use:

$("#eventResult").append(distance == "" ? "No Results" : distance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM