allogos
allogos

Reputation: 47

Ajax Dropdown loading by preselected dropdown

I have two page and each page have one form

Page 1-Form A)

One dropdown (Value populating from database) and button to continue

<select name="form[formA][]" id="dropdown1">
        <option value="1">Option 01</option>
        <option value="1">Option 02</option>
</select>
<button>CONTINUE</button>

Page 2-Form B)

Same dropdown in form a + second dropdown (values loading by Ajax based on dropdown A selection)

 <select name="form[formA][]" id="dropdown1">
        <option value="1">Option 01</option>
        <option value="1">Option 02</option>
</select>
 <select name="form[formB][]" id="dropdown2">
        <option value="1">Option 01</option>
        <option value="">Please select from dropdown1</option>
</select>

Now the problem!, From Page1 by pressing continue, I’ll pass dropdown value to page 2 with below code

url/page2?form[formA][]={dropdown1:value}

Then on page 2 my first dropdown is auto selected, but second dropdown (ajax) is not loading.

dropdown1_id.on('change',  function(e) {
    var selectvalue = $(this).val();
    //Display 'loading' status in the target select list
    dropdown2_id.html('<option value="">Loading...</option>');
    if (selectvalue == '') 
    {
        dropdown2_id.html(initial_dropdown2_html);
    } 
    else 
    {
        //Make AJAX request, using the selected value as the GET
        $.ajax({
            url: 'index.php',
            data:'option=com_mycomponent&task=getdropdown2sHTML&fvalue='+selectvalue,
            success: function(output) {
                dropdown2_id.html(output);
                updateSelect(dropdown2_id.val());
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status +  ' ' + thrownError);
            }
        });
    }
});

On Form B - page 2 Dropdowns without direction form page1 and by itself are working fine.

Upvotes: 0

Views: 556

Answers (1)

Thernys
Thernys

Reputation: 723

I believe the change event is not fired for programmatic changes of a select's value.

The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user. (Change event on MDN)

Assuming dropdown1_id is a valid jQuery collection, you should then place the following somewhere after you have attached the change listener. Mind your placement, so the change listener will only be forced to run once, on page load.

dropdown1_id.trigger('change');

Here is a simple fiddle to demonstrate.

Upvotes: 1

Related Questions