Search code examples
javascriptjqueryhtml

Capture selected option returns not defined instead


I need to capture the selected user option and send that value in a post request.

Let's ignore the post part as it is not directly related to the question.

But right now the value appears as undefined.

CodePen: https://codepen.io/ogonzales/pen/yLyQQaP

I have this JS, but lista_id, the value I need to capture, appears as undefined. Why?

I've tried to set this as a global variable. In the JS, you'll see an alert, this alerts undefined for lista_id

JS:

<script>
    $("#agregarProducto1").click(function () {
    var lista_id;
    $('#listas-de-usuario').change(function() {
       var lista_id = $(this).find('option:selected').val();
    });
    alert(lista_id);
    // $.post("{% url 'listas/agregar-producto/", {
    //     c_slug: "cuadernos",
    //     s_slug: "Cuadernos",
    //     product_slug: "cuadernos-rojos",
    //     lista_id: lista_id,
    //    });
   });
</script>

Solution

  • You could declare the variable only once either globally or in the surrounding function and then not declare them inside the click or change handlers. This way, it is the same variable you are referring to.

    Also, the code to bind change handler could be outside the click handler, otherwise it would be bound every time the button is clicked.

    Example of global variable declaration:

    CodePen

    Example of variable declared inside document ready function of jQuery:

    CodePen