tirenweb
tirenweb

Reputation: 31709

jQuery: associate event to existing elements, and to new elements

I have a code to change an input value clicking on +/- symbols. When the value is 1, the character - disappears.

My doubt: I would like the '-' also dissapears when the page is loaded. How to do that?

I have tried it, using trigger this way below, but it doesn't work:

$(document).on('change', 'input', function() {
 //...
}).trigger('change');

This is my code:

$(document).on('change', 'input', function() {

  if ($(this).val() == 1) {
      $('.substract').hide();
  }   
});


$('.add').on('click', function() {
    
    var old_value = parseInt($('input').val());
    $('input').val(old_value + 1).change();

})

$('.substract').on('click', function() {
    
    var old_value = parseInt($('input').val());
    $('input').val(old_value - 1).change();
})
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  type="text" value="1">
<span class="add">+</span>
<span class="substract">-</span>

Upvotes: 0

Views: 28

Answers (4)

A. Wolff
A. Wolff

Reputation: 74420

Toggle a class:

$(document).on('change', 'input', function() {
      $(this).nextAll('.substract').first().toggleClass('hidden', this.value == 1);
});

HTML:

<span class="substract hidden">-</span>

CSS:

span.hidden {
    display: none;
}

DEMO

Upvotes: 0

Satpal
Satpal

Reputation: 133403

I would recommend you to use CSS

.substract { display:none; }

However using jQuery, just trigger the change event of input. Since you are using event delegation, you are bind event with document not with input thus .trigger('change'); didn't worked.

 $('input').change();

$(document).on('change', 'input', function() {

  if ($(this).val() == 1) {
    $('.substract').hide();
  }
});


$('.add').on('click', function() {

  var old_value = parseInt($('input').val());
  $('input').val(old_value + 1).change();

})

$('.substract').on('click', function() {

  var old_value = parseInt($('input').val());
  $('input').val(old_value - 1).change();
})

$('input').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="1">
<span class="add">+</span>
<span class="substract">-</span>

Upvotes: 1

taesu
taesu

Reputation: 4580

I'd hide the minus on load by putting

<span class="substract" style="display: none;">-</span>,

then add

if ($(this).val() == 1) {
    $('.substract').hide();
}else{
    $('.substract').show(); // add this line
}

Demo

Upvotes: 0

wezzy
wezzy

Reputation: 5935

Why don't you just use a style on loading:

<span class="substract" style='display:none'>-</span>

Or if you prefear jQuery

jQuery(document).ready(function($){
     $('.substract').hide();
}

Remember to wait the DOM ready to be sure that the element is loaded. I'll go for the first version and avoid that user could see the button and then see it disappearing after few seconds

Upvotes: 0

Related Questions