简体   繁体   中英

wrong html output from the javascript

I wrote a script for populating a selectbox with a bunch of options.

Initially the data is in the form of string of a format "key=value;key2=value2;etc...":

//split the string to distinguish between different options to populate a selectbox with
var values = data.split(';');
//reset the length of the selectbox to be populated
document.getElementById(child).options.length = 0;
//create first default option
document.getElementById(child).options[0] = new Option('all', '0');
for(var i = 0; i < values.length; i++){
    //check for and remove unnecessary characters
    values[i].replace(/\s+/g, '');
    //split the option to get the key and value separately
    var options = values[i].split('=');
    if(!isEmpty(options[0]) && !isEmpty(options[1])){
        //insert a new element to the selectbox
        document.getElementById(child).options[i+1] = new Option(options[1], options[0]);
    }
}

The example above populates a selectbox with the given html output:

<option value="0">all</option>
<option value=" 
7">Bermuda</option>
<option value="10">British Virgin Islands</option>
<option value="15">Cayman Islands</option>
<option value="42">Jamaica</option>
<option value="74">St. Lucia</option>
<option value="79">Trinidad Tobago</option>

As you can notice above the second option in the selectbox has a corrupted string value. I need to fix that value because because of that cake cannot save this value properly.

If you have any other questions please ask.

You should try to trim values:

document.getElementById(child).options[i+1] = new Option(
   options[1].replace(/^\s+|\s+$/g, ''), 
   options[0].replace(/^\s+|\s+$/g, '')
);

or if you are using jquery:

document.getElementById(child).options[i+1] = new Option(
   $.trim(options[1]), 
   $.trim(options[0])
);

also you should look close on this fragment:

values[i].replace(/\s+/g, '');

because probably it doesn't do what you want. First, it removes all whitespaces from string so "New York City" will become "NewYorkCity". Next thing is that replace method returns new string so your code will take no effect. It should be:

values[i] = values[i].replace(/\s+/g, '');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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