0

I am dynamically grabbing data from my DB by using the jQuery .getJSON function and append the data to an html select drop-down list. My JS code is as follows:

$.getJSON('url',
  function(data) {
    var html = '<option value="">--Please select one--</option>';
    var len = data.length;
    for (var i = 0; i < len; i++) {
      html += '<option value="' + data[i].name + '">' + '</option>';
    }
    html += '</option>';
    $('#names').html(html);
  });

My html:

<select id="names"></select>

This works fine it starts look like this after the page loads: enter image description here

What I want to do is after the user click the select option and choose one of the available options from the list, I want to disable the --Please select one-- option so that the user will be forced to choose a meaningful name not go back to --Please select one--

I checked online and all I found was solutions for hard-coded drop-down select. Can you please give some advise?

2 Answers 2

2

Have it disabled and selected by default - so once the user clicks the dropdown, they must pick an option:

var html = '<option value="" selected disabled>--Please select one--</option>';
Sign up to request clarification or add additional context in comments.

Comments

1

tymeJV's answer is good if you want the "please select one" option to visibly remain, but to not be selectable. If you want to remove the option completely, see my answer.

All you have to do is remove the first option node from your select node when the value of the select is first changed. Since you're using jQuery, there is a really effective way to go about doing this.

What you can do is add an on change handler that will be called on the first change of the select value, which will serve to remove the first option:

$('#names').one('change', function(){
    $(this).find('option:first').remove();
});

The jQuery one() function is a handler that is "unbound after its first invocation," meaning that the handler will no longer exist after the first time the change action occurs on the select element.

More info on one(): http://api.jquery.com/one/

1 Comment

Definitely another good way of doing and nice explanation. Thumps up. I accepted his answer because less code and suits my needs for now.

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.