lalexa
lalexa

Reputation: 453

jQuery selecting issue, how to select elements when event occurred?

I have several buttons, by clicking on them depending on the state (true or false) stored in database, 0: using ajax changes value in db, 1:appears confirmation modal, if user confirms, then again using ajax value changes.

HTML:

<span class="1" data-state="{{ $subscribe->newsletter }}" data-type="1"></span>
<span class="2" data-state="{{ $subscribe->send_products }}" data-type="2"></span>
<span class="3" data-state="{{ $subscribe->send_shares}}" data-type="3"></span>

jQuery:

  var confirm_modal = $('#unsubscribe-confirmation');

  $('.1, .2, .3').click(function() {

     var button = $(this);
     var state = $(this).data('state');
     var type = $(this).data('type');

     if ( state == 1 ) {
        confirm_modal.modal();
     } else {
        $.ajax({
           'url': get_base_url_with_ajax_url() + 'subscribe',
           'data': { "state": state, "type" : type },
           'type': 'POST',
           'dataType': 'json',
           success: function(result) {
              button.attr('data-state', '1');
           }
        });
     }
  });
 confirm_modal.find('#confirm').click(function() {
     $.ajax({
        'url': get_base_url_with_ajax_url() + 'subscribe',
        'data': { "state": state, "type": type },
        'type': 'POST',
        'dataType': 'json',
        success: function(result) {
           $(this).attr('data-state', '0');
           confirm_modal.modal('hide');
        }
  });

So, in first statement, when changing data-state, selector $(this) is worked. But when appeares modal how can I select elements, which was taken at first: ".sbs-nwlttr, .sbs-evt, .sbs-prod"?

Thanks for attention.

Upvotes: 2

Views: 73

Answers (1)

benomatis
benomatis

Reputation: 5633

First of all, though I suspect you only used it for testing, avoid using one digit class names, and ones that start with a number as that's not allowed in css (more details can be found on that in this questions), so rename class="1" to class="one" for example.

On the other the only problem you have is that your button variable is not global, only declared inside one of the functions. Declare it outside, then you can make use of it in the other function too as follows:

var button;

$('.one, .two, .three').click(function() {

    button = $(this);
    // ...
}

confirm_modal.find('#confirm').click(function() {

    alert(button.text()); // for example

}

I set up a fiddle that demonstrates this (slightly different from the above, but should show the behaviour clearly: http://jsfiddle.net/wz6v306k/

Upvotes: 1

Related Questions