jQuery val() not working properly on dynamic <select> with Aloha Editor

5.5k views Asked by At

I am creating a dynamic <select> element through jQuery append() function, but I cant seem to get the correct selected value. I always get the first option, which is 1. I am trying to configure the Aloha Editor, which probably has something to do with the issue.

This is the select element, appended in a sidebar.

$('.aloha-sidebar-inner').append('<select id="columns"><option value="1">1 Column</option><option value="2">2 Columns</option><option value="3">3 Columns</option><option value="4">4 Columns</option></select>').trigger('create');

As mentioned I use Aloha Editor, so the jquery looks like this:

    Aloha.ready(function() {
          $('.aloha-sidebar-inner').append('<button id="add-section" class="btn aloha-sidebar-btn sidebar-item" type="button" onclick="addSection(document.getElementById(\'articles\').value);">Add Section</button>');
          $('.aloha-sidebar-inner').append('<p>Number of Columns:</p>');
          $('.aloha-sidebar-inner').append('<select id="articles" class="sidebar-item"><option>1</option><option>2</option><option>3</option><option>4</option></select>');
    });

        function addSection() {     
          var idCounter = 0;
          alert($('#articles').val());
};

The alert windows keeps returning the value 1. Maybe there is an issue because I create the select element dynamically?

I have tried using $( "#columns option:selected" ).val(); but still nothing. I even tried using text(), but still nothing; alert keeps returning the first option.

I also tried using $('#add-section').click or $('#articles').change listeners but they don't seem to respond.

2

There are 2 answers

0
Krish On

To get the selected columns use the below code

$('#columns').change(
    function()
    {
        alert($('#columns').val());
    });

fiddle : jsfiddle.net/EnJz5

1
Bellash On

I answered this question last:

    $('#columns').change(function () {
    var optionSelected = $(this).find("option:selected");
    var valueSelected  = optionSelected.val();
    var textSelected   = optionSelected.text();
  });