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

Pobieranie danych z checkboxa

42 Warsaw Coding Academy
+1 głos
199 wizyt
pytanie zadane 30 maja 2024 w JavaScript przez El Lirón Obywatel (1,350 p.)

Dzień dobry!

Chciałbym, aby użytkownik wybrał jedną lub więcej rybek, a jego wybór się zapisał. Zrobiłem to:
 

// elementy sekcji fish
const fish__type_1 = document.querySelector("#daniomargaritatus");
const fish__type_2 = document.querySelector("#aphyosemionaustrale");
const fish__type_3 = document.querySelector("#corydorashabrosus");
const fish__type_4 = document.querySelector("#corydorasaeneus");
const fish__type_5 = document.querySelector("#pseudomugilgertrudy");
const fish__type_6 = document.querySelector("#poeciliasphenops");
const fish__type_7 = document.querySelector("#bettasplendens");
const fish__type_8 = document.querySelector("#trichopodusleerii");
const fish_list = [fish__type_1, fish__type_2, fish__type_3, fish__type_4, fish__type_5, fish__type_6, fish__type_7, fish__type_8];

Elementy HTML pobrane, lista zrobiona. (linie 19-28)

 

let selected_fish_type;
let selected_fish_type_list = [];

Zmienne przygotowane. (linie 55-56)
 

const get_fish_type = () => {
    for (let element of fish_list) {
        if (element.checked) {
            selected_fish_type = element.value;
            selected_fish_type_list.push(selected_fish_type);
        }
    };
};

Funkcja zrobiona. (linie 162-169)
 

    get_fish_type();   

... i wywołana. (linia 231)

I nie wyświetla listy rybek. Gdzie jest błąd? Proszę o pomoc.

Jakby co, to załączam całość JS:

const start = document.querySelector(".start");
const dimensions = document.querySelector(".dimensions");
const subsoil = document.querySelector(".subsoil");
const fish = document.querySelector(".fish");
const summary = document.querySelector(".summary");

// elementy sekcji dimensions
const dimensions__lenght = document.querySelector(".dimensions__lenght__input");
const dimensions__width = document.querySelector(".dimensions__width__input");
const dimensions__height = document.querySelector(".dimensions__height__input");

// elementy sekcji subsoil
const subsoil__height = document.querySelector(".subsoil__height__input");
const subsoil__type_1 = document.querySelector("#sand");
const subsoil__type_2 = document.querySelector("#finegravel");
const subsoil__type_3 = document.querySelector("#coarsegravel");
const subsoil_list = [subsoil__type_1, subsoil__type_2, subsoil__type_3];

// elementy sekcji fish
const fish__type_1 = document.querySelector("#daniomargaritatus");
const fish__type_2 = document.querySelector("#aphyosemionaustrale");
const fish__type_3 = document.querySelector("#corydorashabrosus");
const fish__type_4 = document.querySelector("#corydorasaeneus");
const fish__type_5 = document.querySelector("#pseudomugilgertrudy");
const fish__type_6 = document.querySelector("#poeciliasphenops");
const fish__type_7 = document.querySelector("#bettasplendens");
const fish__type_8 = document.querySelector("#trichopodusleerii");
const fish_list = [fish__type_1, fish__type_2, fish__type_3, fish__type_4, fish__type_5, fish__type_6, fish__type_7, fish__type_8];

// elementy sekcji summary
const p1 = document.querySelector(".p1");
const p2 = document.querySelector(".p2");
const p3 = document.querySelector(".p3");

const p4 = document.querySelector(".p4"); //tymczasowe
const p5 = document.querySelector(".p5"); //tymczasowe
const p6 = document.querySelector(".p6"); //tymczasowe
const p7 = document.querySelector(".p7"); //tymczasowe
const p8 = document.querySelector(".p8"); //tymczasowe
const p9 = document.querySelector(".p9"); //tymczasowe
const p10 = document.querySelector(".p10"); //tymczasowe

// przyciski
const btn1 = document.querySelector(".start__button");
const btn2 = document.querySelector(".dimensions__button");
const btn3 = document.querySelector(".subsoil__button");
const btn4 = document.querySelector(".fish__button");
const btn5 = document.querySelector(".summary__button");

let aqua_lenght;
let aqua_width;
let aqua_height;
let soil_height;
let selected_soil_type;
let selected_fish_type;
let selected_fish_type_list = [];


const get_dimensions_lenght = () => {
    aqua_lenght = dimensions__lenght.value;
};

