bootstrap js dynamically adds option element to select without display

Keywords: Javascript JSON Programming

In the afternoon, when using bootstrap to add option elements to select, js is used to generate them dynamically, and it is found that they can't be generated. So F12 checks that select has been added. The actual display is not the select but the contents of the div below. At this time, you need to force the refresh of the element rendering page

Code example:

function edit(ele){
        	$("#parent").append("<option value=''></option>");
        	var id=$(ele).attr("data-id");
            $.ajax({ 
                type: 'POST', 
                dataType : "json",
                contentType:"application/json",
                async:false,
                url: "/pinyu/menu/list/",
                data: {},
                error: function () {
                	layMsg("Data acquisition exception,Please contact the administrator!");
                },
                success:function(data){
                	var options=""; 
                	for(var i=0;i<data.length;i++){
                		var d=data[i];
	                	if(d.id!=id){
		                	options+="<option value='"+d.id+"'>"+d.name+"</option>";
	                	}else{
	                		$("#level").val(d.level);
				        	$("#name").val(d.name);
				        	$("#sort").val(d.sort);
				        	$("#url").val(d.url);
				        	$("#parent").val(d.parentId);
				        	$("#id").val(d.id);
	                	}
                	}
                	$("#parent").append(options);
                	//To programmatically update the JavaScript selection, first manipulate the selection, then update the UI with the refresh method to match the new state. This is required when removing or adding options, or when disabling / enabling selection through JavaScript.
                	$('#parent').selectpicker('refresh');
				    //The render method forces the bootstrapper to be re rendered - select the ui, which is useful if you change any related values while you are programming to affect the element layout.
				    $('#parent').selectpicker('render');
                }
            })
        }

The first two lines are indispensable:

//To programmatically update the JavaScript selection, first manipulate the selection, then update the UI with the refresh method to match the new state. This is required when removing or adding options, or when disabling / enabling selection through JavaScript.
$('#parent').selectpicker('refresh');
//The render method forces the bootstrapper to be re rendered - select the ui, which is useful if you change any related values while you are programming to affect the element layout.
$('#parent').selectpicker('render');

Posted by EagerWolf on Sat, 28 Dec 2019 08:27:23 -0800