简体   繁体   中英

Build a function that trigger on focusin / focusout

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 !

you should try:

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

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM