Leon van der Veen
Leon van der Veen

Reputation: 1672

jQuery call function on input change by event

I've got a page which loads an external js and on the page I've got a function called calculate_totals(). What I want is to call the function calculate_totals() from a function in the external js.

This is a piece of JavaScript which loads in an external js

function selectItemMouse(thisVar)
{   
    var searchValue = thisVar.attr('data-name');
    thisVar.parent().parent().parent().parent().children('.list').val(searchValue);
    
    
    //alert(thisVar.parent().parent().parent().parent().next().find('input').focus());
    
    thisVar.children().children().each(function()
    {
        var dataId = $(this).attr('data-id');
        var value = $(this).attr('data-name');
        
        //This change the input of my form
        $(thisVar).parent().parent().parent().parent().children().children('.'+dataId).val(value);
    });
    
    $('.customerResults').hide();
    calculate_totals();     
}

Upvotes: 0

Views: 12993

Answers (2)

Viktor S.
Viktor S.

Reputation: 12815

Based on commenting session: calculate_totals is defined inside of $(document).ready(function(){});

Because of that is not seen outside it. Basically, it is visible inside $(document).ready(function(){}); only. Just move it outside it. Now it will became global and visible anywhere.

Instead of

$(document).ready(function(){
   function calculate_totals() {} // this function is visible inside of a ready function only
  ///..... other code here
});

use:

function calculate_totals() {} // now it is a part of global context
$(document).ready(function(){
  ///..... other code here   
});

After that you should have it available inside selectItemMouse and any other place.

Besides, I would think on updating your code.

thisVar.parent().parent().parent().parent().children('.list').val(searchValue);

usage of such chains is not flexible. Just you will wrap thisVar element with some other element - you will need to update your JS code.

Take a look at .parents or .closest. For instance, you may change a line above like this:

thisVar.closest(".class_common_parent").children('.list').val(searchValue);

Where .class_common_parent is a class of an element which you take using parent().parent().parent().parent().

Upvotes: 1

chrisbradbury
chrisbradbury

Reputation: 327

You can put a listener for a change on the input:

$(document).ready(function(){
    $('#input').change(function(){
        alert("alert here");
    });
});

Upvotes: 1

Related Questions