0

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

6
  • It is invalid HMTL to have the same id twice in a single document Commented Jul 20, 2016 at 13:12
  • You can not define mutliple ids for the same element Commented Jul 20, 2016 at 13:12
  • Use different classes to your element Commented Jul 20, 2016 at 13:13
  • Just don't give it an id?! Commented Jul 20, 2016 at 13:13
  • I need to get the element though and am using document.getElementById. So would there be a way to say assign the ID of the element to button, and then the next time the function was called the ID would be button2 Commented Jul 20, 2016 at 13:14

1 Answer 1

1

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);
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I was looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.