1

The property l.livreobj is undefined below. Why?

function livre() {
            i=i+1;
            var cd = document.getElementById("act").value.substr(0,3)+"-"+i;
            var isbn = document.getElementById("isbn").value;
            var act = document.getElementById("act").value;
            var titre = document.getElementById("titre").value;

            var livreobj ={
              Cd:cd,
              Isbn:isbn,
              Act:act,
              Titre:titre
           };

    }



        function add() {
          var l = new livre();
          alert("kjkj");
          ajoutertable(l.livreobj);
        }

HTML:

<body>
 code : <input type="text" id="cd" disabled/>

  isbn : <input type="text" id="isbn"/>

  Acteur : <input type="text" id="act"/>

  Titre : <input type="text" id="titre"/>

  <input type="button" id="ajt"  value="Ajouter" onclick="add();"/>

<table border  id = "myTable">
<tr>
    <td>
    Code</td>
    <td>
    ISBN</td>
    <td>
    Auteur</td>
    <td>
    Titre</td>
    <td>
    Action</td>
</tr>
</table>
Basilevs
  • 22,440
  • 15
  • 57
  • 102
  • what is your html structure? – Dekel Dec 06 '16 at 23:27
  • 1
    I don't do much of this type of logic, but I feel like it should be `this.livreobj = ...` instead of var – Taplar Dec 06 '16 at 23:28
  • @AyoubElHafi edit your question and put the markup in it, not as a comment. – Taplar Dec 06 '16 at 23:29
  • Not here. Add in your original question – Dekel Dec 06 '16 at 23:29
  • jsfiddle will really help – 1Mayur Dec 06 '16 at 23:34
  • 2
    That's not how constructors work. When a function is called with a `new` keyword an object is created from the function's prototype (which by default is a plain Object) and the `this` keyword inside the function points to the newly created object. Google around and read about how objects work in javascript first. – slebetman Dec 07 '16 at 01:37
  • 1
    You'll want to read [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/q/13418669/1048572) – Bergi Dec 07 '16 at 03:33
  • Possible duplicate of [Why is the variable declared inside the JS class \`undefined\`](http://stackoverflow.com/questions/28799363/why-is-the-variable-declared-inside-the-js-class-undefined) – Basilevs Dec 07 '16 at 03:55
  • @Bergi, thanks, this question is an exact duplicate of one of linked question there – Basilevs Dec 07 '16 at 03:56

2 Answers2

0

In your livre() constructor no object properties are initialized. Use "this" pseudo-variable to initialize constructed object field, replace var with this.:

     this.livreobj ={
          Cd:cd,
          Isbn:isbn,
          Act:act,
          Titre:titre
       };

See Operator new

Basilevs
  • 22,440
  • 15
  • 57
  • 102
-1

Initialize variable i to something. Right now it is null

    var i = 0;
Gregg
  • 615
  • 6
  • 6