const get_dimensions_width = () => {
    aqua_width = dimensions__width.value;
};

const get_dimensions_height = () => {
    aqua_height = dimensions__height.value;
};

const get_subsoil_height = () => {
    soil_height = subsoil__height.value;
};

//Obliczenia i ich wyniki (B-E) v v v

let glass_thickness_mm;
let glass_volume;
let glass_weight;
let aqua_netto_volume;
let subsoil_volume;
let subsoil_density;
let subsoil_weight_kg;
let total_weight_kg;

const get_subsoil_type = () => {
    for (let element of subsoil_list) {
        if (element.checked) {
            selected_soil_type = element.value;
            break;}
        else {
            selected_soil_type = "default";
        }
    };
};

const calculate_subsoil_density = () => {
    if (selected_soil_type == "sand") {
        subsoil_density = 2.6;
    }
    else if (selected_soil_type == "finegravel") {
        subsoil_density = 2.2;
    }
    else if (selected_soil_type == "coarsegravel") {
        subsoil_density = 1.8;
    }
    else {
        subsoil_density = 2;
    }
};

const calculate_glass_thickness = () => {
    let lh = (aqua_lenght * 1) + (aqua_height * 1);
    if (lh > 170) {
        glass_thickness_mm = 12;
    }
    else if (lh > 140) {
        glass_thickness_mm = 1;
    }
    else if (lh > 120) {
        glass_thickness_mm = 8;
    }
    else if (lh > 90) {
        glass_thickness_mm = 6;
    }
    else if (lh > 70) {
        glass_thickness_mm = 5;
    }
    else {
        glass_thickness_mm = 4;
    }
};

const calculate_glass_volume = () => {
    let glass_bottom = aqua_lenght * aqua_width * glass_thickness_mm / 10;
    let glass_front_back = aqua_lenght * aqua_height * glass_thickness_mm / 10 * 2;
    let glass_left_right = aqua_width * aqua_height * glass_thickness_mm / 10 * 2;
    glass_volume = glass_bottom + glass_front_back + glass_left_right;
};
 
const calculate_glass_weight = () => {
    glass_weight = glass_volume * 2.5;
};

const calculate_aqua_netto_volume = () => {
    let aqua_brutto_volume = aqua_lenght * aqua_width * aqua_height;
    aqua_netto_volume = aqua_brutto_volume - glass_volume;
};

const calculate_subsoil_volume = () => {
    subsoil_volume = (aqua_lenght - 2 * glass_thickness_mm / 10) * (aqua_width - 2 * glass_thickness_mm / 10) * soil_height;
};

const calculate_subsoil_weight_kg = () => {
    subsoil_weight_kg = subsoil_volume * subsoil_density / 1000;
};

const calculate_total_weight_kg = () => {
    total_weight_kg = ((glass_weight + aqua_netto_volume) / 1000) + subsoil_weight_kg;
};

const get_fish_type = () => {
    for (let element of fish_list) {
        if (element.checked) {
            selected_fish_type = element.value;
            selected_fish_type_list.push(selected_fish_type);
        }
    };
};

//Obliczenia i ich wyniki (B-E) ^ ^ ^

const refresh_data = () => {
    glass_thickness_mm = 0;
    glass_volume = 0;
    glass_weight = 0;
    aqua_netto_volume = 0;
    subsoil_density = "";
    subsoil_density = 0;
    subsoil_volume = 0;
    subsoil_weight_kg = 0;
    total_weight_kg = 0;
    selected_fish_type = "";
    selected_fish_type_list = [];
}

const display_summary = () => {
    calculate_glass_thickness();
    calculate_glass_volume();
    calculate_glass_weight();
    calculate_aqua_netto_volume();
    calculate_subsoil_density();
    calculate_subsoil_volume();
    calculate_subsoil_weight_kg();
    calculate_total_weight_kg();

    p1.textContent = glass_thickness_mm;
    p2.textContent = subsoil_weight_kg;
    p3.textContent = total_weight_kg;
    
    p4.textContent = glass_volume; //tymczasowe
    p5.textContent = glass_weight; //tymczasowe
    p6.textContent = aqua_lenght; //tymczasowe
    p7.textContent = aqua_width; //tymczasowe
    p8.textContent = aqua_height; //tymczasowe
    p9.textContent = subsoil_density //tymczasowe
    p10.textContent = selected_fish_type_list //tymczasowe
};

const go_to_dimensions = () => {
    dimensions.style.display = "flex";
    start.style.display = "none";
};

