• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Javascript - dynamiczny formularz

42 Warsaw Coding Academy
0 głosów
774 wizyt
pytanie zadane 2 maja 2022 w JavaScript przez Czang Kai Shrek Obywatel (1,990 p.)

Witam, chcę uzyskać efekt, by po wybraniu opcji z listy pokazał się odpowiedni pakiet formularzy. Jednak w obecnej postaci jedynie dodają się kolejne i kolejne... 
lista select:

      <label>Wybierz z listy:</label>
<select type="text" id="select" onchange="formFunction()">
  <option value="laptopy">Laptopy</option>
  <option value="telefony">Telefony</option>
  <option value="monitory">Monitory</option>
  <option value="aparaty">Aparaty</option>
  <option value="modemy">Modemy</option>
  <option value="peryferia">Peryferia</option>
  <option value="licencje">Licencje</option>
  <option value="drukarki">Drukarki</option>
</select>

i kod JS:
 

<script>
function formFunction() {
const currentDiv = document.getElementById("div1");
const input1 = document.createElement("input");
const input2 = document.createElement("input");
const input3 = document.createElement("input");
const input4 = document.createElement("input");
const newlabel1 = document.createElement("Label");
const newlabel2 = document.createElement("Label");
const newlabel3 = document.createElement("Label");
const newlabel4 = document.createElement("Label");
if(document.getElementById('select').value == "laptopy") {
    //element.node.removeChild(node);
 
    document.body.insertBefore(newlabel1, currentDiv);
    newlabel1.innerHTML = "Firma:";
    document.body.insertBefore(input1, currentDiv);
    document.body.insertBefore(newlabel2, currentDiv);
    newlabel2.innerHTML = "Model:";
    document.body.insertBefore(input2, currentDiv);
    document.body.insertBefore(newlabel3, currentDiv);
    newlabel3.innerHTML = "Procesor:";
    document.body.insertBefore(input3, currentDiv);
    document.body.insertBefore(newlabel4, currentDiv);
    newlabel4.innerHTML = "RAM:";
    document.body.insertBefore(input4, currentDiv);
  }
 
  if(document.getElementById('select').value == "telefony") {
    document.body.insertBefore(newlabel1, currentDiv);
    newlabel1.innerHTML = "xx:";
    document.body.insertBefore(input1, currentDiv);
    document.body.insertBefore(newlabel2, currentDiv);
    newlabel2.innerHTML = "xx:";
    document.body.insertBefore(input2, currentDiv);
    document.body.insertBefore(newlabel3, currentDiv);
    newlabel3.innerHTML = "x:";
    document.body.insertBefore(input3, currentDiv);
    document.body.insertBefore(newlabel4, currentDiv);
    newlabel4.innerHTML = "x:";
    document.body.insertBefore(input4, currentDiv);
     
  }
 
 
  if(document.getElementById('select').value == "monitory") {
    alert("zmienna: monitory");
     
   
  }
   
  }
 
   
 
</script>

Próbowałem przed stworzeniem nowych formularzy usuwać te poprzednie (w każdym ifie) - removeChild(), ale nie potrafię uzyskać zamierzonego efektu.
Ew. możnaby użyć replaceChild(), ale trzeba wpierw stworzyć wszystko raz (u mnie dalej tworzyły sie w nieskończoność)

Ma ktoś pomysł jak to rozwiązać? Czy może jest zupełnie lepszy sposób od child i elemenrs?
Pozdrawiam.

2 odpowiedzi

+2 głosów
odpowiedź 2 maja 2022 przez VBService Ekspert (256,600 p.)
wybrane 3 maja 2022 przez Czang Kai Shrek
 
Najlepsza

Też bym Tobie doradzał rozwiązanie podane przez @Comandeer-a

nie bawiłbym się w usuwanie i dodawanie na nowo, a pokazywanie i ukrywanie divów z poszczególnymi polami formularzy

 

ale jeśli chcesz pozostać przy Twoim kodzie, to np.

skoro masz

const currentDiv = document.getElementById("div1");

to możesz go użyć do "czyszczenia" za pomocą

currentDiv.innerHTML = "";

 

i zamiast

document.body.insertBefore(newlabel1, currentDiv);

użyć po porostu

currentDiv.appendChild(newlabel1); // itd.

 

jeżeli nie "dodajesz" do elementu kodu html, lepiej IMHO jest użyć np.

newlabel1.innerHTML = "Firma:";

na

newlabel1.textContent = "Firma:";

 

przykład  [ on-line ]

<label for="select">Wybierz z listy:</label>
<select id="select" onchange="formFunction()">
  <option value=""></option>
  <option value="laptopy">Laptopy</option>
  <option value="telefony">Telefony</option>
  <option value="monitory">Monitory</option>
  <option value="aparaty">Aparaty</option>
  <option value="modemy">Modemy</option>
  <option value="peryferia">Peryferia</option>
  <option value="licencje">Licencje</option>
  <option value="drukarki">Drukarki</option>
