Javascript - Focusout does not activate AJAX

Asked

Viewed 180 times

1

Hello! I’m having a problem with JS which is the following: The focusout event is not activating $.ajax

JS:

$('.focusout_input_budget').focusout(function () {
  var amount = $(this).val(),
      id = $(this).parent('.line-table-products').attr('data-id'),
      nomeprod = $(this).parent('.line-table-products').find('.coll1-line-product-list').html();

  if (amount > 0) {
     $.ajax({
        url : SITE  + 'addbudget',
        type: "POST",
        dataType: "JSON",
        data: { id: id, amount: amount, nomeproduto: nomeproduto },
        async: false,
        success: function (json) {
           json = json;
           if (json['true'] === 'true') {
              $('.icon-inform-budge').html(json['quant']);
              console.log(json['quant']);
              if (json['quant'] == 1) { 
                 $('#products-budge-top li').first().remove();
                 var li = "<li class='item-product-budge-top'>"+json['nome']+"</li>";
                 $('#products-budge-top').append(li);
              }
              if (json['quant'] > 1 && json['quant'] <= 5) {
                 $('#products-budge-top li').last().remove();
                 var li = "<li class='item-product-budge-top'>"+json['nome']+"</li>";
                 $('#products-budge-top').append(li);
              }
              if (json['quant'] == 6) {
                 $('#products-budge-top li').last().remove();
                 var li = "<li class='item-product-budge-top'>Ver todos os produtos...</li>";
                 $('#products-budge-top').append(li);
              }
              if(json['quant'] >= 6){
                 $('#products-budge-top li').first().remove();
                 var li = "<li class='item-product-budge-top'>"+json['nome']+"</li>";
                 $('#products-budge-top').append(li);
              }                     
              var link = SITE + 'carrinho';
              var last = "<li class='item-product-budge-top'><a href='"+link+"' title='acessar carrinho' class='button-budget-budge-top'>Revisar Orçamento</a></li>";
              $('#products-budge-top').append(last);

              $(this).html('ADICIONADO COM SUCESSO');
              setTimeout(function(){
                 $('.button-add-product-budget').html('ADICIONAR AO ORÇAMENTO');
              },200);           
           } else {
              $(this).html('ERRO AO ADICIONAR');
              setTimeout(function(){
                 $('.button-add-product-budget').html('ADICIONAR AO ORÇAMENTO');
              },2000);            }
        }
     });

  } else {
     $.ajax({
        url : SITE  + 'removebudget',
        type: "POST",
        dataType: "JSON",
        data: { id:id },
        async: false,
        success: function(json){
           json = json;
           if(json == 'true'){
              location.reload();
           }
        }
     });
  }
});

html:

<ul id="main-products">
            <li class="line-table-products line-title-table-products">
                <span class="coll-line-product coll-title-line-product coll1-line-product">NOME DO PRODUTO</span>
                <span class="coll-line-product coll-title-line-product coll2-line-product">UNIDADE</span>
                <span class="coll-line-product coll-title-line-product coll3-line-product">QUANTIDADE</span>
                <span class="coll-line-product coll-title-line-product coll4-line-product">ADICIONAR AO MEU ORÇAMENTO</span>
            </li>
            <?php foreach($produtos as $prod){ ?>
            <li class="line-table-products" data-id="<?php echo $prod->codigo; ?>">
                <span class="coll-line-product coll1-line-product coll1-line-product-list <?php if(check_size_line($prod->nome, 36, 'space') == 'true') echo 'item-large-size-products'; ?>"><?php echo $prod->nome; ?></span>
                <span class="coll-line-product coll2-line-product"><?php echo $prod->unidade; ?></span>
                <div class="coll-line-product coll3-line-product">
                    <img src="<?php echo IMG . 'px.png'; ?>" alt="Icone diminui quantidade" data-operation="subtraction" class="icon-amount-product-budget icon-decrease-product-budget" />
                    <input type="text" name="productqtd" value="<?php echo check_prod_in_budget($prod->codigo); ?>" placeholder="00" class="input-amount-product-budget focusout_input_budget"/>
                    <img src="<?php echo IMG . 'px.png'; ?>" alt="Icone diminui quantidade" data-operation="sum" class="icon-amount-product-budget icon-increase-product-budget" />
                </div>
                <span class="coll-line-product coll4-line-product button-add-product-budget">ADICIONAR AO ORÇAMENTO</span>
            </li>
            <?php } ?>
        </ul>

Someone could help me?

  • But the event used there is the blur.

  • I already tried and it didn’t work either, then a colleague told me to use the focusout event

  • the code works until the "if(amount > 0){" check then it no longer works!

  • You can mount an example with HTML here or in jsFiddle?

  • jsFiddle: https://jsfiddle.net/samuelbdesouza/ufetc77b/

1 answer

3


There is an error in your if, some '{' were in wrong places, put it that way:

if(amount > 0){
    $.ajax({
        url : SITE  + 'addbudget',
        type: "POST",
        dataType: "JSON",
        data: { id:id, amount:amount, nomeproduto:nomeproduto },
        async: false,
        success: function(json){
            json = json;
            if(json['true'] == 'true'){
                $(this).html('ADICIONADO COM SUCESSO');
            }
            else {
                $(this).html('ERRO AO ADICIONAR');
            }
        }
    });

}

Below is a functional example using jquery on().

jQuery(document).ready(function(){
  jQuery('#teste').on('focusout',function(){
     alert('focusout ativado');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="teste">

  • I corrected the errors, but it’s not working yet!

  • Post the current and complete code including the html elements

  • I edited the question by adding html and js

  • I tested your code in jsfiddle itself and gave problem in the variable SITE, it is not set please check, other than this by removing all the sites that it is worked normal, try to add first of all to 'var SITE = ' ';'

  • The variable "url : SITE + 'addbudget'," is sending the data to a page that registers the codes in the session and in the bank, I already tested this same code with the click event and works normally, only with the focusout or Blur that is not working!

  • The event is triggered ? has how to put console.log in to confirm. I’ll do an example with out

  • I just added a functional example using on() jQuery.

  • The event is triggered, but it did not declare $.ajax(), I switched these lines: var amount = $(this). val(), id = $(this). Parent('.line-table-products'). attr('data-id'), for these: var amount = $(this). val(), id = $(this). attr('data-id'), and added a data-id in the input and worked

  • Congratulations friend, I’m glad you decided, until next time.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.