1

So I'm trying to create a function which changes the 0 slot of an array to an input value. However I want this function to only be able to run once. How do I do this, any help is greatly appreciated thanks.

function submitForm() {
    $('#inputForm').submit;
         if ($("#inputValue").val() != inputException) {
              charSetName();
              $("#inputValue").val("");
         }
         $("#inputValue").val("");
     }
function charSetName() {
    var nameSet = false;
    if (nameSet == false) {
        nameSet = true;
        charDetails[0] = $("#inputValue").val();
        document.getElementById("name").innerHTML = "<li id='name''>Name: " + charDetails[0] + "</li>";
    }
}

4 Answers 4

2

This is an old question but I was brought here because I needed something similar. To anyone who comes next time, here was what I eventually did:
I simply declared a variable with an initial count of 0. Then every time my function runs, it auto increases. The code I want to run once just checks if the count is 1, then it runs. If not, it doesnt. Like this:

let count = 0;
count === 1 ? doSomething : doNothing
count++

Does it help?

Sign up to request clarification or add additional context in comments.

2 Comments

Wale, thank you for eventually dropping this code, I'm having a similar problem and your code helped. Thumbs Up
^^ Cheers Wale!
1

Try this, I have defined isFunctionCalled:Boolean variable for handle it.

var isFunctionCalled = false;

function submitForm() {
  $('#inputForm').submit;
  if ($("#inputValue").val() != inputException) {

    if (!isFunctionCalled) {
      charSetName();
    }

    $("#inputValue").val("");
  }
  $("#inputValue").val("");
}

function charSetName() {
  var nameSet = false;
  if (nameSet == false) {
    nameSet = true;
    charDetails[0] = $("#inputValue").val();
    document.getElementById("name").innerHTML = "<li id='name''>Name: " + charDetails[0] + "</li>";
  }

  isFunctionCalled = true;
}

Comments

1

Mind the executed variable:

var something = (function() {
    var executed = false;
    return function () {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

Comments

0

There are a lot of ways to do this.

Just a simple way is to set a flag value.

if(flag){
//your code here...
flag = !flag;
}

SO, if the value of the flag is 1 at first it will work. Then as the flag value is changed to 0, then the next time it is called, it will not be invoked, as flag is 0.

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.