У меня проблемы с моим кодом. Я пытаюсь создать массив с элементами, исходящими из html.
Мой html:
<h2>Write the name of a friend </h2>
<input id="friends" type="text"/> <input type="button" value="Add name" button onclick="enter()"/>
и мой jquery:
myArray =[];
function enter() {
var friend = $("#friends").val();
myArray.push(friend);
};
благодаря
Да, ваш код работает. Вам просто нужно удалить эту дополнительную button
в button onclick="enter()"/>
:
<input type="button" value="Add name" onclick="enter()"/>
"Как я могу увидеть массив после ввода имен?" Это зависит от вас, вы можете просто нажать alert()
и вы увидите текущее значение массива: alert(myArray);
, Или вы можете добавить новый элемент и показать/вывести значение вашего массива onclick. Также почему бы не переключиться на ненавязчивый способ обработки событий:
HTML:
<h2>Write the name of a friend </h2>
<input id="friends" type="text" />
<input type="button" value="Add name">
<p id="output"></p>
JQuery:
myArray = [];
$('input[type="button"]').click(function () {
var friend = $('#friends').val();
myArray.push(friend);
$('#output').text('My Friends: '+ myArray)//output myArray value
$('#friends').val('');//reset the input field
});
Вот скрипка.