开发者

Problem with HTML entities inserted with JavaScript

开发者 https://www.devze.com 2023-02-01 00:12 出处:网络
I have the following JS to dynamically change the content of an HTML select list inside a form: <script type=\"text/javascript\">

I have the following JS to dynamically change the content of an HTML select list inside a form:

<script type="text/javascript">

var provincias = [];

provincias['bsas'] = new Array('Capital Federal','San Martin','Quilmes');
provincias['cba'] = new Array('C&acute;rdoba','La Carlota','Rio Cuarto');
provincias['nqn'] = new Array('Neuqu&eacute;n','Cipolletti','Plottier');

function setLoc() {
    provSel开发者_开发问答 = document.getElementById('provincia');
    locList = provincias[provSel.value];
    updateLista('localidad', locList, locList);
}

function updateLista(fieldID, newOptions, newValues) {
    selectField = document.getElementById(fieldID);
    selectField.options.length = 0;
    for (i=0; i<newOptions.length; i++) {
    selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
    }
}

</script>

And the list is:

<select name="provincia" id="provincia" onchange="setLoc();">
    <option value="bsas">Buenos Aires</option>
    <option value="cba">C&oacute;rdoba</option>
    <option value="nqn">Neuqu&eacute;n</option>
</select>

<select name="localidad" id="localidad">
    <option value="">Seleccione una localidad</option>
</select>

It works Ok, but I don't understand for what reason the output of the entities inserted by JavaScript is literal: in the borwser you see &aacute; instead of á. Worse yet, if I change the entities by the special characters, the browser displays a weird question mark (?) symbol, the reason for which I started to use entities in the first place.

Does anyone know if there's a shortcut to solve this (like a special JS character scape)? or should I reformulate my script using innerHTML to display the outputs?

One more thing: keep in mind that this is a small list, but this script will be adapted to load the form data from an XML document with around 4000 entries (the complete list of states and cities of my country). And I will be using MySQL databases to store the form data as well). This is like a charset nightmare for me...

BTW: I'm coding in utf8 without BOM (now I write this I thik this is the problem...).

Cheers, and thank you all in advance for the good thinking.


it seems that javascript treated option text as plaintext, so you indeed have to use innerHTML, like so:

function updateLista(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
for(i=0; i<newOptions.length; i++) {
    selectField.options[i] = new Option();
    selectField.options[i].innerHTML = newOptions[i];
    selectField.options[i].value = newValues[i];
    }
}

PS. your first value of 'cba' array should be 'C&oacute;rdoba' instead of 'C&acute;rdoba'

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号