Jimmy Jimmy - 4 months ago 17
HTML Question

Take selected icon list values into an input box

I'm new to JS and I'm trying to make a password generator using icons. It's designed so that you click on any number of icons in a list and the hex code is put into an input box. Two important bits:


  • The hex codes appear in the input box the same no matter what order you selected the icons in.

  • You can toggle and untoggle the icons.



Here is my code so far:

https://jsfiddle.net/uvzb8a6s/1/

HTML

<input id="pass">
<ul id="icons">
<li class="icon">&#9824;</li>
<li class="icon">&#9742;</li>
<li class="icon">&#9743;</li>
<li class="icon">&#9744;</li>
</ul>


JS

$('#icons li').click(function() {
$(this).toggleClass( "active" );
$('#pass').text('#icons li');
});


How do I get the value of all active li's listed into the input box, something like this (if I had clicked icon three and then icon one:

&#9824;&#9743;

Answer
  • Select li elements that has active class with li.active
  • Get their texts with .text() method.
  • Set the input's value with .val(value) method.

Additionally:

  • To get html entity string instead of characters inside the input, you can replace each character with its entity string manually. See the Stringify button in the example.

$('#icons li').click(function() {
  $(this).toggleClass("active");
  $("#pass").val($("#icons li.active").text());
});

$("button").on("click", function() {
  var lookup = {
    "♠": "&#9824;",
    "☎": "&#9742;",
    "☏": "&#9743;",
    "☐": "&#9744;"
  }

  $("#pass").val($("#pass").val().replace(/(.)/g, function(char) {
    return lookup[char];
  }));
});
ul li {
  list-style: none;
  display: inline;
}
.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="pass">
<button>Stringify</button>
<ul id="icons">
  <li class="icon">&#9824;</li>
  <li class="icon">&#9742;</li>
  <li class="icon">&#9743;</li>
  <li class="icon">&#9744;</li>
</ul>

Updated jsFiddle