const go_to_subsoil = () => {
    get_dimensions_lenght();
    get_dimensions_width();
    get_dimensions_height();
    subsoil.style.display = "flex";
    dimensions.style.display = "none";
};

const go_to_fish = () => {
    get_subsoil_height();
    get_subsoil_type();
    fish.style.display = "flex";
    subsoil.style.display = "none";
};

const go_to_summary = () => {
    get_fish_type();   
    summary.style.display = "flex";
    fish.style.display = "none";  
    display_summary();              
};                                  

const go_to_start = () => {
    refresh_data();
    start.style.display = "flex";
    summary.style.display = "none";
};

btn1.addEventListener("click", go_to_dimensions);
btn2.addEventListener("click", go_to_subsoil);
btn3.addEventListener("click", go_to_fish);
btn4.addEventListener("click", go_to_summary);
btn5.addEventListener("click", go_to_start);

:)

2 odpowiedzi

+4 głosów
odpowiedź 30 maja 2024 przez adrian17 Mentor (353,220 p.)
Tak szybko na oko: bo dodajesz rzeczy do `selected_fish_type_list`, ale nigdzie nie widzę żebyś potem gdziekolwiek wypisywał jego zawartość.

BTW, poddaję w wątpliwość te funkcje edytujące zmienne globalne typu `get_dimensions_width` - albo niech normalnie zwracają wartości zamiast edytować zmienne globalne, albo w ogóle nie powinny istnieć.
0 głosów
odpowiedź 31 maja 2024 przez VBService Ekspert (256,600 p.)
edycja 31 maja 2024 przez VBService

Twój kod działa

[ wersja on-line ]

<form>
  <section id="fish--type">
    <h4>Wybierz typ rybki - rybek</h4>
    <label for="daniomargaritatus">
      <input type="checkbox" id="daniomargaritatus" name="fish" value="daniomargaritatus">
      Danio Margaritatus
    </label>
    <label for="aphyosemionaustrale">
      <input type="checkbox" id="aphyosemionaustrale" name="fish" value="aphyosemionaustrale">
      Aphyosemion Australe
    </label>
    <label for="corydorashabrosus">
      <input type="checkbox" id="corydorashabrosus" name="fish" value="corydorashabrosus">
      Corydoras Habrosus
    </label>
    <label for="corydorasaeneus">
      <input type="checkbox" id="corydorasaeneus" name="fish" value="corydorasaeneus">
      Corydoras Aeneus
    </label>
    <label for="pseudomugilgertrudy">
      <input type="checkbox" id="pseudomugilgertrudy" name="fish" value="pseudomugilgertrudy">
      Pseudomugil Gertrudy
    </label>
    <label for="poeciliasphenops">
      <input type="checkbox" id="poeciliasphenops" name="fish" value="poeciliasphenops">
      Poecilia Sphenops
    </label>
    <label for="bettasplendens">
      <input type="checkbox" id="bettasplendens" name="fish" value="bettasplendens">
      Betta Splendens
    </label>
    <label for="trichopodusleerii">
      <input type="checkbox" id="trichopodusleerii" name="fish" value="trichopodusleerii">
      Trichopodus Leerii
    </label>
  </section>

  <button type="button" id="save-form">Zapisz</button>
  <button type="reset">Wyczyść</button>

  <pre id="console"></pre>
</form>
<script>
  //let selected_fish_type;
  let selected_fish_type_list;

  const get_fish_type = (fish_list) => {
    for (const element of fish_list) {
      if (element.checked) {
        //selected_fish_type = element.value;
        selected_fish_type_list.push(element.value);
      }
    };
  };

  const save_button = document.querySelector('form #save-form');
  save_button.addEventListener('click', () => {
    const fish__type_1 = document.querySelector("#daniomargaritatus"),
          fish__type_2 = document.querySelector("#aphyosemionaustrale"),
          fish__type_3 = document.querySelector("#corydorashabrosus"),
          fish__type_4 = document.querySelector("#corydorasaeneus"),
          fish__type_5 = document.querySelector("#pseudomugilgertrudy"),
          fish__type_6 = document.querySelector("#poeciliasphenops"),
          fish__type_7 = document.querySelector("#bettasplendens"),
          fish__type_8 = document.querySelector("#trichopodusleerii");
    const fish_list = [
      fish__type_1, fish__type_2, fish__type_3, fish__type_4,
      fish__type_5, fish__type_6, fish__type_7, fish__type_8
    ];

    selected_fish_type_list = [];
    get_fish_type(fish_list);
    //console.log(selected_fish_type_list);
    document.querySelector("pre#console").textContent = selected_fish_type_list.join('\n');
  });
