0

as the title says I am attempting to have my setAnswer() function return true when a button with the class .btnAnswer is clicked, otherwise return false. Then I am passing the value returned to the showHideAnswer() function and using that value for logic. It seems fairly easy and I am not sure where I am going wrong.. I code alot in .NET and am still pretty new to working with Javascript functions. I am sure that it is something easy!

//On partial page load    
function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        showHideAnswers(setAnswer());
        alert(setAnswer());
    }
}

//Set answer
function setAnswer() {
    $("input.btnAnswer[type=submit]").click(function (event) {
        //do stuff and return true if clicked
        return true;
    });
}

//Show hide stuff
function showHideAnswers(flag) {
if(flag){

//do stuff

}

}

Thanks in advance!

P.S. My alert in the page load always shows undefined.

1
  • When you call setAnswer, you only assign the click event handler. The handler itself is only executed after the users clicked the element, which is at an arbitrary time after setAnswer was called. If you have to react to the click event somehow, then you have to put all the logic inside the click event handler. Commented Aug 30, 2013 at 0:03

2 Answers 2

1

Your function setAnswer() does not return anything. The jQuery .click() is an event listener, meaning it is not something you call. Once set, it is called when the element is clicked.

Simple working example would be, to set a global flag variable, and to have the .click() listener to change it whenever clicked:

var flag=false;
$( "#buttonID" ).click(function() {
  flag=true;
});

//On partial page load    
function pageLoad(sender, args) {
  if (args.get_isPartialLoad()) {
    showHideAnswers();
    alert(flag);
  }
}

//Show hide stuff
function showHideAnswers() {
  if(flag){
    //do stuff. flag is global, no need to define in function or pass to it
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You don't get the return value since it is out of scope you can simply call the function when the event fires. iff all you check is if the button was clicked you can be certain the function will only fire on click:

function setAnswer() {
    $("input.btnAnswer[type=submit]").click(function (event) {
        //do stuff and return true if clicked
        showHideAnswers(true)
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.