Search textbox using checkbox in Javascript

576 Views Asked by At

I am trying to do a text-search using a checkbox. For example, if the person selects the check box it will display the word/letter the user has entered into the search box(this word/letter will be highlighted). Say I enter "the" it will search for all "the" in the paragraph and will highlight all the "the". I already got that first part down what I am not understanding is how to make the checkbox connect with the text-search form. So when the user selects the checkbox "the" will display or whatever word/letter they enter into the search box.

I was thinking of using the if statement...

2

There are 2 best solutions below

0
On BEST ANSWER

You can use something like this:

$(':checkbox').on('change', function() {
    if ($(this).is(':checked')) {
        $(".content").addClass("highlight");
    } else {
        $(".content").removeClass("highlight");
    }
});

And in the CSS you need to have:

.highlight {background: #99f;}

Snippet

$(function () {
  text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt repellat sint eligendi adipisci consequuntur perspiciatis voluptate sunt id, unde aspernatur dolor impedit iure quaerat possimus nihil laboriosam, neque, accusamus ad.";
  $(".content").text(text);
  $(':checkbox').on('change', function() {
    if ($(this).is(':checked')) {
      $(".content").addClass("highlight");
      $(".content").html(text.replace(/lo/gi, '<span>lo</span>'));
    } else {
      $(".content").removeClass("highlight");
    }
  });
});
.check + input {display: none;}
.check:checked + input {display: inline-block;}
.highlight span {background: #ccf;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" class="check" />
<input type="text" placeholder="Type your terms..." class="term" />
<div class="content"></div>

Maybe something like the above.

0
On

So if you want to interact with that checkbox you could do something like:

$(':checkbox').on('change', function() { 
    if ($(this).is(':checked')) { 
        // do your search thing 
    } else {
        // turn off your search thingy
    } 
});

Fiddle