Я пытаюсь создать форму, в которой пользователь может выбрать, хотят ли они получать электронные письма о собаках и / или кошках, выбрать уведомления по электронной почте или смс, ввести свой адрес электронной почты / номер телефона, а затем отправить. У меня есть все, кроме адреса электронной почты/телефона. Что бы я ни делал, я всегда возвращаю пустую строку для значения текстового поля ввода.
Я думаю, что проблема как-то связана с тем, что я скрываю текстовое поле и кнопку отправки при загрузке страницы. Я пробовал различные способы доступа к значению текстового поля, такие как доступ к нему непосредственно в функции прослушивателя событий, обновление его с помощью переменной и доступ к этому значению и т. д. Я думал, что что-то сделал с функцией textbox_update, которую я добавил с тех пор Теперь я вижу, что я печатаю, отражено в переменной textbox_value, но я не смог передать это в функцию прослушивателя событий.
Любая помощь приветствуется.
let form = document.querySelector('.form');
let change = document.getElementById('change');
const input = document.querySelector(".send");
//input.addEventListener('change', smsORemail);
input.onchange = function() {
smsORemail
};
function smsORemail() {
let choice = form.notif.value;
if (!choice) {
return;
}
if (choice === 'email') {
change.innerHTML = 'Email: ';
const textbox = document.getElementById("textbox")
textbox.style.display = "block";
textbox.value = "";
textbox.placeholder = "[email protected]";
document.getElementById("submit").style.display = "block";
} else if (choice === 'sms') {
change.innerHTML = 'Phone: ';
const textbox = document.getElementById("textbox")
textbox.style.display = "block";
textbox.value = "";
textbox.placeholder = "555-555-5555";
document.getElementById("submit").style.display = "block";
}
}
document.getElementById("textbox").oninput = textbox_update;
function textbox_update() {
let textbox_value = document.querySelector('input[name = "comm_textbox"]').value;
console.info(textbox_value)
return textbox_value;
}
form.addEventListener('submit', event => {
event.preventDefault();
let textbox_value = textbox_update();
const formData = new FormData(form);
//console.info(formData.getAll('notif'));
console.info(formData.get('notif'));
console.info(formData.get('chk_dog'));
console.info(formData.get('chk_cat'));
console.info(formData.get('comm_textbox'));
console.info(textbox_value);
})<form name = "myform" onchange = "smsORemail()" class = "form">
<p>Would you like notifications for new dogs and/or new cats?</p>
<input type = "checkbox" id = "dog_checkbox" name = "chk_dog" value = "dogs"> Dogs<br>
<input type = "checkbox" id = "cat_checkbox" name = "chk_cat" value = "cats"> Cats
<br><br>
<p>Would you like email or sms notifications?</p>
<input type = "radio" class = "send" id = "email_id" name = "notif" value = "email">
<label for = "email_id">E-mail</label>
<input type = "radio" class = "send" id = "sms_id" name = "notif" value = "sms">
<label for = "sms_id">SMS</label>
<br><br>
<label for = "textbox" id = "change" style = "text-align: left; float: left;padding-right: 5px;"></label>
<input type = "text" name = "comm_textbox" id = "textbox" style = "display: none;" placeholder = "" value = "">
<br>
<button type = "submit" id = "submit" style = "display: none;">Submit</button>
</form>


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


