I have a form in a document HTML
with a field select
where I load several provinces. Is this way of loading the provinces in the Select correct? It gives me an error.
<select name="provincia" id="provincia">
<option value="cargar_provincias();">Seleccione una Provincia...
</select>
function cargar_provincias(){
var array = ["Cantabria", "Asturias", "Galicia", "Andalucia", "Extremadura"];
var provincia = document.getElementById("provincia");
for(var i=0;i<array.length;i++){
provincia.options[i] = new option(array[i]);
}
}
To call a function from an HTML tag you must do it inside an event ( , , etc.). If this function must be executed only once, I recommend placing it in the event of the tag .
onClick="..."
onFocus="..."
onLoad="..."
<body>
Example:
I hope this example is a good illustration of: how to do it , Greetings! ;))...
What I recommend is that you execute the function that will be in charge of creating your elements
{opciones}
once the document is ready , I give you the example based on your code and using a bit of jQuery :HTML :
JavaScript + jQuery :
I hope it helps :)
greetings and good luck.
I would start from the HTML base structure : the
select
empty or with the firstoption
, which does not usually have a "useful" content beyond indicating the action to be carried out. I've added alabel
so that the HTML structure is "correct".There is a first block
<script>
with helper functions, which can be reused for a certain purpose when needed. I have placed them separate from the main script although their position on the page doesn't matter too much.The main script does require a certain position, in this case it must always be placed below the
select
since otherwise the line:It would try to load a page element that is not yet in the document.
As for the code, when the window is loaded, the function that fills the selector with the array of strings that is passed to it in the order in which they are executed is executed:
what the helper function does indirectly
loadSelector(selectNode, arrData);
The answer helped me a lot to get an idea. Now I have a problem that I can only call that function once in a select. I have a form where you have to select which club is going to win, so I use select permanently, but it lets me use it only once.