webdevexp
webdevexp

Reputation: 109

Disable toggle based on a condition

I am trying to disable a toggle function based on the value of the input field. Below is the markup

<ul>
  <li><input type="text" class="search" placeholder="Search..." id="search"></li>
  <li><button type="submit" id="search-submit"><span></span></button></li>
</ul>

Initially the search input will have width set to 0. On clicking the submit button, a toggle class is added which will animate the width of the text input. If there's any value in the text input, on clicking the submit button it should redirect to a page but it shouldn't toggle. I tried the below javascript but somehow not able to disable the toggle.

$('.sm-search button').click(function () {
 $('.search').toggleClass('search-expand');
});
$('.search').on('change keyup paste', function () {
 if ($(this).val() != "") {
  $('.sm-search button').click(function () {
   window.location.href = "/some-url";
   $('.search').addClass('search-expand');
  });
 } 
});

Upvotes: 0

Views: 564

Answers (1)

schildi
schildi

Reputation: 136

your jQuery-selectors don't match your HTML-classes, but that's probably just a problem right here.

What's happening here is:

you add multiple JS-listener to your button, which are all executed. If you want your code, you have to remove the initial "click"-listener.

try:

$('.sm-search button').click(function () {
 $('.search').toggleClass('search-expand');
});
$('.search').on('change keyup paste', function () {
 if ($(this).val() != "") {
  $('.sm-search button').off('click').click(function () {
   window.location.href = "/some-url";
   $('.search').addClass('search-expand'); // this shouldn't be necessary anymore, since you do not toggle the class anymore
  });
 } else {
    $('.sm-search button').off('click').on('click', function () {
      $('.search').toggleClass('search-expand');
    });
 }
});

Upvotes: 1

Related Questions