0

I'm looking to find a more efficient way to build buttons and assign actions to them. The site I'm working with is written entirely in javascript. I tried to implement this:

var test = $('<button/>', {
    text: i, //set text 1 to 10
    id: 'btn_'+i,
    click: function () { alert('hi'); }
});

but I get an error "Uncaught Error: NotFoundError: DOM Exception 8". Does anyone have a terse solution to creating buttons with actions assigned in Javascript? Any help is greatly appreciated.

Thanks!

1
  • Check this jsfiddle.net/QY7HD. You code works fine.. Which version of jquery you are using? Commented May 2, 2013 at 5:51

4 Answers 4

1

Try this:

for(i=1;i<=10;i++)
{
    var test = $('<button/>', {
        text: i, //set text 1 to 10
        id: 'btn_'+i,
        click: function () { alert('hi'); }
    });
    $('body').append(test);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is a "terse solution", Try this, $('<button/>').click( function(){}).attr('text',i).attr('id','btn_'+i).appendTo('body') (Pls fill in the loop and other stuff :)

Comments

0

"Uncaught Error: NotFoundError: DOM Exception 8"

error because you haven't set i in you code..so it is undefined...

 var test = $('<button/>', {
   text: i, //set text 1 to 10 //<----here
   id: 'btn_'+i,
   click: function () { alert('hi'); }
 });

if you need i to be values of 1 - 10 then you can use loop

$(document).ready(function(){
for(i=1;i<=10;i++)
{
   var test = $('<button/>', {
     text: i, //set text 1 to 10 //<----here
     id: 'btn_'+i,
     click: function () { alert('hi'); }
   });
}
});

1 Comment

grrr... I pasted the wrong code, if I replace i with with a string value the same error is produced. Thanks for the suggestion, I will be testing here in a minute
0

Try below code

var i=0;
$(function () {
    var test = $('<button/>', {
        text: i,
        class:'btn',
        id: 'btn_' + i        
    });
    i++;
    var test1 = $('<button/>', {
        text: i, 
        class:'btn',
        id: 'btn_' + i        
    });

    $(document).on('click','.btn',function(){
        alert($(this).attr('id'));
    });

    $('#mydiv').append(test);
    $('#mydiv').append(test1);
});

Check working sample on jsFiddle http://jsfiddle.net/vijaypatel/QgdsC/

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.