</script>

<style>
  body {
    margin: 2rem;
  }
  form h4 {
    margin: .5rem 0;
  }
  form label {
    display: block;
  }
  form button {
    margin: .5rem 0;
  }
  form pre:not(:empty) {
    background-color: black;
    color: limegreen;
    padding: .5rem;
    width: 50%;
  }
</style>

w zaprezentowanym przez Ciebie kodzie, jak to już zauważył @adrian17

... dodajesz rzeczy do `selected_fish_type_list`, ale nigdzie nie widzę żebyś potem gdziekolwiek wypisywał jego zawartość.

 

proponuje zamiast pętliif-a i listy const-ansów, użyć [...] (spread operator), metody map i skorzystania z możliwość jakie daje querySelector (w przykładzie bardziej querySelectorAll) i użycie :checked (pseudo class css-a [ 1 ] [ 2 ]).

'form input[name="fish"]:checked'
const get_fish_type = () => {
  return [...document.querySelectorAll('form input[name="fish"]:checked')]
         .map(checkbox => checkbox.value);
};

 

[ wersja on-line ]

<form>
  <section id="fish--type">
    <h4>Wybierz typ rybki - rybek</h4>
    <label for="daniomargaritatus">
      <input type="checkbox" id="daniomargaritatus" name="fish" value="daniomargaritatus">
      Danio Margaritatus
    </label>
    <label for="aphyosemionaustrale">
      <input type="checkbox" id="aphyosemionaustrale" name="fish" value="aphyosemionaustrale">
      Aphyosemion Australe
    </label>
    <label for="corydorashabrosus">
      <input type="checkbox" id="corydorashabrosus" name="fish" value="corydorashabrosus">
      Corydoras Habrosus
    </label>
    <label for="corydorasaeneus">
      <input type="checkbox" id="corydorasaeneus" name="fish" value="corydorasaeneus">
      Corydoras Aeneus
    </label>
    <label for="pseudomugilgertrudy">
      <input type="checkbox" id="pseudomugilgertrudy" name="fish" value="pseudomugilgertrudy">
      Pseudomugil Gertrudy
    </label>
    <label for="poeciliasphenops">
      <input type="checkbox" id="poeciliasphenops" name="fish" value="poeciliasphenops">
      Poecilia Sphenops
    </label>
    <label for="bettasplendens">
      <input type="checkbox" id="bettasplendens" name="fish" value="bettasplendens">
      Betta Splendens
    </label>
    <label for="trichopodusleerii">
      <input type="checkbox" id="trichopodusleerii" name="fish" value="trichopodusleerii">
      Trichopodus Leerii
    </label>
  </section>

  <button type="button" id="save-form">Zapisz</button>
  <button type="reset">Wyczyść</button>

  <pre id="console"></pre>
</form>
<script>
  let selected_fish_type_list = [];

  const get_fish_type = () => {
    return [...document.querySelectorAll('form input[name="fish"]:checked')]
           .map(checkbox => checkbox.value);
  };

  const save_button = document.querySelector('form #save-form');
  save_button.addEventListener('click', () => {
    selected_fish_type_list = get_fish_type();
    //console.log(selected_fish_type_list);
    document.querySelector("pre#console").textContent = selected_fish_type_list.join('\n');
  });
</script>

<style>
  body {
    margin: 2rem;
  }
  form h4 {
    margin: .5rem 0;
  }
  form label {
    display: block;
  }
  form button {
    margin: .5rem 0;
  }
  form pre:not(:empty) {
    background-color: black;
    color: limegreen;
    padding: .5rem;
    width: 50%;
  }
</style>

 

Podobne pytania

0 głosów
1 odpowiedź 3,004 wizyt
pytanie zadane 2 kwietnia 2019 w JavaScript przez zerakot Obywatel (1,870 p.)
0 głosów
1 odpowiedź 491 wizyt
pytanie zadane 1 października 2019 w PHP przez michal_php Stary wyjadacz (13,700 p.)
0 głosów
3 odpowiedzi 3,863 wizyt
pytanie zadane 11 października 2017 w HTML i CSS przez adrian588 Początkujący (470 p.)

93,382 zapytań

142,382 odpowiedzi

322,540 komentarzy

62,738 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
...