Reputation: 717
I've searched around Stack Overflow for a couple of hours and seen similar questions asked but none of the supplied solutions are quite what I'm looking for, or just plain don't work.
So I'm trying to get the ID of a button which sits under a certain div using Javascript ONLY and not using any Javascript within the HTML code.
My HTML code looks like this:
<div id="constants" class="hidden">
<fieldset>
<legend>Gas</legend>
<div>
<div class="daily_charge">
<p>Daily charge: <span id="gasDaily"></span></p>
<button id="gasDaily_Edit">Edit</button>
</div>
<div class="rate_charge">
<p>Gas rate: <span id="gasRate"></span></p>
<button id="gasRate_Edit">Edit</button>
</div>
</div>
</fieldset>
<fieldset>
<legend>Elec</legend>
<div>
<div class="daily_charge">
<p>Daily charge: <span id="elecDaily"></span></p>
<button id="elecDaily_Edit">Edit</button>
</div>
<div class="rate_charge">
<p>Elec rate: <span id="elecRate"></span></p>
<button id="elecRate_Edit">Edit</button>
</div>
</div>
</fieldset>
<fieldset>
<legend>Water</legend>
<div>
<div class="daily_charge">
<p>Daily charge: <span id="waterInDaily"></span></p>
<button id="waterInDaily_Edit">Edit</button>
</div>
<div class="rate_charge">
<p>Water rate: <span id="waterInRate"></span></p>
<button id="waterInRate_Edit">Edit</button>
</div>
</div>
</fieldset>
</div>
and the Javascript I've been trying to use unsuccessfully is:
var constantsDiv = document.getElementById("constants");
var constants_button = constantsDiv.getElementsByTagName("button");
var button_count = constants_button.length;
for (var i = 0; i <= button_count; i += 1) {
constants_button[i].onclick = function (e) {
alert(this.id);
};
};
For a start I'm not sure putting it in a for loop is entirely the right way but I get an 'Unable to set property 'onclick' of undefined or null reference' anyway.
Any ideas?
Thanks
Upvotes: 0
Views: 131
Reputation: 149
Add a function which create a data-click element on clicked button (with class), then find data and her value...
$(".btnToClick").on("click", function {
$(this).data('click', true);
})
and
$(".btnToClick [data-click=true]").val();
i wrote with JQuery
Upvotes: 0
Reputation: 995
You can try it with this:
e.target.getAttribute("id")
Where e
is the variable in your function to handle the event.
Upvotes: 0
Reputation:
You can use: e.target.id
for (var i = 0; i < button_count; i += 1) {
constants_button[i].onclick = function (e) {
alert(e.target.id);
};
};
Upvotes: 0
Reputation: 22158
Your for()
statement will crash in the last element. Change removing the =
sign in the condition:
for (var i = 0; i < button_count; i += 1) {
===================^
Upvotes: 2