js generated input button not working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bning
    New Member
    • Aug 2007
    • 8

    js generated input button not working

    Hmm this forum really doesn't give you long enough to type in your question before logging you out.. well here goes my second attempt:

    I'm trying to teach myself javascript with dom scripting and am attempting to write an application as I learn. It's been going fine but I've ran into a problem which is driving me crazy.

    I'll start off by explaining what I'm trying to achieve... I'm simply trying to insert an input button into a table at a specific place which calls a function when clicked. For examples sake I'm trying to place it into row 3, column 4 of the table.

    So I started off by creating an button that called the javascript to insert that button. This works fine. In the script I first define the new element like so :

    [CODE=javascript]var newDelete = document.create Element('input' );
    newDelete.setAt tribute('type', 'button');
    newDelete.setAt tribute('value' , 'delete');
    newDelete.setAt tribute('onclic k', 'test();');[/CODE]

    I then insert it into the correct place in the table :

    [CODE=javascript]document.getEle mentsByTagName( 'table')[0].firstChild.chi ldNodes[2].childNodes[3].appendChild(ne wDelete);[/CODE]

    I realise there are probably better ways to find the correct 'td' in the table but I'm a newbie.

    At first it appears to run fine... I click the static button, and the new button appears in the table at the correct position. You can even click the button!!! However, clicking the button does not call the test() function as expected. Looking at the generated html the button looks ok :

    [CODE=html]<INPUT onclick=test(); type=button value=delete>[/CODE]

    To test whether it was a problem with the html generated I copied the button html into a separate html page and opened it. The button appeared... clicking it called the test() function!

    So even though these two buttons are effectively the same... clicking the dynamically generated button does not call the test() function... while clicking the static one does...

    Any help would be greatly appreciated!

    Ben.
    Last edited by pbmods; Oct 4 '07, 10:41 PM. Reason: Changed [CODE] to [CODE=javascript].
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    hi ...

    try to not use the setAttribute-method for it ... use something like that:

    [CODE=javascript]var click_handler = function(this) {
    alert(this.node Name);
    };

    newDelete.oncli ck = click_handler;[/CODE]
    kind regards

    Comment

    • mrhoo
      Contributor
      • Jun 2006
      • 428

      #3
      You were pretty close.

      [CODE=javascript]var B= document.create Element('input' )
      B.type= 'button';
      B.value= 'Delete';
      B.onclick= test; // reference the function, don't call() it here[/CODE].


      Finding a particular cell in a table is a common and tiresome task, you might want a function just for that.
      [CODE=javascript]function getCell(t,r,c){
      t= document.getEle mentsByTagName( 'table')[t-1];
      r= t.getElementsBy TagName('tr')[r-1];
      var tem,i= 0;
      while(r.childNo des[i] && c>0){
      tem= r.childNodes[i];
      if(/^(td|th)$/i.test(tem.node Name)){
      if(--c== 0) return tem;
      }
      ++i;
      }
      return null;
      }[/CODE]
      To add the button defined above to the first table, third row, fourth cell:

      getCell(1,3,4). appendChild(B);

      Comment

      • dmjpro
        Top Contributor
        • Jan 2007
        • 2476

        #4
        Originally posted by bning
        Hmm this forum really doesn't give you long enough to type in your question before logging you out.. well here goes my second attempt:

        I'm trying to teach myself javascript with dom scripting and am attempting to write an application as I learn. It's been going fine but I've ran into a problem which is driving me crazy.

        I'll start off by explaining what I'm trying to achieve... I'm simply trying to insert an input button into a table at a specific place which calls a function when clicked. For examples sake I'm trying to place it into row 3, column 4 of the table.

        So I started off by creating an button that called the javascript to insert that button. This works fine. In the script I first define the new element like so :

        [CODE=javascript]var newDelete = document.create Element('input' );
        newDelete.setAt tribute('type', 'button');
        newDelete.setAt tribute('value' , 'delete');
        newDelete.setAt tribute('onclic k', 'test();');[/CODE]

        I then insert it into the correct place in the table :

        [CODE=javascript]document.getEle mentsByTagName( 'table')[0].firstChild.chi ldNodes[2].childNodes[3].appendChild(ne wDelete);[/CODE]

        I realise there are probably better ways to find the correct 'td' in the table but I'm a newbie.

        At first it appears to run fine... I click the static button, and the new button appears in the table at the correct position. You can even click the button!!! However, clicking the button does not call the test() function as expected. Looking at the generated html the button looks ok :

        [CODE=html]<INPUT onclick=test(); type=button value=delete>[/CODE]

        To test whether it was a problem with the html generated I copied the button html into a separate html page and opened it. The button appeared... clicking it called the test() function!

        So even though these two buttons are effectively the same... clicking the dynamically generated button does not call the test() function... while clicking the static one does...

        Any help would be greatly appreciated!

        Ben.

        Have a look at this ...............
        [code=html]
        <td id = "some_id"></td>
        [/code]

        [code=javascript]
        function addChild()
        {
        var ref = document.create Element("input" );
        ref.setAttribut e("type","text" );
        .
        .
        typeof window.attachEv entListener ? ref.attachEvent Listener("click ",test,true ) : ref.addEventLis tener("onclick" ,test);
        document.getEle mentById('some_ id').appendChil d(ref);
        }
        function test()
        {
        //some code
        }
        [/code]

        Debasis Jana

        Comment

        • ajos
          Contributor
          • Aug 2007
          • 283

          #5
          Originally posted by bning

          [CODE=html]<INPUT onclick=test(); type=button value=delete>[/CODE]

          Ben.
          hey ben,
          i doubt the way you ve declared the above line,though im not sure abt wat you are doing with this, i think you shud do something like this-->
          Code:
          <INPUT type="button" value="delete" onclick=[B]"test()"[/B]>
          just give it a try:)
          regards,
          ajos

          Comment

          • bning
            New Member
            • Aug 2007
            • 8

            #6
            Thanks for all your quick replies! Eliminating the setAttributes and referencing the function rather than calling it (thanks mrhoo!) made the button work finally. And that cell finding function will no doubt save me a LOT of time.

            Thanks again everyone!

            Comment

            • bning
              New Member
              • Aug 2007
              • 8

              #7
              Hmmm another problem hehe...

              this example required no values be be passed to the test function ... however the actual application needs the name of the input button to be passed to the test function... now as adding (this.name) to the onclick attribute causes loss of function to the button... how might I achieve this?

              Ben.

              Comment

              • dmjpro
                Top Contributor
                • Jan 2007
                • 2476

                #8
                Originally posted by bning
                Hmmm another problem hehe...

                this example required no values be be passed to the test function ... however the actual application needs the name of the input button to be passed to the test function... now as adding (this.name) to the onclick attribute causes loss of function to the button... how might I achieve this?

                Ben.
                Post your Code and tell what you are not achieving.

                Debasis Jana

                Comment

                • bning
                  New Member
                  • Aug 2007
                  • 8

                  #9
                  The real application lets you enter values into a form then click a button which then adds a row to a table containing these values. A button is the added to the end of the row which when clicked deletes this row. Now when I create the row I will assign the postion of the row in the table as its name attribute, and ideally when this delete button is clicked it will pass its name to a function so the function knows which row to delete.

                  Code:
                  var newDelete = document.createElement('input');
                  newDelete.type = 'button';	
                  newDelete.name = 'row2';
                  newDelete.value = 'delete';
                  newDelete.onclick = test;
                  document.getElementsByTagName('table')[0].firstChild.childNodes[emptyRowNum].childNodes[5].appendChild(newDelete);
                  The above code creates the delete button. As discussed above the dynamically created button will not call the test function if the onclick attribute is assigned as 'test()' but will work when its assigned as 'test'. However, this will not allow me to pass the name of the input button to the test function by using 'test(this.name )'.

                  Any help would be greatly appreciated .

                  Ben.

                  Comment

                  • dmjpro
                    Top Contributor
                    • Jan 2007
                    • 2476

                    #10
                    Originally posted by bning
                    The real application lets you enter values into a form then click a button which then adds a row to a table containing these values. A button is the added to the end of the row which when clicked deletes this row. Now when I create the row I will assign the postion of the row in the table as its name attribute, and ideally when this delete button is clicked it will pass its name to a function so the function knows which row to delete.

                    Code:
                    var newDelete = document.createElement('input');
                    newDelete.type = 'button';	
                    newDelete.name = 'row2';
                    newDelete.value = 'delete';
                    newDelete.onclick = test;
                    document.getElementsByTagName('table')[0].firstChild.childNodes[emptyRowNum].childNodes[5].appendChild(newDelete);
                    The above code creates the delete button. As discussed above the dynamically created button will not call the test function if the onclick attribute is assigned as 'test()' but will work when its assigned as 'test'. However, this will not allow me to pass the name of the input button to the test function by using 'test(this.name )'.

                    Any help would be greatly appreciated .

                    Ben.
                    Is that necessary to pass that?

                    [code=javascript]
                    .
                    .
                    button_ref.setA ttribute("id"," some_id");
                    .
                    .
                    function test()
                    {
                    alert(document. getElementById( "some_id").getA ttribute("name" ));
                    }
                    [/code]

                    Debasis Jana

                    Comment

                    • bning
                      New Member
                      • Aug 2007
                      • 8

                      #11
                      There would be one delete button for each row in the table. Clicking the button on a row should delete that row and no others. Even assigning a unqiue id to each button would not allow the test function to know which button had called it unless I could pass it a variable? Although I'm probably missing something.

                      Comment

                      • gits
                        Recognized Expert Moderator Expert
                        • May 2007
                        • 5388

                        #12
                        hi ...

                        you may use the event-obj for this ... here i show you the standards-compliant method:

                        [HTML]
                        <script type="text/javascript">
                        function add_click() {
                        var newDelete = document.getEle mentById('test' );

                        var click_handler = function(e) {
                        var obj = e.target;

                        alert(obj.name) ;
                        };

                        newDelete.oncli ck = click_handler;
                        }
                        </script>

                        <body onload="add_cli ck();">
                        <input type="button" id="test" name="test_butt on" value="click_me "/>
                        </body>
                        [/HTML]

                        note: IE has no e.target but srcElement ... so it has to be adapted for cross-browser-capabilities

                        kind regards

                        Comment

                        • dmjpro
                          Top Contributor
                          • Jan 2007
                          • 2476

                          #13
                          Originally posted by bning
                          There would be one delete button for each row in the table. Clicking the button on a row should delete that row and no others. Even assigning a unqiue id to each button would not allow the test function to know which button had called it unless I could pass it a variable? Although I'm probably missing something.
                          Sorry you can do it another way ........ :-)
                          Without having my code, i said earlier.
                          Actually it is possible in IE....I tested that in Mozilla i failed.

                          [code=javascript]
                          function test()
                          {
                          alert(event.src Element.name);
                          }
                          [/code]

                          Debasis Jana

                          Comment

                          • gits
                            Recognized Expert Moderator Expert
                            • May 2007
                            • 5388

                            #14
                            :) now ... simply combine the last two posts :))

                            kind regards

                            Comment

                            • dmjpro
                              Top Contributor
                              • Jan 2007
                              • 2476

                              #15
                              Originally posted by gits
                              hi ...

                              you may use the event-obj for this ... here i show you the standards-compliant method:

                              [HTML]
                              <script type="text/javascript">
                              function add_click() {
                              var newDelete = document.getEle mentById('test' );

                              var click_handler = function(e) {
                              var obj = e.target;

                              alert(obj.name) ;
                              };

                              newDelete.oncli ck = click_handler;
                              }
                              </script>

                              <body onload="add_cli ck();">
                              <input type="button" id="test" name="test_butt on" value="click_me "/>
                              </body>
                              [/HTML]

                              note: IE has no e.target but srcElement ... so it has to be adapted for cross-browser-capabilities

                              kind regards
                              Does browser send the event object when an event fired up :-)

                              Debasis Jana

                              Comment

                              Working...