Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
Why is it corrupted? Isn't the value Bermuda? – neo 20 hours ago
@neo: The line is broken (\n) – MMM 20 hours ago

1 Answer

up vote 0 down vote accepted

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, '');
share|improve this answer
thanks, that solves my problem :-) – user2192677 19 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.