Filter with Jquery, Json and Input

Asked

Viewed 1,089 times

2

I have a list of inputs with type checkbox, with values that are loaded from a JSON file. I wanted to know how to make a filter, so that when clicking on a certain checkbox, the products (which are loaded from another JSON file) were filtered, leaving only the one with the size chosen in the checkbox.

Unico framework I’m using is Jquery

    "produto" : [
{
  "dados": {
    "nome": "Vestido Listrado",
    "imgNome": "vestido-listrado",
    "data": "Ter, 25 Abr 2017 05:00:00 GMT"
  },
  "caracteristicas":{
    "tamanho": [1,2,3],
    "tipo": 1,
    "cores": [1,2,3,4,5,6,7,8,9,10]
  },
  "pagamento":{
    "de": null,
    "por": 198,
    "qtdParcela": 2
  },
  "link": "img/produtos/vestido-listrado.jpg"
},
{
  "dados":{
    "nome": "Chapéu Florido",
    "imgNome": "chapéu-florido",
    "data": "Sun, 23 Oct 2016 12:00:00 GMT"
    },
  "caracteristicas":{
    "tamanho": [5],
    "tipo": 1,
    "cores": [6]
  },
  "pagamento":{
    "de": null,
    "por": 398,
    "qtdParcela": 3
    },
  "link": "img/produtos/chapeu-florido.jpg"
},

And the HTML of the product generated by JS

    <piicture class="produtos-organizados">
    <img src="img/produtos/vestido-florido.jpg" alt="vestido-florido">
    <figcaption>Vestido Florido</figcaption>
    <div>
    <p>R$ 198</p>
    <p>até 2x de 99.00</p>
    </div>
    <i class="large material-icons">shopping_cart</i>
    </piicture>

And the list HTML, only the form is filled by JS

    <div class="lista-cores">
            <div class="espacado">
                    <button id="btn-cor">Cores</button>
                    <span class="canto canto-cor">+</span>
                    <form class="lista-de-cores oculto fadeOut">
                            <input type="checkbox">Todos<br>
                            <input type="checkbox">Amarelo<br>
                            <input type="checkbox">Azul<br>
                            <input type="checkbox">Branco<br>
                            <input type="checkbox">Cinza<br>
                            <input type="checkbox">Laranja<br>
                            <input type="checkbox">Verde<br>
                            <input type="checkbox">Vermelho<br>
                            <input type="checkbox">Preto<br>
                            <input type="checkbox">Rosa<br>
                            <input type="checkbox">Vinho<br>
                    </form>
            </div>
    </div>

JS to generate inputs

    function listaDeCores(){
var response = JSON.parse(produto.responseText);
var cor = response.cores;

for (var i = 0; i < cor.length; i++) {
    var arrayDeCores = response.cores[i].label;

    var listaDeCores = $(".lista-de-cores");
    var inputText = arrayDeCores;
    var inputP = "<p>" + "</p>";
    var idP = response.cores[i].id;
    var inputDeCores = "<input type='checkbox'>" + inputText;
    var srcIdP = $(inputP).attr("class", idP);

    srcIdP.append(inputDeCores);
    listaDeCores.append(srcIdP);
}};
  • You can give an example of JSON and HTML?

  • What is the relation of colors to JSON? is in numerical order?

  • Yes, each color received an id within JSON.

  • And the inputs of the form are generated in a way that always respects that order? The Todos is what number?

  • Yes, they always respect this, order, "All" is 0, as well as the number of its position within the JSON generated array

  • Can you put the code that generates these inputs? I want to give an answer and so I have all the data :)

Show 1 more comment

2 answers

1

Well, I’ll give you a generic example here with a JSON more or less the way you want it.

In jQuery, there is a function called grep (same as linux) that serves to filter arrays, since a JSON is an object notation, you should have a structure more or less like this:

var produtos = [
  {nome:"produto", tamanho:34, preco:24.99},
  {nome:"produt2", tamanho:37, preco:25.99},
  {nome:"produto3", tamanho:38, preco:29.99},
  {nome:"produto4", tamanho:32, preco:21.99}
];

Which would translate to an array of objects.

So you could do something like this:

$(produtos).grep(function(i,produto) { return produto.tamanho == $(seuoption).val(); });

Or using filter as well at this link.

Take a look at the documentation of grep and of filter jQuery to get a better sense.

-1

Take a look at that lib

https://datatables.net/

With it you will be able to mount a responsive table and have options for sorting and searching for fields. You can make the necessary filters. I’ve used and recommend for simplicity.

You just need to create a table html. It is essential to have thead tags. It is not necessary to create the one that will be created when json is consumed.

<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>

    </table>

It is also important to add the css from the library

<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.min.css">

Then just start the library.

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": "file.json",
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    } );
} );

For example I used this json

{"data": [{
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
  },
  {
  "name": "Garrett Winters",
  "position": "Accountant",
  "salary": "$170,750",
  "start_date": "2011/07/25",
  "office": "Tokyo",
  "extn": "8422"
  },
  {
  "name": "Ashton Cox",
  "position": "Junior Technical Author",
  "salary": "$86,000",
  "start_date": "2009/01/12",
  "office": "San Francisco",
  "extn": "1562"
  },
  {
  "name": "Cedric Kelly",
  "position": "Senior Javascript Developer",
  "salary": "$433,060",
  "start_date": "2012/03/29",
  "office": "Edinburgh",
  "extn": "6224"
  },
  {
  "name": "Airi Satou",
  "position": "Accountant",
  "salary": "$162,700",
  "start_date": "2008/11/28",
  "office": "Tokyo",
  "extn": "5407"
  }]
}

See working in https://jsfiddle.net/oaqcybdg/1/

  • Mauricio, links break, if possible post the example here. The idea of the site is to have the content here.

  • I edited it with an example of using the library. When suggesting a lib what is the best way to do this ? I still have a hard time making answers like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.