JQuery – Click – Same Class But On Many Element

Listed Element

<div class="links">
  <ul style="font-size: 20px">
    <li data-id="1">Nepal</li>
    <li data-id="2">India</li>
    <li data-id="3">China</li>
    <li data-id="4">Bhutan</li>
  </ul>
</div>

Anchor Click with Class

<div class="links">
   <a href="javascript:void(0)" class="test" data-id="red">Red</a><br>
   <a href="javascript:void(0)" class="test" data-id="green">Green</a><br>
   <a href="javascript:void(0)" class="test" data-id="blue">Blue</a><br>
</div>

Anchor Click with Function
<div class="links">
   <ul style="font-size: 20px">
       <a data-id="1" onclick="myfunction(event)" href="">First</a><br>
       <a data-id="2" onclick="myfunction(event)" href="">Second</a><br>
       <a data-id="3" onclick="myfunction(event)" href="">Third</a><br>
       <a data-id="4" onclick="myfunction(event)" href="">Fourth</a><br>
   </ul>
</div>

JQuery on Class

<script type="text/javascript">
   $('.test').on('click',function(event){
       event.preventDefault();
       var $target = $(event.target);
       var itemId = $target.data('id');
       alert(itemId);
   });
</script>

JQuery on Function

<script>
    function myfunction(event){
       event.preventDefault();
       var $target = $(event.target),
       itemId = $target.data('id');
       alert(itemId);
    }
</script>

JQuery on Class

<script type="text/javascript">
  $(document).ready(function(){
      $('ul').on('click li',function(e){
          e.preventDefault();
          var $target = $(e.target),
          itemId = $target.data('id');
          alert(itemId);
      });
  });
</script>

Event from Child Node but ID is Of Parent Node

<script type="text/javascript">
    $(document).ready(function(){
       event.preventDefault();
        $target = $(event.currentTarget);
        var id = $target.data('id');
        var col = $target.data('col');
   });
</script>

NOTE:

  • Using “javascript:void(0);” in anchor tag: Writing “javascript:void(0);” in anchor tag can prevent the page to reload and JavaScript functions can be called on single or double clicks easily.
  • Using e.preventDefault() will also prevent from working for current event(e)
  • $(event.currentTarget)  is to select the parent node of current event

Set Content – text(), html(), and val()

We will use the same three methods from the previous page to set content:

  • text() – Sets or returns the text content of selected elements
  • html() – Sets or returns the content of selected elements (including HTML markup)
  • val() – Sets or returns the value of form fields

$("#btn1").click(function(){
    $("#test1").text("Hello world!");
});


$("#btn2").click(function(){
    $("#test2").html("<b>Hello world!</b>");
});


$("#btn3").click(function(){
    $("#test3").val("Dolly Duck");
});

Leave a Reply

Your email address will not be published. Required fields are marked *