0

For the question let me simplify my code:

I have two html forms with id's of 'header' and 'existing'

In the 'existing' form I have a select element where the options list is loaded dynamically using Ajax depending on the result of a search - this works fine with the following jQuery:

$(document).ready(function() {
    $('#article').keyup(function() {
        var getData = 'q=' + this.value + '&s=' + $('#supplierCode').val();
        $.getJSON('article.php', getData, function(j) {
            var options = '';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
            }
            $('select#articleList').html(options);
        });

        return false;
    });
});

The search works and the list appears to be loaded correctly as part of the form. I then want the input data of this form to be combined with the data of the 'header' form before submitting. I use this jQuery:

$(document).ready(function() {
    $('#articleList').change(function() {
        $('#existing :input').not(':submit').clone().hide().appendTo('#header');
        $('#header').submit();
    });
});

But whatever I select from the options list the $_REQUEST data always shows the first item on the list as chosen.

I can add more code if this is necessary - but hopefully the esence of the problem is clear!

3
  • I'll go ahead and suggest that you use a library for such an operation. github.com/ivaynberg/select2 will be perfect for your needs. Commented Sep 18, 2014 at 7:53
  • What exactly is $_REQUEST? Are you talking php by any chance? Commented Sep 18, 2014 at 7:55
  • Yes, this is all part of a 500 line php script... I will take a look at Select2 - thanks Commented Sep 18, 2014 at 7:59

1 Answer 1

1

If you are to study the way Select2 Jquery plugin works,

The plugin creates a list of items using <ul>s and stores the value of the chosen element in an <input>.

I believe this is done, so as to workaround the issue that you are having with dynamically populated <select> lists.

You can do the same as a solution to your issue.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes the whole restructuring of the input from <select> to normal <input> by using this plugin solved the problem. None of the other code had to be changed and I got much nicer dropdown menus. Two birds with one stone! Thanks ...
Glad to be of help. Tip: use plugins instead of self-built solutions, if possible. The plugins will be more robust and would have ironed, most, if not all the kinks of the daily programmer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.