3.4 KiB
DOM Input
LESSON OBJECTIVES
after this lesson, students will be able to:
- Capture text input from the browser
- Use a form's submit event
- Build a list from input
Capture text input from the browser
Provide a means for the user to provide input, and capture that input with an event handler.
Make an input field and a button in index.html
<input type="text" id="input-box" />
<input type="submit" id="submit-btn" />
Set an event on the submit
$('#submit-btn').on('click', () => {
console.log('clicked');
});
Make it so the handler grabs the value inside the input box (and logs it to check)
Use jQuery .val()
$('#input-box').val()
$('#submit-btn').on('click', () => {
console.log('clicked');
console.log( $('#input-box').val() );
});
Use a form's submit event
With a form tag you can hit the enter key to submit the form data.
<form>
<input type="text" placeholder="enter your name" id="input-box"/>
<input type="submit" value="SUBMIT"/>
</form>
Set the handler on the form element instead of the submit.
$('form').on('submit', () => {
console.log('clicked');
console.log( $('#input-box').val() );
});
Prevent default refresh
When you submit the form, the default action is to refresh the page. Let's prevent this default behavior using the freebie event.
$('form').on('submit', (event) => {
console.log('clicked');
console.log( $('#input-box').val() );
event.preventDefault();
});
Reset your input field
.trigger() can trigger events on elements (click, hover, etc). The reset event clears a text input
$(elem).trigger('reset');
$('form').on('submit', (event) => {
console.log('clicked');
console.log( $('#input-box').val() );
event.preventDefault();
$(event.currentTarget).trigger('reset');
});
Build a list from input
Make a nonsense list to store any kind of nonsense
- Make a
listarray where nonsense data will be stored - Push input into the list
- Run a function render that will render items in the list.
const list = [];
$('form').on('submit', (event) => {
console.log('clicked');
console.log( $('#input-box').val() );
list.push( $('#input-box').val() );
event.preventDefault();
$(event.currentTarget).trigger('reset');
render();
});
- Make render function to iterate over all items in the list
const render = () => {
console.log('render everything in the list');
console.log('list: ', list);
list.forEach((item) => {
console.log(item);
});
}
-
Let's build in some
uls for the list items<ul></ul> -
Make a list item for every item in the array
const render = () => {
console.log('render everything in the list');
console.log('list: ', list);
$('ul').empty();
list.forEach((item) => {
$('ul').append('<li>' + item + '</li>');
});
}
- Add an event listener to each item that calls on one single event handler
list.forEach((item) => {
const $li = $('<li>' + item + '</li>');
$li.on('click', doNonsense);
$('ul').append($li);
});
const doNonsense = (event) => {
console.log('item clicked: ', event.currentTarget);
$(event.currentTarget).css('background-color', 'red');
}
