Jquery Properties and Each Demo

Jquery Properties and Each Demo

by Shrikrishna Gupta

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="addToContexts">
  <option>private</option>
  <option>public</option>
  <option>shared</option>
</select>
<br />
<br />
<ul>
  <li>private</li>
  <li>public</li>
  <li>shared</li>
</ul>

CSS

li {
  margin: 15px;
  cursor: pointer;
}

li:hover {
  color: #f00;
}

JavaScript

/* certain action */
$("li").on("click", function() {
  var aux = $(this /*li*/ ).html();

  $('#addToContexts > option')

  /* remove all selected true options */
  .prop("selected", false)

  /* and for each one verify to check true */
  .each(function() {

    /* I'm using here .html() comparison..
    you can change it by what you want */

    if ($(this).html() === aux) {
      $(this /*option*/ ).prop("selected", true);
    }

  });

});