Dynamically load contents via <select> tag

Asked

Viewed 583 times

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 information from Hotel Units.

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

Follow the codeshare link for better explanation of the code. https://codeshare.io/pulisnoob

  • managed to solve the problem?

1 answer

0


I couldn’t quite understand your question, but based on my experience what I normally do when I need to load dynamic content according to a select type input is as follows:

I create a script tag like text/template

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

I create an event that will observe my select input

$('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 fetch 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 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 place a foreach (or $.each()) in the fillTemplate() function and treat the result appropriately.

  • Thank you very much Raphael I managed to solve.

  • If you used my answer would you mark it as a sure thing please? If you have solved it yourself in some other way it would be interesting for you to write an answer and accept it so that people with similar problems can consult as well. =)

Browser other questions tagged

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