0

Maybe you can help me with this:

I have a function that ads a div by a button click. Any div contains a checkbox and a text field. If the checkbox is checked the text field is green, if not, the text field is red.

I don't know how to assign a dynamic div name for the "procedure" div, as the counter, like id = procedure1, id=procedure2... and then access the background color as procedure1.style.backgroundColor...

Thank you!

var counter = 1;

function addInput(divName) {
    var newdiv = document.createElement('div');
    newdiv.innerHTML = "<input type='checkbox' id='check' onclick='if(this.checked){procedure.style.backgroundColor=`green`;}
          else {procedure.style.backgroundColor=`red`;}'><input type='text' id='procedure'>";
    document.getElementById(divName).appendChild(newdiv);
    counter++;
}
user2226755
  • 12,494
  • 5
  • 50
  • 73
chitoiu daniel
  • 107
  • 2
  • 13

3 Answers3

3

You shouldn't be using IDs for this at all. Traverse the DOM instead to find the corresponding <input>. In your specific case, the next sibling of the checkbox is the element you want to manipulate:

onclick='this.nextSibling.style.backgroundColor = this.checked ? "green" : "red";'

I also suggest to learn about other ways of binding event handlers, because inline event handlers have many disadvantages and using innerHTML like this makes your code more difficult to maintain.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

If you make the elements with document.createElement rather than with a string, then you can use setAttribute.

var dynamicId = 'someId';
element.setAttribute('id', dynamicId);

So for your example

var input = document.createElement('input');
input.setAttribute('type', 'checkbox');
input.setAttribute('id', 'check');
input.addEventListener('click', function() {
  if(this.checked) {
    // ...
  }
});

However, you might have noticed that using this approach you don't even need to use IDs. You can simply keep a reference to the elements you created with some variables.

var procedure1 = document.createElement('input');
var procedure2 = document.createElement('input');

procedure1.addEventListener('click', function() {
  // do something with procedure2
  procedure2.style.backgroundColor = 'red';
});
Dan Prince
  • 29,491
  • 13
  • 89
  • 120
0

you can use jquery to do this

to set: $('#myObj').attr('id','NEWID');

or $('#myObj').prop('id','NEWID');

to get : $('#myObj').attr('id');

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
RBoschini
  • 496
  • 5
  • 16
  • 1
    From the JavaScript tag description: *"Unless a tag for a framework/library is also included, a pure JavaScript answer is expected."* – Felix Kling Nov 09 '15 at 17:04