skip to Main Content

I have some html on test.html and JavaScript code on test.js. I put alerts in the functions to test it, and I’m constantly getting only the first alert (1232c) regardless of which hyperlink I click on. I don’t understand, I have a reference to a specific anchor element using its id, why does .onclick think they are all the same if they have the same URL (form.html). I want only function test to happen if I click the hyperlink with id 1232c, and function test2 to happen if I click the hyperlink with id1232b.

function init () {
  var jobID = document.getElementById("1232c");
  var jobID2 = document.getElementById("1233b");
  jobID.onclick = test("1232c");
  jobID2.onclick = test("1233b");
}

function test(id) {
  alert(id);
}

function test2(id) {
  alert(id);
}

window.onload = init;
<a href="form.html" id="1232c">Apply</a>
<a href="form.html" id="1233b">Apply</a>

3

Answers


  1. You are calling your function before clicking

    You have to assign a function, not a function call

    function init() {
    
      var jobID = document.getElementById("1232c");
      var jobID2 = document.getElementById("1233b");
      jobID.onclick = () => test("1232c");
      jobID2.onclick = () => test("1233b");
    
    }
    
    function test(id) {
      alert(id);
    }
    
    function test2(id) {
      alert(id);
    }
    
    window.onload = init;
    <a href="form.html" id="1232c">Apply</a>
    <a href="form.html" id="1233b">Apply</a>
    Login or Signup to reply.
  2. You have a typo in that jobID2 calls test() and not test2(). As you describe it, that may be all you need.

    But, if you are trying to wire up on click handlers, you need to assign functions to the onclick property. What you have assigned is the return values after you call test() during window OnLoad. Something like this:

    jobID.onclick = test;
    

    or as @Konrad described, an anonymous function if you need to pass in that argument:

    jobID.onclick = () => {
        test("1232c");
    };
    

    (I don’t believe the order of the function definitions is important due to hoisting)

    Login or Signup to reply.
  3. An event listener requires a function to be assigned to it. Currently you’re assigning the result of calling those functions. Note: you don’t need two functions to deal with the clicks. Since you’re passing in an id as an argument just use test to cater for both events.

    Option 1

    Assign a function to the listener that calls test when the event is fired.

    jobID2.onclick = () => test('1233b');
    

    Option 1

    Assign test directly to the listener, and log/alert the id from the clicked anchor.

    var jobID = document.getElementById("1232c");
    var jobID2 = document.getElementById("1233b");
    
    jobID.onclick = test;
    jobID2.onclick = test;
    
    function test(e) {
      e.preventDefault();
      console.log(this.id);
    }
    <a href="form.html" id="1232c">Apply</a>
    <a href="form.html" id="1233b">Apply</a>

    There are a couple of alternative approaches.

    Approach 1

    1. Use querySelectorAll to grab all the anchors.

    2. Iterate over the anchors and assign event listeners to them.

    3. The handler accepts an event e. It first prevents the anchor from its default action (going to the page indicated by the href), and then logs the id of the element that was clicked.

    // Cache the anchors
    const anchors = document.querySelectorAll('a');
    
    // Iterate over the anchors and add a listener to
    // each one
    anchors.forEach(anchor => {
      anchor.addEventListener('click', handleClick);
    });
    
    // The handler accepts the event as an argument,
    // prevents the redirect, and then logs the clicked
    // anchor's id
    function handleClick(e) {
      e.preventDefault();
      console.log(this.id);
    }
    <a href="form.html" id="1232c">Apply</a>
    <a href="form.html" id="1233b">Apply</a>

    Approach 2

    Use event delegation. Add one listener to a containing element (a section perhaps as in this example), and assign it a handler that deals with all the click events from its child elements.

    1. Use querySelector to grab the container.

    2. Add one event listeners to the container.

    3. The handler accepts an event e. It first checks to see what element was clicked. If it’s an anchor it prevents the anchor from its default action, and then logs the id of the anchor that was clicked.

    // Cache the container
    const container = document.querySelector('.container');
    
    // Add a listener to the container
    container.addEventListener('click', handleClick);
    
    // The handler accepts the event as an argument,
    // prevents the redirect, and then logs the clicked
    // anchor's id
    function handleClick(e) {
      if (e.target.matches('a')) {
        e.preventDefault();
        console.log(e.target.id);
      }
    }
    <section class="container">
      <a href="form.html" id="1232c">Apply</a>
      <a href="form.html" id="1233b">Apply</a>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search