Так что в основном это действительно из-за вашей функции очистки, функция вызывается при onChange объявления формы, и, как вы можете видеть в этой строке
textbox.value = "";
Очистит значение текстового поля, проблема заключается в том, что когда вы вызываете его в событии onchage формы, любой тип изменения, включая щелчок отправки, вызовет функцию и очистит значения до вызова функции щелчка.
[![введите здесь описание изображения][1]][1]
Сделайте так, чтобы ваша чистая функция запускалась только с помощью переключателей, нет необходимости в вызове строки onChange в объявлении формы, поэтому просто удалите первый вызов в onChange и убедитесь, что назначение radioButton правильное
например
1 - Удалите вызов onChange() в первой строке вашего html.
<form name = "myform" class = "form">
2 - Измените назначение переключателя onChange, чтобы он имел «()» для запуска функции.
input.onchange = function() {
smsORemail()
};
Полный код:
<form name = "myform" class = "form">
<p>Would you like notifications for new dogs and/or new cats?</p>
<input type = "checkbox" id = "dog_checkbox" name = "chk_dog" value = "dogs"> Dogs<br>
<input type = "checkbox" id = "cat_checkbox" name = "chk_cat" value = "cats"> Cats
<br><br>
<p>Would you like email or sms notifications?</p>
<input type = "radio" class = "send" id = "email_id" name = "notif" value = "email">
<label for = "email_id">E-mail</label>
<input type = "radio" class = "send" id = "sms_id" name = "notif" value = "sms">
<label for = "sms_id">SMS</label>
<br><br>
<label for = "textbox" id = "change" style = "text-align: left; float: left;padding-right: 5px;"></label>
<input type = "text" name = "comm_textbox" id = "textbox" style = "display: none;" placeholder = "" value = "">
<br>
<button type = "submit" id = "submit" style = "display: none;">Submit</button>
</form>
<script>let form = document.querySelector('.form');
let change = document.getElementById('change');
const input = document.querySelector(".send");
//input.addEventListener('change', smsORemail);
input.onchange = function() {
smsORemail()
};
function smsORemail() {
let choice = form.notif.value;
if (!choice) {
return;
}
if (choice === 'email') {
change.innerHTML = 'Email: ';
const textbox = document.getElementById("textbox")
textbox.style.display = "block";
textbox.value = "";
textbox.placeholder = "[email protected]";
document.getElementById("submit").style.display = "block";
} else if (choice === 'sms') {
change.innerHTML = 'Phone: ';
const textbox = document.getElementById("textbox")
textbox.style.display = "block";
textbox.value = "";
textbox.placeholder = "555-555-5555";
document.getElementById("submit").style.display = "block";
}
}
document.getElementById("textbox").oninput = textbox_update;
function textbox_update() {
let textbox_value = document.querySelector('input[name = "comm_textbox"]').value;
console.info(textbox_value)
return textbox_value;
}
form.addEventListener('submit', event => {
event.preventDefault();
let textbox_value = textbox_update();
const formData = new FormData(form);
//console.info(formData.getAll('notif'));
console.info(formData.get('notif'));
console.info(formData.get('chk_dog'));
console.info(formData.get('chk_cat'));
console.info(formData.get('comm_textbox'));
console.info(textbox_value);
})
</script>
Было несколько вещей,
Я удалил некоторые функции, которые мешали печатать (let textbox_value = textbox_update();)
Добавлен делегированный обработчик событий для радиостанций.
Я также переименовал кнопку отправки, так как любое имя отправки в форме будет мешать обработчику отправки.
Быть последовательным. Используйте addEventListener везде вместо «onevent» где-то и eventlistener в другом месте
Переключить «скрытый» проще, чем изменить отображение между блоком и отсутствием
const form = document.querySelector('.form');
const change = document.getElementById('change');
const input = document.querySelector(".send");
const textbox = document.getElementById("textbox");
const subbut = document.getElementById("subbut");
form.addEventListener('click', smsORemail);
function smsORemail(e) {
const tgt = e.target;
if (!tgt.matches("[name=notif]")) return;
let choice = document.querySelector("input[name=notif]:checked")?.value || "";
textbox.hidden=true;
subbut.hidden= true;
if (!choice) {
return;
}
if (choice === 'email') {
change.innerHTML = 'Email: ';
textbox.value = "";
textbox.placeholder = "[email protected]";
} else if (choice === 'sms') {
change.innerHTML = 'Phone: ';
textbox.value = "";
textbox.placeholder = "555-555-5555";
}
subbut.hidden= false;
textbox.hidden=false;
}
form.addEventListener('submit', event => {
event.preventDefault();
const formData = new FormData(form);
//console.info(formData.getAll('notif'));
console.info(formData.get('notif'));
console.info(formData.get('chk_dog'));
console.info(formData.get('chk_cat'));
console.info(formData.get('comm_textbox'));
console.info(textbox_value);
})<form name = "myform" class = "form">
<p>Would you like notifications for new dogs and/or new cats?</p>
<input type = "checkbox" id = "dog_checkbox" name = "chk_dog" value = "dogs"> Dogs<br>
<input type = "checkbox" id = "cat_checkbox" name = "chk_cat" value = "cats"> Cats
<br><br>
<p>Would you like email or sms notifications?</p>
<input type = "radio" class = "send" id = "email_id" name = "notif" value = "email">
<label for = "email_id">E-mail</label>
<input type = "radio" class = "send" id = "sms_id" name = "notif" value = "sms">
<label for = "sms_id">SMS</label>
<br><br>
<label for = "textbox" id = "change" style = "text-align: left; float: left;padding-right: 5px;"></label>
<input type = "text" name = "comm_textbox" id = "textbox" hidden placeholder = "" value = "">
<br>
<button type = "submit" id = "subbut" hidden>Submit</button>
</form>
Никогда не называйте ничего «отправить» в форме