totoaussi
totoaussi

Reputation: 741

Javascript : onclick="class method" => possible?

I have a class who has a method generating 100 input text.

And I want to add another method (to set a instance property for example) in these input text.

Here the code below :

<div id="container"></div>

<script type="text/javascript">

container = document.getElementById("container");

//Class :
function Foo(age)
{
    //Attribute :
    this.age = age;

    //Setter :
    this.setAge = function(age)
    {
        this.age = age;

        console.log(this.age);
    };

    this.displayInputText = function()
    {
        for(var i = 0; i < 100; i++)
        {container.innerHTML += '<input type="text" onkeyup="'+this.setAge(value)+';">';}
    };
}

foo1 = new Foo(32);
foo1.displayInputText();

</script>

But onkeyup="'+this.setAge(value)+'" generates javascript error in console, so it doesn't work.

Have you an idea ?

Thank you, cordially.

Upvotes: 0

Views: 1047

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

this.setAge returns undefined, so your line translates to

{container.innerHTML += '<input type="text" onkeyup="undefined">';}

If you want to use whatever value given in this input box to be set as setAge then you need to use addEventListener.

  var self = this;
  for (var i = 0; i < 10; i++) 
  {
    var inputEl = document.createElement( "input" );
    inputEl.addEventListener("keyup", function(){
        self.setAge( this.value );
    });
    container.append( inputEl );
  }

Demo

<div id="container"></div>

<script type="text/javascript">
  container = document.getElementById("container");

  //Class :
  function Foo(age) {
    //Attribute :
    this.age = age;

    //Setter :
    this.setAge = function(age) {
      this.age = age;

      console.log(this.age);
    };

    this.displayInputText = function() {
      var self = this;
      for (var i = 0; i < 10; i++) 
      {
        var inputEl = document.createElement( "input" );
        inputEl.addEventListener("keyup", function(){
            self.setAge( this.value );
        });
        container.append( inputEl );
      }
    };
  }

  foo1 = new Foo(32);
  foo1.displayInputText();
</script>

Upvotes: 2

Related Questions