简体   繁体   中英

Using JavaScript to create a card element?

I want to make a simple app that allows users to enter text in 2 input boxes and upon clicking a button, a new card element is generated in the view. This is very similar to a todo list, but most todo list either use a single Div, or they use and just edit the list with user input.

I know how to add info to an existing div or element based on ID and working with user input in general, but I am not sure how to go about actually making a button that when clicked, creates a “card” which displays the users input.

Basically, I am trying to create a todo app, but instead of the classic to do list UI which shows a Unordered List, I want each to do list item to be connected to a new independent card element. I also want each of these new card elements to be deleted if the user clicks a delete button under it.

I would really appreciate if someone can point me in the right direction on where to start.

Thank you all.

Here's a proto-example using JQuery. It shouldn't be too hard to convert it to raw Javascript if need be.

Basically what you're doing here is looping through all of the todos and making a div ("card") for each of them. The loop allows you to add a custom id for each card based on the index of the todo, and the values are taken from the properties of the respective todo objects.

Then, when you click the button, you just push a blank todo to the todos array.

Here's the HTML:

<div>
  <div id="todos-container">

  </div>

  <button id="btnAddtoList">Add</button>
</div>

And the JS

let todos = [
  {input1: 'Input0-0', input2: 'Input0-1'},
  {input1: 'Input1-0', input2: 'Input1-1'}
];

function runEach() {
  $('#todos-container').html(''); // clear the list
  // create a new div for each todo
  $.each( todos, function( index, value ){
     var newCard = $(`<div class="todo card" id="card-${index}""><input type="text" value="${value.index1}" />Input 1 <input type="text" value="${value.index2}" />Input 2</div>`);
     $('#todos-container').append(newCard); // append the new card to the container
  });
}

$('#btnAddtoList').click(function(){
    todos.push({input1: '', input2: ''}); // add a todo
    runEach(); // run the function to re-add the cards
});

runEach();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM