Is there some way to locate in two different locations the same radio group inputs and if they change one of them, also the other changes automatically?
For two location, I mean two different places on a same submit form.
I edited the post to better show what I mean. There are two groups. If user click on 1 on first group, I'd like to have also 1 checked on second group.
My code:
<p>First group</p>
<label >1
<input type="radio" name="number_people" value="1">
<span ></span>
</label>
<label >2
<input type="radio" name="number_people" value="2">
<span ></span>
</label>
<label >3
<input type="radio" name="number_people" value="3">
<span ></span>
</label>
<label >4
<input type="radio" name="number_people" value="4" checked="checked">
<span ></span>
</label>
<br>
<p>Second group</p>
<label >1
<input type="radio" name="number_people_2" value="1">
<span ></span>
</label>
<label >2
<input type="radio" name="number_people_2" value="2">
<span ></span>
</label>
<label >3
<input type="radio" name="number_people_2" value="3">
<span ></span>
</label>
<label >4
<input type="radio" name="number_people_2" value="4" checked="checked">
<span ></span>
</label>
CodePudding user response:
You can divide the groups to two groups with wrapper div
, and with event delegate, you can capture change
event on each group, and change check the corresponding radio
in the other group.
const groupOne = document.getElementById('group-one')
const groupTwo = document.getElementById('group-two')
const changeGroup = (groupA, groupB) => {
groupA.addEventListener('change', (e) => {
groupB.querySelector(`[value="${e.target.value}"]`).checked = true
})
}
changeGroup(groupOne, groupTwo)
changeGroup(groupTwo, groupOne)
<div id="group-one">
<p>First group</p>
<label
>1
<input type="radio" name="number_people" value="1" />
<span ></span>
</label>
<label
>2
<input type="radio" name="number_people" value="2" />
<span ></span>
</label>
<label
>3
<input type="radio" name="number_people" value="3" />
<span ></span>
</label>
<label
>4
<input
type="radio"
name="number_people"
value="4"
checked="checked"
/>
<span ></span>
</label>
</div>
<br />
<div id="group-two">
<p>Second group</p>
<label
>1
<input type="radio" name="number_people2" value="1" />
<span ></span>
</label>
<label
>2
<input type="radio" name="number_people2" value="2" />
<span ></span>
</label>
<label
>3
<input type="radio" name="number_people2" value="3" />
<span ></span>
</label>
<label
>4
<input
type="radio"
name="number_people2"
value="4"
checked="checked"
/>
<span ></span>
</label>
</div>