vbnewbie
vbnewbie

Reputation: 226

How to create a button with function parameter?

I want to create a button by using function below, example createGetInfo(120,Test,1) I want the result become a 'Test' button with 120 width but the function below fail, How can I put the parameter inside the button tag?

function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:size'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};

Upvotes: 0

Views: 68

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176956

for binding event with dynamically created element you need to use on method of jquery, so your code will be as below

$( document ).ready(function() {
  var size=100;
    var GetInfo = $("<button class='eqGroupBtn' id='btnGetInfo' type='button' class='btn' style='width:"+size+"px;'>wording</button>");
    $("body").append(GetInfo);

     $( "#btnGetInfo" ).on( "click", function() {
              alert( $( this ).text() );
     });  
}); 

Working jsfiddle demo : https://jsfiddle.net/pranayamr/uuvtx5ga/

  • read more about on function here : http://api.jquery.com/on/
  • one more change in you code is always create element in html DOM with ID attribute , so i added Id for button which is btnGetInfo

Upvotes: 1

Lalit Sachdeva
Lalit Sachdeva

Reputation: 6639

function createGetInfo(size,wording,filter) {
    var GetInfo = $("<button class='eqGroupBtn' type='button' class='btn' style='width:'+size + 'px'>wording</button>");
    secondLevelMenuDiv.append(GetInfo);
    GetInfo.click(function(){
        Do something...
    });
};

'width:'+size + 'px'

Define it like the above

Upvotes: 0

Related Questions