manbearpig1 manbearpig1 - 2 months ago 6
Javascript Question

Javascript - Distinguish between similar list items

Each list item is appended by this for loop. Imagine a list with three elements, for example. Two buttons in a row comprise each list element. The goal is to first hide all of the .second buttons by default. When a specific .first button is clicked, that specific .first button is hidden and that specific .second button is shown. By specific, I mean belonging to the same list element.

for (i=0; i<userLog.length; i++) {
$('#modalChoices').append("<li id='modalItem'><input class='modalInput btn btn-primary first' type='button'> <input class='modalInput btn btn-success second' type='button'></li>");
}

// Hide all seconds by default.
$('.second').hide();

$('.first').on('click', function() {
$('.first').hide();
$('.second').show();
});


We can hide all of the seconds and all of the firsts very easily. How do we distinguish between list items? Is there some 'this' selector that will accomplish this?

Answer

One-liner to fix this problem. $(this) refers to the input.first being clicked and next() is its adjacent input.second. It should be faster to use next than to use siblings.

$('.first').click(function() {
    $(this).hide().next('.second').show();
});

  for (i=0; i<5; i++) {
      $('#modalChoices').append("<li id='modalItem'><input class='modalInput btn btn-primary first' value='first' type='button'> <input class='modalInput btn btn-success second' type='button' value='second'></li>");
    }

  // Hide all seconds by default.
  $('.second').hide();

  $('.first').click(function() {
    $(this).hide().next('.second').show();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modalChoices"></div>