How to save space in HTML selection list <option value = hi this> hi </option>

I have one control. I am trying to update this control using jquery, but the value after the space is a space.

 if (brandObj != "") { brandObj = eval("(" + brandObj + ")"); $.each(brandObj, function(i, item) { $("#<%=listBrand.ClientID%>").append( "<option value="+ item.Brand + ">" + item.Brand + "</option>"); }); } 

The data that I receive from the server

enter image description here

But after rendering it as an HTML selection, it omits the word after space.whole there is a value, but as soon as I get the value, it has only half (the value, which is in double quotes). I tried adding &nbsp; but it is shown as is. it is not rendering like space. please give your suggestion.

enter image description here

+5
source share
2 answers

You must transfer the value of the attribute value to a quote (Quote It). If you do not wrap them in a quote, then the value after the space will be considered an attribute:

 $("#<%=listBrand.ClientID%>").append("<option value='"+ item.Brand + "'>" + item.Brand + "</option>"); 
+8
source

As I mentioned in comment , the problem can be solved by wrapping the value of the value attribute in quotation marks.

 .append("<option value='" + item.Brand + "'>" ... ^ ^ 

However, I recommend using the Option constructor to dynamically create a new <option> element.

Demo:

 var arr = [{ text: 'Hello World!', value: 'hello World' }, { text: 'Bye World!', value: 'bye World' }]; var select = document.getElementById('mySelect'); // Iterate over array arr.forEach(function (obj, i) { // Create new <option> with dynamic value and text // Add the <option> to the <select> select.appendChild(new Option(obj.text, obj.value)); }); 
 <select id="mySelect"></select> 
+4
source

Source: https://habr.com/ru/post/1245475/


All Articles