Build a function that trigger on focusin / focusout

68 views Asked by At

I'm trying to build a function that will trigger on focusin / focusout and show the result in a <span> when I entering data in the inputs fields.

My doc-ready function is in the <head> and the code below is call in a script tag after the <body>.

Here's a screenshot: This is the input fields and the span that shows the result

Code:

var $costPrice = parseInt($("#cost-price").val()); // Cost price <div>
var $markupPercentage = parseInt($("#markup-percentage").val()); // Markup <div>

var $sellingPrice = ($markupPercentage / 100) * $costPrice + $costPrice;

var $finalPrice = $("#final-price"); // This <span> tag that receive the result of $sellingPrice

function showPrice($sellingPrice, $finalPrice){
    if ($sellingPrice !== null) {
        $finalPrice.html("$" + $sellingPrice);
    } else {
        $finalPrice.html("$0"); // Here I want to replace Nan by $0
    }
};

$costPrice.focusout(showPrice); // I want to trigger/show the result.
$markupPercentage.focusout(showPrice); // I want to trigger/show the result.

If I enter a value in the inputs and run this code below in the console, it works. But that's not interactive. I'd like to get the same result but on focusin / focusout input fields.

var $costPrice = parseInt($("#cost-price").val()); // Cost price <div>
var $markupPercentage = parseInt($("#markup-percentage").val()); // Markup <div>

var $sellingPrice = ($markupPercentage / 100) * $costPrice + $costPrice;

var $finalPrice = $("#final-price").html("$" + $sellingPrice);

Thanks for help !

3

There are 3 answers

0
LucR On

Wouldn't active and blur work? Active would be when someone ckicks on the inputs, and blur when someone "unselections" it

0
Tí Sún On

you should try:

$("#cost-price").focusout(function(){
//do something
});

$("#final-price").focusout(function(){
//do something
});
0
Dave On

Finally, I found the solution by myself.

Variables, scope and the way I built the function sellingPrice were the main problems.

Then I use the .on() method instead of .focusout() or .focusin() methods to output the result as I typing data in the input fields.

Code:

var $costPrice;
var $markupPercentage;
var $sellingPrice;

function sellingPrice($costPrice, $markupPercentage, $sellingPrice) {
    
  $costPrice = parseInt($("#cost-price").val() || 0);
  $markupPercentage = parseInt($("#markup-percentage").val() || 0);

  $sellingPrice = ($markupPercentage / 100) * $costPrice + $costPrice;

  $("#final-price").html("$" + $sellingPrice || 0);
}

$("#cost-price").on('input', sellingPrice);
$("#markup-percentage").on('input', sellingPrice);

Thanks!