Search code examples
javascriptfunctioncallbackreturn

how to create and then use your own function inside another javascript


 var cityToCheck = document.getElementById("text").value;

 var btn = document.querySelector("button");
 btn.addEventListener('click', add);



 function makeCapital(str) {

var firstChar= str.slice(0,1); 
var otherChars = str.slice(1);
firstChar = firstChar.toUpperCase(); 
otherChars = otherChars.toLowerCase(); 
var cappedString = firstChar + otherChars; 
 return cappedString;
}

function add() { 

cityToCheck = makeCapital(cityToCheck);
console.log(cityToCheck);


}

Im struggling to understnad the concept of creating a function and then using it somewhere else in the program, cna someone tell me what is wrong with my code and why I am getting an empty string and not a capitalised value of what was in the text box i typed in? im clearly mis understanding the whole concept despite my hours of trying to get this to work

thanks all


Solution

  • instead call the value when you define the variable cityToCheck just call the value inside the add() function block (when the event of the button is triggered). Its working.

    var cityToCheck = document.getElementById("text");
    var btn = document.querySelector("button");
    btn.addEventListener('click', add);
    
    function makeCapital(str) {
        var firstChar = str.slice(0,1); 
        var otherChars = str.slice(1);
        firstChar = firstChar.toUpperCase(); 
        otherChars = otherChars.toLowerCase(); 
        var cappedString = firstChar + otherChars; 
        console.log(cappedString);
        return cappedString;
    }
    
    function add() { 
    cityToCheck = makeCapital(cityToCheck.value);
    }