Dynamically load content using the select tag

0

I have a question and I wish you could help me. My case is the following I have a dynamic where according to the selected option it returns a JSON with the information of the Hotels Units.

What I need is to populate the JSON content in HTML according to the selected select option.

Follow the codeshare link for a better explanation of the code. link

    
asked by anonymous 11.05.2016 / 20:56

1 answer

0

I could not understand your question right, however based on my experience what I normally do when I need to load dynamic content according to a select input is as follows:

I create a text / template tag script

<script type="text/template" id="templateDoConteudo">
    <div>
        <h1>{{titulo}}</h1>
        <span>{{texto}}</span>
    </div>    
</script>

I create an event that will observe my input from select

$('select#idDoCampo').on('change', function (){
    // Esse código garante que o template só será preenchido após o
    // json ser recuperado.
    $.when(buscarJSON($(this).val()))
    .then(preencheTemplate);
});

I create the function that will get the json according to what was selected

function buscarJSON(id) {
    // retorna a promisse do jquery para a função then();
    // esse ajax pode ser facilmente substituido por outras promisses
    // do jquery ($.Deferred(), $.getJson, etc...).
    return $.ajax({
         type: 'GET',
         url: 'pesquisa.php'
         dataType: 'json'
    });
}

And I create a function that will fill and append the template on the page

    function preencheTemplate(valor) {
        // recupero o conteúdo do template
        var template = $('script[type="text/template"]#templateDoConteudo').html();
        // substituo os marcadores utilizando expressões regulares
        template = template.replace(/{{titulo}}/g, valor.titulo)
                           .replace(/{{texto}}/g, valor.texto);
        // insiro o conteúdo novo no container
        $('div#container').append(template);
    }

If your JSON has an Array, just put a foreach (or $ .each ()) in the fillTemplate () function and treat the result accordingly.

    
19.05.2016 / 21:51