</select>
<div id="div1"></div>
function formFunction() {
  const currentDiv = document.getElementById("div1");
  currentDiv.innerHTML = "";

  const input1 = document.createElement("input"),
        input2 = document.createElement("input"),
        input3 = document.createElement("input"),
        input4 = document.createElement("input");
  const newlabel1 = document.createElement("Label"),
        newlabel2 = document.createElement("Label"),
        newlabel3 = document.createElement("Label"),
        newlabel4 = document.createElement("Label");

  if (document.getElementById('select').value == "laptopy") {
    currentDiv.appendChild(newlabel1);
    newlabel1.textContent = "Firma:";
    currentDiv.appendChild(input1);
    currentDiv.appendChild(newlabel2);
    newlabel2.textContent = "Model:";
    currentDiv.appendChild(input2);
    currentDiv.appendChild(newlabel3);
    newlabel3.textContent = "Procesor:";
    currentDiv.appendChild(input3);
  }

  if (document.getElementById('select').value == "telefony") {
    currentDiv.appendChild(newlabel1);
    newlabel1.textContent = "xx:";
    currentDiv.appendChild(input1);
    currentDiv.appendChild(newlabel2);
    newlabel2.textContent = "xx:";
    currentDiv.appendChild(input2);
    currentDiv.appendChild(newlabel3);
    newlabel3.textContent = "x:";
    currentDiv.appendChild(input3);
  }

  if (document.getElementById('select').value == "monitory") {
    currentDiv.textContent = "zmienna: monitory";
  }

}

 

przykład  [ on-line ]

function formFunction() {
  const currentDiv = document.getElementById('div1');
  const selectValue = document.getElementById('select').value;
  currentDiv.innerHTML = '';
  
  if (! selectValue) return;

  let elements = [];

  switch (selectValue) {
    case 'laptopy':
      elements = [ 'firma', 'model', 'procesor' ];
      break;
    case 'telefony':
      elements = [ 'xx', 'xxx', 'xxxx' ];
      break;
  }

  if (elements.length) {
    for (const element of elements) {
      const div = document.createElement('DIV');
      div.setAttribute('class', 'field');
      const label = document.createElement('LABEL');
      label.setAttribute('for', element);
      // label.textContent = element + ': '; // w css label { text-transform: capitalize; }
      label.textContent = element.charAt(0).toUpperCase() + element.slice(1) + ': ';
      div.appendChild(label);
      const input = document.createElement('INPUT');
      input.setAttribute('id', element);
      input.setAttribute('name', element);
      div.appendChild(input);
      currentDiv.appendChild(div); 
    }
  } else {
    currentDiv.textContent = 'zmienna: ' + selectValue;
  }

}

 

przykład  [ on-line ]

function formFunction() {
  const currentDiv = document.getElementById('div1');
  const selectValue = document.getElementById('select').value;
  currentDiv.innerHTML = '';

  if (! selectValue) return;

  let elements = [];

  switch (selectValue) {
    case 'laptopy':
      elements = [ 'firma', 'model', 'procesor' ];
      break;
    case 'telefony':
      elements = [ 'xx', 'xxx', 'xxxx' ];
      break;
  }

  if (elements.length) {
    let formHTML = '';
    for (const element of elements) {
      const field = `
        <div class="field">
          <label for="${element}">${element}: </label>
          <input id="${element}" name="${element}" />
        </div>
      `;
      formHTML += field; 
    }
    currentDiv.innerHTML = formHTML;
  } else {
    currentDiv.textContent = 'zmienna: ' + selectValue;
  }

}

 

+1 głos
odpowiedź 2 maja 2022 przez Comandeer Guru (607,060 p.)
Tak szczerze, to nie bawiłbym się w usuwanie i dodawanie na nowo, a pokazywanie i ukrywanie divów z poszczególnymi polami formularzy. Byłoby to IMO zdecydowanie łatwiejsze do ogarnięcia.

Podobne pytania

0 głosów
1 odpowiedź 897 wizyt
pytanie zadane 1 września 2015 w JavaScript przez marika Nowicjusz (190 p.)
0 głosów
1 odpowiedź 241 wizyt
pytanie zadane 2 listopada 2020 w PHP przez wius2012 Początkujący (330 p.)
+1 głos
2 odpowiedzi 565 wizyt
pytanie zadane 19 stycznia 2022 w JavaScript przez ferdynand Obywatel (1,250 p.)

93,394 zapytań

142,387 odpowiedzi

322,550 komentarzy

62,752 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

VMware Cloud PRO - przenieś swoją infrastrukturę IT do chmury
...