Как получить значение input из label

Рейтинг: 1Ответов: 1Опубликовано: 10.02.2023

Есть вот такой примитивный код

window.onload = function () {

    const ph_block = document.querySelectorAll(".pt_item");

    if (ph_block.length !== 0) {
        chooseVariable();
    }

    function chooseVariable() {
        const items = document.querySelectorAll(".ph_label");
        for (let i = 0; i < items.length; i++){
            items[i].addEventListener("click", function (){
                let item = this.target;
                console.log("click" + item);


            })
        } 
    }


}
.ph_label{
    display: block;
    position: relative;
    padding: 10px;
    margin-bottom: 5px;
    border: 1px solid #333;
    border-radius: 10px;
    cursor: pointer;
}

.ph_radio{
    
    position: absolute;
    top: 10px;
    right: 10px;

}
<div class="pt_item">
    <div id="ph_block1" class="pt_block">
        <label class="ph_label">
            <span class="ph_name">It's first variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_1">
        </label>
        <label class="ph_label">
            <span class="ph_name">It's second variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_2">
        </label>
        <label class="ph_label">
            <span class="ph_name">It's third variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_3">
        </label>
        <label class="ph_label">
            <span class="ph_name">It's forth variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_4">
        </label>
    </div>
</div>

Задача - по нажатию на label получать значение value того input который его содержит.

У меня вопросЖ почему при текущем коде, мне в консоль дважды выводить значение, если итерируютсь по label элементам.

Ответы

▲ 2Принят

Для обращения к элементу, с которым связан label, необходимо обратиться к свойсву control. Оно содержит как раз ссылку на элемент.

window.onload = function () {

    const ph_block = document.querySelectorAll(".pt_item");

    if (ph_block.length !== 0) {
        chooseVariable();
    }

    function chooseVariable() {
        const items = document.querySelectorAll(".ph_label");
        for (let i = 0; i < items.length; i++){
            items[i].addEventListener("click", function (e){
                e.preventDefault()
                console.log('Связан инпут: ', this.control.value);
                console.log(e.target, this);
            })
        } 
    }

}
.ph_label{
    display: block;
    position: relative;
    padding: 10px;
    margin-bottom: 5px;
    border: 1px solid #333;
    border-radius: 10px;
    cursor: pointer;
}

.ph_radio{
    
    position: absolute;
    top: 10px;
    right: 10px;

}
<div class="pt_item">
    <div id="ph_block1" class="pt_block">
        <label class="ph_label">
            <span class="ph_name">It's first variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_1">
        </label>
        <label class="ph_label">
            <span class="ph_name">It's second variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_2">
        </label>
        <label class="ph_label">
            <span class="ph_name">It's third variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_3">
        </label>
        <label class="ph_label">
            <span class="ph_name">It's forth variant of answer</span>
            <input class="ph_radio" type="radio" name="ph_1" value="ph_1_4">
        </label>
    </div>
</div>

UPD: Из комментариев. Сокращаем код, убираем ненужное.

window.onload = function () {

  document.querySelectorAll('.ph_label').forEach(function (item) {
    item.addEventListener("click", function (e) {
      e.preventDefault();
      console.log('Связан инпут: ', this.control.value);
      console.log(e.target, this);
    })
  })

}