У меня есть следующая форма с различными флажками и полем выбора с различными параметрами.
Когда пользователь нажимает на флажок, я хочу, чтобы соответствующий параметр был выбран автоматически.
Примеры:
Когда пользователь нажимает на «ввод» со значением = «Доступная лодка», выбирается «опция» с value = "1".
Когда пользователь нажимает «ввод» со значением «Доступные пробелы», выбирается «опция» со значением = «3».
Вот форма:
<form>
<input name = "title" type = "checkbox" class = "formElements" id = "title1" value = "Boat Available">Boat Available
<input name = "title" type = "checkbox" class = "formElements" id = "title2" value = "Spaces Available">Spaces Available
<input name = "title" type = "checkbox" class = "formElements" id = "title3" value = "Fully Booked">Fully Booked
<input name = "title" type = "checkbox" class = "formElements" id = "title4" value = "Not Available">Not Available
<input name = "title" type = "checkbox" class = "formElements" id = "title5" value = "Short Trip">Short Trip
<input name = "title" type = "checkbox" class = "formElements" id = "title6" value = "Trip Cancelled">Trip Cancelled
</form>
<select name = "epcCat[1]" class = "formElements" id = "category">
<option id = "101" value = "1">Boat Available</option>
<option id = "103" value = "3">Spaces Available</option>
<option id = "104" value = "4">Fully Booked</option>
<option id = "105" value = "5">Not Available</option>
<option id = "10204" value = "204">Short Trips</option>
<option id = "10180" value = "180">Trip Cancelled</option>
</select>1. Вы хотите радио 2. Опции не имеют идентификаторов 3. Установите значение



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Поскольку вы используете флажки (несколько из которых могут быть проверены параллельно), для того, что вы хотите, требуется select, который позволяет выбирать несколько вариантов, поэтому я добавил атрибут multiple:
let options = Array.from(category.querySelectorAll('option'));
document.forms[0].addEventListener('change', (e) => {
options.find(o=>o.textContent===e.target.value).selected = e.target.checked;
})<form>
<input name = "title" type = "checkbox" class = "formElements" id = "title1" value = "Boat Available">Boat Available
<input name = "title" type = "checkbox" class = "formElements" id = "title2" value = "Spaces Available">Spaces Available
<input name = "title" type = "checkbox" class = "formElements" id = "title3" value = "Fully Booked">Fully Booked
<input name = "title" type = "checkbox" class = "formElements" id = "title4" value = "Not Available">Not Available
<input name = "title" type = "checkbox" class = "formElements" id = "title5" value = "Short Trip">Short Trip
<input name = "title" type = "checkbox" class = "formElements" id = "title6" value = "Trip Cancelled">Trip Cancelled
</form>
<select name = "epcCat[1]" class = "formElements" id = "category" multiple>
<option id = "101" value = "1">Boat Available</option>
<option id = "103" value = "3">Spaces Available</option>
<option id = "104" value = "4">Fully Booked</option>
<option id = "105" value = "5">Not Available</option>
<option id = "10204" value = "204">Short Trip</option>
<option id = "10180" value = "180">Trip Cancelled</option>
</select>Пользователь должен иметь возможность установить только один флажок, а не несколько, можно ли это изменить, чтобы он работал таким образом?
Изменение флажка на радио и удаление «несколько» заставило ваш код работать, спасибо.
@Weyboat Честно говоря, это была ошибка твой, а не моя. Мой ответ был правильным в первую очередь, ваши спецификации были неясны в этом отношении, и ваш подход вводил в заблуждение. Приложите больше усилий к следующему вопросу, пожалуйста.
вы правы, конечно, это была моя вина, и ваш код помог мне обнаружить мою ошибку. Спасибо..
Я предположил, что вы заинтересованы в выборе одного варианта за раз (в противном случае это не имело бы никакого смысла). Изменены все флажки на переключатели, потому что вам нужно выбирать только одну категорию за раз. Также <form> оборачивается вокруг всего.
Подробности прокомментированы в демо
// Reference the <form>
var form = document.forms.main;
/*
Register the change event to form
When <form> is changed call sync()
*/
form.onchange = sync;
// sync() passes Event Object
function sync(event) {
// Reference all form tags under <form>
var ui = this.elements;
// Reference the changed radio button
var tgt = event.target;
// Find the radio button id and extract the number -1
var idx = (tgt.id.split('').pop()) - 1;
// Reference the <select>
var cat = ui.category;
// Reference the <option> at the position of idx
var opt = cat.options[idx];
// Select that <option>
opt.selected = true;
}<form id='main'>
<input name = "title" type = "radio" class = "formElements" id = "title1" value = "Boat Available">Boat Available
<input name = "title" type = "radio" class = "formElements" id = "title2" value = "Spaces Available">Spaces Available
<input name = "title" type = "radio" class = "formElements" id = "title3" value = "Fully Booked">Fully Booked
<input name = "title" type = "radio" class = "formElements" id = "title4" value = "Not Available">Not Available
<input name = "title" type = "radio" class = "formElements" id = "title5" value = "Short Trip">Short Trip
<input name = "title" type = "radio" class = "formElements" id = "title6" value = "Trip Cancelled">Trip Cancelled<br>
<select name = "epcCat[1]" class = "formElements" id = "category">
<option id = "101" value = "1">Boat Available</option>
<option id = "103" value = "3">Spaces Available</option>
<option id = "104" value = "4">Fully Booked</option>
<option id = "105" value = "5">Not Available</option>
<option id = "10204" value = "204">Short Trips</option>
<option id = "10180" value = "180">Trip Cancelled</option>
</select>
</form>На данный момент это не работает для меня, я очень тщательно сверю свой код с вашим и сообщу.
@Weyboat Я обмотал все вокруг тегом <form>, наверное, поэтому. Есть ли какая-то особая причина, по которой <select> не находится в том же <form>, что и флажки/радио?
Да, поле выбора используется в массиве выбранных элементов. Я только что попытался переместить закрывающий тег </form> ниже поля выбора, но, поскольку он является частью массива, он помещается ниже нескольких полей выбора.
ФФ работает с демо на этом сайте? Меня устраивает.
Да, у меня есть новый файл с рабочим кодом, мне просто нужно перевести его в мой существующий код. Возможно, я задержусь, но пока спасибо за помощь!
С минимальными изменениями в HTML (на самом деле только для того, чтобы сделать его действительным) вы можете сделать это:
Инициализировать на основе раскрывающегося списка
document.getElementById("main")
.addEventListener("change", (e) => {
if (e.target.name == "title") document.getElementById("category").value = e.target.value;
});
// Initialise based on dropdown
document.querySelector("[name=title][value='"+document.getElementById("category").value+"']").click(); <form id='main'>
<input name = "title" type = "radio" class = "formElements" id = "title1" value = "1">Boat Available
<input name = "title" type = "radio" class = "formElements" id = "title2" value = "3">Spaces Available
<input name = "title" checked type = "radio" class = "formElements" id = "title3" value = "4">Fully Booked
<input name = "title" type = "radio" class = "formElements" id = "title4" value = "5">Not Available
<input name = "title" type = "radio" class = "formElements" id = "title5" value = "204">Short Trip
<input name = "title" type = "radio" class = "formElements" id = "title6" value = "180">Trip Cancelled<br>
<select name = "epcCat[1]" class = "formElements" id = "category">
<option value = "1">Boat Available</option>
<option value = "3">Spaces Available</option>
<option value = "4">Fully Booked</option>
<option value = "5">Not Available</option>
<option value = "204">Short Trips</option>
<option value = "180">Trip Cancelled</option>
</select>
</form>Инициализация на основе радио
document.querySelectorAll("#main [name=title]").forEach(function(chk) {
chk.addEventListener("click", function() {
document.getElementById("category").value = this.value;
})
});
// initialise based on radio
document.querySelector("[name=title]:checked").click();<form id='main'>
<input name = "title" type = "radio" class = "formElements" id = "title1" value = "1">Boat Available
<input name = "title" type = "radio" class = "formElements" id = "title2" value = "3">Spaces Available
<input name = "title" checked type = "radio" class = "formElements" id = "title3" value = "4">Fully Booked
<input name = "title" type = "radio" class = "formElements" id = "title4" value = "5">Not Available
<input name = "title" type = "radio" class = "formElements" id = "title5" value = "204">Short Trip
<input name = "title" type = "radio" class = "formElements" id = "title6" value = "180">Trip Cancelled<br>
<select name = "epcCat[1]" class = "formElements" id = "category">
<option value = "1">Boat Available</option>
<option value = "3">Spaces Available</option>
<option value = "4">Fully Booked</option>
<option value = "5">Not Available</option>
<option value = "204">Short Trips</option>
<option value = "180">Trip Cancelled</option>
</select>
</form>
Что делать, если есть более одного флажка?