У меня есть HTML-файл с двумя текстовыми полями и одним щелчком. Нажатие кнопки распечатает текст, введенный в текстовое поле. HTML-ФАЙЛ НИЖЕ:
<main>
<!--Input-->
<section class = "StudentAndCourseInfo">
<!--Student Info-->
<p>First Name</p>
<input type = "text" name = "firstName">
<p>Last Name</p>
<input type = "text" name=lastName>
<button> Capture Name </button>
</section>
<!--Output-->
<section class=registeredCourses ">
<h2><i><u>Registered Courses</u></i></h2>
</main>
JavaScript
var main = function() {
"use strict";
var addCommentForCaptureName = function() {
var $newComment = $("<p>");
var commentText1 = $(".StudentAndCourseInfo input").val();
var commentText2 = $(".StudentAndCourseInfo input").val();
if (commentText1 !== "" && commentText2 !== "") {
$newComment.text(commentText1 + commentText2 + " is registered for the following courses:");
$(".registeredCourses").append($newComment);
}
}
$(".StudentAndCourseInfo button").on("click", function(event) {
addCommentForCaptureName();
});
};
$(document).ready(main);
Извини за это. Когда я ввожу текст в два текстовых поля и нажимаю кнопку, текст не отображается в разделе зарегистрированных курсов.
Хм, я изменил их все, но все равно получаю неверные результаты. мой полный HTML-код
Что ты пробовал?
Пожалуйста, сформулируйте свой вопрос правильно. Прочитать stackoverflow.com/help/how-to-ask



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


Когда вы используете ".StudentAndCourseInfo input", вы всегда выбираете один и тот же (первый) вход.
Используйте атрибут равно селектору [name = ”value”], чтобы выбрать нужный элемент.
Также в вашем последнем элементе <section> отсутствует закрывающий тег.
например
var addCommentForCaptureName = function() {
var $newComment = $("<p>");
var commentText1 = $(".StudentAndCourseInfo input[name='firstName']").val();
var commentText2 = $(".StudentAndCourseInfo input[name='lastName']").val();
if (commentText1 !== "" && commentText2 !== "") {
$newComment.text(commentText1 + " " + commentText2 + " is registered for the following courses:");
$(".registeredCourses").append($newComment);
}
};
$(".StudentAndCourseInfo button").on("click", function(event) {
addCommentForCaptureName();
});<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<!--Input-->
<section class = "StudentAndCourseInfo">
<!--Student Info-->
<p>First Name</p>
<input type = "text" name = "firstName">
<p>Last Name</p>
<input type = "text" name=lastName>
<button> Capture Name </button>
</section>
<!--Output-->
<section class = "registeredCourses">
<h2><i><u>Registered Courses</u></i></h2>
</section>
</main>Вы получаете значение из первого текстового поля в обоих операторах. Таким образом, значение первого текстового поля повторяется. Поскольку оба текстовых поля имеют разные имена, вам необходимо настроить их с помощью селектора атрибутов перед выборкой значений.
Ниже приводится рабочая демонстрация:
var main = function() {
"use strict";
var addCommentForCaptureName = function() {
var $newComment = $("<p>");
var commentText1 = $(".StudentAndCourseInfo input[name=firstName]").val();
var commentText2 = $(".StudentAndCourseInfo input[name=lastName]").val();
if (commentText1 !== "" && commentText2 !== "") {
$newComment.text(commentText1 + commentText2 + " is registered for the following courses:");
$(".registeredCourses").append($newComment);
}
}
$(".StudentAndCourseInfo button").on("click", function(event) {
addCommentForCaptureName();
});
};
$(document).ready(main);<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<!--Input-->
<section class = "StudentAndCourseInfo">
<!--Student Info-->
<p>First Name</p>
<input type = "text" name = "firstName">
<p>Last Name</p>
<input type = "text" name=lastName>
<button> Capture Name </button>
</section>
<!--Output-->
<section class = "registeredCourses">
<h2><i><u>Registered Courses</u></i></h2>
</section>
</main>Это связано с тем, что методы обработчиков событий on('click';,function... находятся внутри другой функции main и являются частными для функции main. Таким образом, событие не будет прикреплено к элементу, пока не будет вызван main. Сначала активируйте этот метод, вызвав main().
Также кажется, что нет необходимости помещать эти две функции внутри основного метода
var main = function() {
"use strict";
var addCommentForCaptureName = function() {
var $newComment = $("<p>");
var commentText1 = $(".StudentAndCourseInfo input").val();
var commentText2 = $(".StudentAndCourseInfo input").val();
if (commentText1 !== "" && commentText2 !== "") {
$newComment.text(commentText1 + ' ' + commentText2 + " is registered for the following courses:");
$(".registeredCourses").append($newComment);
}
}
$(".StudentAndCourseInfo button").on("click", function(event) {
addCommentForCaptureName();
})
}
main()<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<!--Input-->
<section class = "StudentAndCourseInfo">
<!--Student Info-->
<p>First Name</p>
<input type = "text" name = "firstName">
<p>Last Name</p>
<input type = "text" name = "lastName">
<button> Capture Name </button>
</section>
<!--Output-->
<section class = "registeredCourses">
<h2><i><u>Registered Courses</u></i></h2>
</section>
</main>
в чем вопрос? Также сообщите нам, в чем заключается ваша проблема здесь, в коде.