user3204820
user3204820

Reputation: 349

How to assign multiple Id's to the same button

I am looking to have a button which does two specific things depending on what the value of a variable is, however in order for my code to work I need to have multiple buttons rather than only creating and using one for the same purpose. For example:

function createCloseButton(){
    var close = document.createElement("input");
    close.type = "button";
    close.setAttribute("class", "btn btn-primary");
    close.setAttribute("value", "Close");
    close.setAttribute("id", "close");
    close.setAttribute("onclick"," hideFields(); createPicker();")
    if (change == "set"){
    close.setAttribute("data-dismiss", "modal");
    }
    else if (change == "search"){
        close.onclick = function(){
            hideFields();
        }
    }
    return (close);
}

This function when it is called creates and returns a close button. Is there a way to assign the button a different id each time it is called so that they can be differentiated? Or do I need to create 9 separate buttons?

Thanks

Upvotes: 0

Views: 1737

Answers (1)

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

Yes you can do this using global counter variable

var idCounter=0; //declare variable here
function createCloseButton(){
  idCounter++; //every time this counter get incremented 
  ....
  close.setAttribute("id", "close"+idCounter);
  ...
}

Upvotes: 1

Related Questions