0

My issue is simple, and I have an idea of why it might not work but I could use some advice or alternative options.

Essentially, what I am trying to achieve is having the same button be responsive for the save, and once saved is clicked and processed correctly, then I want the id to change to next and perform an on-click event once the button is clicked again with the new id. The id change part below is in a functioning if statement so that is not the issue, I left it out so it was more readable.

document.getElementById("save").id = "next";

I tried showing and hiding two separate buttons, but I would like the buttons to be in the exact same place.

document.getElementById("save").id = "next";

$('#next').on('click', function () {

     // My code here

}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • And what would you expect here? You put a click handler on a button then essentially removed it, Use two buttons, hide one then swap the display/visibility. Position has nothing to do with having two buttons. – Mark Schultheiss Jul 16 '20 at 19:03
  • I did that previously, the buttons show up in different spots on the page. I was just looking for a simple solution to having the buttons in the same exact place. – Courtney Erickson Jul 16 '20 at 19:06
  • You have to use event delegation if you're changing IDs dynamically, just like when you're creating elements dynamically. – Barmar Jul 16 '20 at 19:08
  • Works fine for me: https://jsfiddle.net/w7poen45/ – devlin carnate Jul 16 '20 at 19:10
  • Changing IDs dynamically is bad design. Why don't you just set a global variable that the click handler checks? – Barmar Jul 16 '20 at 19:10
  • @devlincarnate - yea because your fiddle attaches the click handler after you make a new button id. – Mark Schultheiss Jul 16 '20 at 19:11
  • As mentioned above, changing an element id is bad design. Another alternative is to uses classes -- add and remove a class – devlin carnate Jul 16 '20 at 19:11
  • @MarkSchultheiss - ok, so the solution is to attach the click handler after changing the Id – devlin carnate Jul 16 '20 at 19:13
  • No the solution is to have two buttons and show/hide them when the first is clicked OR just have one and change the text only - depending upon use etc. you could also use a `data` property to hold the "state of things" to make it a single button – Mark Schultheiss Jul 16 '20 at 19:14
  • @MarkSchultheiss - I guess that depends on what your definition of solution is. Something that works vs something that is designed well. Switching classes is another solution. – devlin carnate Jul 16 '20 at 19:16
  • https://stackoverflow.com/q/27041673/125981 – Mark Schultheiss Jul 16 '20 at 19:18

1 Answers1

-1

Try using this $('#save').attr('id', 'next');.

If that doesn’t work, maybe assign a class instead. Like:

$("#save").attr("class","next");

$('.next').on('click', function () {

     // My code here

});