Skip to content
Advertisement

how to make blur all option after select 2 from 4?[jquery]

I want select 3 option from many.After select 3 option,all option will be blur so that anyone can’t select more.

Here I added my code,please check it.

Link to File

<!DOCTYPE html>
<html>
<head>
    <title>want to select</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>


<style>
.select {
    border: 1px solid blue;
    height: 25px;
    margin-bottom: 5px;
}
.fill {
    background-color: red;
}
</style>

<body>



<div class="select" id="1">Egg</div>
<div class="select" id="2">mango</div>
<div class="select" id="3">apple</div>
<div class="select" id="4">egg</div>
<div class="select" id="5">apple</div>
<div class="select" id="6">egg</div>




</body>
<script>
$('.select').click(function(e){
    var $et = $(e.target);
    if ($et.hasClass('fill')) { 
        $et.removeClass('fill');
    } else {
        if ($('.fill').length < 3) {
            $et.addClass('fill');
             $et.blur();
        }
    }
});
</script>
</html>

Advertisement

Answer

Consider the following.

$(function() {
  $('.select').click(function(e) {
    var $et = $(this);
    if ($et.hasClass('fill')) {
      $et.toggleClass('fill');
    } else if ($et.parent().find(".fill").length < 3) {
      $et.toggleClass('fill');
    }
    return false;
  });
});
.select {
  border: 1px solid blue;
  height: 25px;
  margin-bottom: 5px;
}

.fill {
  background-color: red;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div class="wrapper">
  <div class="select" id="1">Egg</div>
  <div class="select" id="2">mango</div>
  <div class="select" id="3">apple</div>
  <div class="select" id="4">egg</div>
  <div class="select" id="5">apple</div>
  <div class="select" id="6">egg</div>
</div>

Adding a wrapper allows for better reference to the parent. You can then check how many .fill elements there are inside the wrapper. Now you can conditionally remove or add fill class.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement