how can I pass a function to multiple selected in an HTML file?

0

I'm doing a course in JavaScript and I have the following problem:

In the same html file I have a function and in turn the html code that consists of a series of options which allows me to select day, month and year, it runs well without any problem in the browser.

My problem lies in separating the codes, and when wanting to execute the JavaScript code from an external file, I do not know how to invoke the function within the selected , as it is done correctly when everything is inside from the same file.

I have tried to create a file with createElement , but it does not work the same to me and I am wrong so I come to you to help me please.

I leave a file codepen for a better compression of the file.

link

Greetings and thanks for your help.

    
asked by Tony_85 10.09.2018 в 20:03
source

1 answer

0

To solve this you could for example include in the function a variable that passes the element of DOM to be updated. Once this is done, inside the function you save in a variable that element, and in the part where you write in the document, you replace it with this element.

I'll leave it as I would solve it (I've changed the method write() by innerHTML since you enter HTML code). I add to the variables that you pass to the function a select call that contains a string with the id of the element where to enter the information. Inside the function I keep the element of the id in a variable with document.getElementById(idelemento) and at the time of writing I execute the innerHTML function on that element so that it inserts HTML inside the nodes of that element.

var dia = document.getElementById("dia");

misOpciones(1,31,"dia");
misOpciones(1,12,"mes");
misOpciones(1900, 2050, "anio", 1980);

function misOpciones (desde,hasta,select,selected){
  var select = document.getElementById(select);
  for (let i = 0; i < (hasta - desde+1); i++){
  if (selected != undefined) {
    if (selected === (i + desde)) {
      select.innerHTML += "<option selected='selected'>"+ (i + desde) +"</option>";
    }else{
      select.innerHTML += "<option>"+ (i + desde) +" </option>";
    }
  } else{
    select.innerHTML += "<option>"+ (i + desde) +" </option>";
    }
  }
}
<p>Fecha de nacimiento</p>
<form action="">
  <select name="dia" id="dia" ></select>
  <select name="mes" id="mes"></select>
  <select name="anio" id="anio"></select>    
</form>

I have also changed the way you presented the numbers simply by adding the i of the for and the variable desde .

    
answered by 10.09.2018 в 22:26