buck1112
buck1112

Reputation: 502

Calling function from anonymous function in JQuery returns undefined

I'm working with this script which needs to call the external function, but the value returned in the log shows 'undefined'.
I have a checkbox that calls the external function successfully, but the anonymous jQuery function is not successful. Could this be a scope issue of some sort?

Thanks for any help.

css:

div.row {
    border: 1px solid blue;
    width: 100px;
}
div.child {
    border: 1px solid red;
    display: inline-block;
}

javascript:

function padZeros(ksa) {
    getDigits(ksa);
    //alert(s); 
    //document.getElementById("ksa_padded").value=s
}

function getDigits(MyDigits) {
    var ksa = MyDigits;
    var re4Digit = /^([0-9])([0-9]?)([k|s|a])([0-9])([0-9]?)([A-z]?)$/;
    var first2Digits = ksa.replace(re4Digit, "$1$2");
    //alert(first2Digits);
    //return first2Digits;
    pad(first2Digits, '2');
}

function pad(num, size) {
    //var s = num+"";
    //alert(num);
    s = num + "";
    //alert(s);
    while (s.length < size) s = "0" + s;
    return s;
    //alert(s);

}

$("#add").click(function () {
    var inserted = false;
    var newText = $("#addText").val();
    var $newItem = $("<div class='child'>" + newText + "</div>");
    $(".row:first .child").each(function () {
        //alert($(this).text());
        xx = $(this).text();
        var compare_a = padZeros(xx);
        //alert(compare_a);
        console.log(xx);

        if ($(this).text() > newText) {
            $newItem.insertBefore($(this));
            inserted = true;
            return false;
        }
    });
    if (inserted == false) {
        $newItem.appendTo(".row:first");
    }
});

html

 <div class="row">
     <div class="child">3K1</div>
     <div class="child">3K3</div>
     <div class="child">3K4</div>
     <div class="child">1K1</div>
     <div class="child">1K2</div>
 </div>
 <div class="row">
     <div class="child">IS2</div>
     <div class="child">IS4</div>
 </div>
 <div class="row">
     <div class="child">IA2</div>
     <div class="child">IA4</div>
 </div>
 <br/>
 <input id="addText" type="text" />
 <input id="add" type="button" value="Insert Element" />
 <br>

 <input type="checkbox" onClick="padZeros('1k10s')">
 <input type="text" id="ksa_padded">

Upvotes: 0

Views: 740

Answers (1)

Abraham Hamidi
Abraham Hamidi

Reputation: 13789

Try

return getDigits(ksa);
return pad(first2Digits,'2');

You have to return things, otherwise they'll come out as undefined.

Upvotes: 0

Related Questions