J.Doe
J.Doe

Reputation: 3

How to use javascript function in just fixed numbers of time?

<img src='plus.jpg' width='80' height='80' onclick="myFunction2()">

return

function myFunction2() {
        var x = document.createElement("INPUT");
        x.setAttribute("name", "image[]");
        x.setAttribute("type", "file");
        document.getElementById("add").appendChild(x);
}

I would like to use myFunction2() just 4 times. After that, I want to stop this function. Can you give me any suggestion? Thanks in advance.

Upvotes: 0

Views: 52

Answers (3)

Darshan
Darshan

Reputation: 1074

solution using jQuery.

var timesClicked = 0;
$( "#imgId" ).bind( "click", function( event ) {

  // do your operations here

  timesClicked++;
  if ( timesClicked >= 4 ) {
    $( this ).unbind( event );
  }
});

Upvotes: 1

Theo Itzaris
Theo Itzaris

Reputation: 4671

why dont you use a counter to check when the clicks reach 4, like this

HTML:

<img src='plus.jpg' width='80' height='80' onclick="myFunction2()">

INTO JS

    var myCounter=0;  
    function myFunction2() {
if(myCounter <4){myCounter++;
            var x = document.createElement("INPUT");
            x.setAttribute("name", "image[]");
            x.setAttribute("type", "file");
            document.getElementById("add").appendChild(x);
}
    }

Upvotes: 0

Mohammaed Abed
Mohammaed Abed

Reputation: 26

Try this :

var limit = 1;
function myFunction2() {
  if(limit <= 4){
   var x = document.createElement("INPUT");
   x.setAttribute("name", "image[]");
   x.setAttribute("type", "file");
   document.getElementById("add").appendChild(x);
   limit += 1;
  }else{
   alert("Stop");
  }
}

Upvotes: 1

Related Questions