Lelio Faieta
Lelio Faieta

Reputation: 6684

onclick event: select item to be clicked by id

I have a button with name="testo_da_inviare" and I can trigger it's click event with:

document.forms['form_da_ricordare'].elements['testo_da_inviare'].onclick

Now I want to replace the button element with an a element that doesn't support the name attribute. So I gave the a element the id="testo_da_inviare"

How do I have to edit my js to trigger the onclick? Javascript is not my cup of tea and I am still learning how to use plain javascript.

Upvotes: 0

Views: 2449

Answers (3)

L777
L777

Reputation: 8487

1- You can let the onclick event trigger on the link/button itself like this:

<a href="#" target="_self" onclick="thefunct()">description</a>
<button onclick="thefunct()">description</button>

function thefunct() {
    alert("button clicked");
}

2- Or on the script like this:

document.getElementById("id").onclick = function thefunct(){ alert('button clicked'); };

3- Or using an eventlistener like this:

document.getElementById("id").addEventListener("click", thefunct);

function thefunct() {
    alert('button clicked');
}

4- Or using jQuery like this:

$("#id").click(function(){
alert('button clicked');   
});

<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>

Upvotes: 0

xxxmatko
xxxmatko

Reputation: 4142

If you want to fire an event of an element, the right way is to use dispatch method or createEventObject, not to call the element handler name

var eventName = "click";
var element = document.getElementById("testo_da_inviare");

if (document.createEventObject) {
   // Dispatch for IE
   var evt = document.createEventObject();
   element.fireEvent("on" + eventName, evt);
}
else {
   // Dispatch for firefox + others
   var evt = document.createEvent("HTMLEvents");

   // Event type, bubbling, cancelable
   evt.initEvent(eventName, true, true);
   element.dispatchEvent(evt);
}

Upvotes: 0

j08691
j08691

Reputation: 207963

You can use getElementById to select it:

document.getElementById('testo_da_inviare').onclick

Upvotes: 3

Related Questions