Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically trigger a blur event with jQuery

Tags:

jquery

I have a matrix of sort with rows of inputs of class oneInput and I have a jquery function that triggers on the blur event of any of those inputs and sums the row and the column and inserts the sum into the proper place -- all of this works like I intend.

What I am trying to do is on page load to total all rows and columns with the initial values. I am calling an init() function on document.ready and I have tried both of the following without success.

function init(){
  $('.oneInput').trigger('blur');
}

or

function init(){
    $('.oneInput').each(function(){
      $(this).trigger('blur');
    });
  }

The function that is triggered on that blur event is this:

$(".oneInput").blur(function(){
    // Tally Row
    var thisRow = $(this).closest('tr');
    var rowTotal = 0;
    thisRow.find('input.oneInput').each(function() {
        var n = parseFloat(this.value);
        if(!isNaN(n))
            rowTotal += n;
      });
     $(this).parent().parent().find( 'input.screenOneTotal').empty().val( rowTotal );

     // Tally Column
     var colName = $(this).attr('name');
     var col = colName.substr(0,3);
     var spanName = "input#tot"+col;
     var tot = parseInt($("input[name='"+col+"1']").val())+parseInt($("input[name='"+col+"2']").val())+parseInt($("input[name='"+col+"3']").val())+parseInt($("input[name='"+col+"4']").val())+parseInt($("input[name='"+col+"5']").val())+parseInt($("input[name='"+col+"6']").val())+parseInt($("input[name='"+col+"7']").val())+parseInt($("input[name='"+col+"8']").val())+parseInt($("input[name='"+col+"9']").val())+parseInt($("input[name='"+col+"10']").val())+parseInt($("input[name='"+col+"11']").val())+parseInt($("input[name='"+col+"12']").val());
     $(spanName).empty().val(tot);

     //GRAND TOTAL
     var gTotalOne = parseInt($("#totLIB").html())+parseInt($("#totRPI").html())+parseInt($("#totLMM").html());
     $("#scrOneTotal").empty().html(gTotalOne);
  }); // end inputOne blur

If needed I can supply the rest of the page code but it is in php and requires a database.

like image 755
jgravois Avatar asked Jun 26 '13 16:06

jgravois


2 Answers

Just add .blur() to the end of your blur function, it will invoke it on DOM ready:

$(".oneInput").blur(function(){
   //code code and more code
}).blur();

Demo: http://jsfiddle.net/Exw3f/

like image 177
tymeJV Avatar answered Nov 05 '22 01:11

tymeJV


Put your code into a separate function to call it on document.ready AND on the blur trigger.

Example

function calculateTotals() { ... }

$(document).ready(function() {
    $('.oneInput').each(calculateTotals);
}):

$('.oneInput').blur(calculateTotals);
like image 22
Patrick Avatar answered Nov 05 '22 02:11

Patrick