user2581649 user2581649 -4 years ago 112
HTML Question

Change HTML tag with Javascript

I asking the user to select given emails, and getting them with javascript from a form on click.

If I have an href like

<a href="#" id="myHref" emails="whatever@example.com"></a>


And I have a bunch of checkboxes for every email obtained from the database



Using javascript, how can I add this
value
into the emails="" tag by clicking the checkbox?

Answer Source

You can listen to change event for each checkbox to keep track of checked emails:

var boxes = document.querySelectorAll('input[name=email]');
var link = document.getElementById('myHref');
var emails = [];

boxes.forEach(box => box.addEventListener('change', function(e) {
  var v = e.target.value;
  if (e.target.checked === true) {
    if (!emails.includes(v)) emails.push(v);
  } else {
    emails.splice(emails.indexOf(v), 1);
  };
  link.setAttribute('emails', emails.join(', '));
  console.log(link.attributes.emails.value)
})) 
<input type="checkbox" value="1@d.com" name="email">
<input type="checkbox" value="2@d.com" name="email">
<input type="checkbox" value="3@d.com" name="email">

<a href="#" id="myHref" emails="whatever@example.com">Link</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download