简体   繁体   English

禁用动态创建的下拉选择列表选项

[英]disable dynamically created drop-down select list options

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. 我正在使用jQuery .getJSON函数从数据库中动态获取数据,并将数据附加到html select下拉列表中。 My JS code is as follows: 我的JS代码如下:

$.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: 我的html:

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

This works fine it starts look like this after the page loads: 在页面加载后,它看起来像这样,效果很好: 在此处输入图片说明

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-- 我要做的是在用户单击选择选项并从列表中选择一个可用选项之后,我要禁用-请--Please select one--选项,以便用户将被迫选择一个有意义的名称,而不是返回-请--Please select one--

I checked online and all I found was solutions for hard-coded drop-down select. 我在网上检查了一下,发现所有内容都是硬编码下拉选择的解决方案。 Can you please give some advise? 你能给点建议吗?

默认情况下disabled它并selected它-因此,一旦用户单击下拉列表,他们必须选择一个选项:

var html = '<option value="" selected disabled>--Please select one--</option>';

tymeJV's answer is good if you want the "please select one" option to visibly remain, but to not be selectable. 如果您希望“请选择一个”选项明显保留但不能选择,则tymeJV的答案很好。 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. 您要做的就是在第一次更改select的值时从选择节点中删除第一个选项节点。 Since you're using jQuery, there is a really effective way to go about doing this. 由于您使用的是jQuery,因此有一种非常有效的方法来执行此操作。

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: 您可以做的是添加一个on更改处理程序,该更改处理程序将在select值的第一次更改时被调用,这将用于删除第一个选项:

$('#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. jQuery one()函数是一个处理程序,该处理程序“在第一次调用后便未绑定”,这意味着该处理程序在select元素上第一次执行更改操作后将不再存在。

More info on one(): http://api.jquery.com/one/ 有关one()的更多信息: http : //api.jquery.com/one/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM