Can't pass a variable as an argument in a onClick function - javascript

I want to have a table and its cells are filled with data from MySQL.
The table have many TDs, which have an Id.
I want to pass the id of the cell to a function, so that I can edit its content:
document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name = "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList("Cell_ID")" value="Edit Action" />';
function SaveUpdateToActionList(Cell) {
alert(Cell);
document.getElementById(Cell).innerHTML = 'Here';
}
When I have alert(Cell); displayed, I see this sends the Text "Cell_ID", whereas I wanted to see the data ActionButton386 there.
Any help appreciated.

You can pass in the element being clicked by setting your onClick script to SaveUpdateToActionList(this);
Then, in the body of SaveUpdateToActionList, Cell will refer to the button that just got clicked. You can then walk up the DOM to get to the TD it belongs to.

You can try this:
document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name = "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList()" value="Edit Action" />';
function SaveUpdateToActionList(event) {
alert(event.target.id);
document.getElementById(Cell).innerHTML = 'Here';
}
But if i understand correctly what you are trying to do, you shoud have a single event listner that catches bubling events from all cells, rather that attaching a an onclick to each cell....

Just register the event listener separately from specifying the innerHTML property:
Document.getElementById(IndexedActionButton).addEventListener('onclick', SaveUpdateToActionList);
SaveUpdateToActionList will be called with an event object as the first argument. You can access which element was clicked by checking the event.target property. For more information check out MDN - addEventListener documentation

Related

Bind an html event to a function

How do I bind an html event such as onclick to a function myFunc(e){}?
I do not want to use document.getElementByClass or Id.
I do not want use jQuery.
Try this:
document.getElementsByTagName('body')[0].addEventListener('click', function(){alert("you clicked on the page")})
This adds an event listener to the body tag. Once you click on the page, it will fire the alert function.
You can get the elements by either class name, id and/or tag name:
document.getElementById('someId')
document.getElementsByClassName('someClassName')
document.getElementsByTagName('body')
Keep in mind, the "getElementsByClassName" and "getElementsByTagName" return arrays, so you might want to add the index like this
getElementsByTagName('body')[0]
document.getElementsByClassName('someClassName')[1]
...
If it's still the 1990s where you are and jQuery hasn't been invented, then sure:
<div onclick="myFunc">
</div>
First you must find the element on the page, for example var element = document.getElementById('clickme'), then you must add a listener to the click event element.addEventListener('click',function)

Getting String Value Of JavaScript Button

I have a list of buttons that is created by the DOM which references an array. When a button in the list is clicked, I want to retrieve the String that is displayed on the Button.
I have tried the following code to reference the string value, but get undefined:
this.String; inside the function when the button is clicked to retreive the string.
How can I properly retrieve the string.
The click handling function is:
$('.timeButtons').click(function() {
confirmation.push(this.textContent);
})
This is how the list of buttons is created:
var populateList=function(array){
var list = document.createElement('ul');
list.className="delete";
for(var i = 0; i < array.length;- i++) {
var item = document.createElement('li');
var itemButton=document.createElement('button');
itemButton.style.cssText='background:#f85a5a; border:none; width:200px; height:50px; margin-bottom:50px; align:center; border-radius:25px; color:#ffffff;'
itemButton.appendChild(document.createTextNode(array[i]));
item.appendChild(itemButton);
list.appendChild(item);
}
return list;
}
Assuming that this is a reference to the button element in question, you can use this.textContent to get the button's text. (Or .innerHTML.)
Demo: http://jsfiddle.net/w0ntsrLx/
Or since in your edited question you seem to be using jQuery, use the .text() method. In a comment you say that the containing div has the "timeButtons" class, so bind a delegated handler to that div as follows:
$(".timeButtons").on("click", "button", function(e) {
confirmation.push($(this).text());
});
Demo: http://jsfiddle.net/w0ntsrLx/1/
That way the function will only be called if the click is on a button element within the .timeButtons div, and this will be the clicked button. The click handler that you show in your question with $(".timeButtons").click(...) is bound to the div and doesn't in any way test for the buttons, so within the handler this will be the div, not the clicked button.
Check this out
Assuming you want pure javascript code,
Whenever an event is triggered, an object is passed back in callback (generally being named as 'event'). this object has many properties including source element, position of click and many more.
get the element using event.srcElement
You can use element.innerHTML or element.innerText to find out the content of the Button.
There is a difference between using innerText and innerHTML, but in your case, both can be used.
Also, you can use jquery too to easily append child, create elements and binding events.

Deconstructing javascript script

I'm new to javascript and I am trying to destruct the following so I can understand it. I can't seem to find the answer on the web. Is anyone able to help?
$("#modal-add-person").on('show.bs.modal', function (e) {
var personId = $(e.relatedTarget).attr('data-id');
$('#modal-add-person-hidden').val(personId);
$('#modal-add-person-id-text').html(personId);
});
Thanks
In you code you have eventHandler on $("#modal-add-person") .
It means that somewhere in you global code you are triggering 'show.bs.modal' event on
$("#modal-add-person") like this
$("#modal-add-person").trigger('show.bs.modal')
The function that is 2nd parameter of on function is eventHandler function that receive eventObject.
function (e) {
var personId = $(e.relatedTarget).attr('data-id');
$('#modal-add-person-hidden').val(personId);
$('#modal-add-person-id-text').html(personId);
}
It use relatedTarget property of event object and extract data-id attribute from it.
var personId = $(e.relatedTarget).attr('data-id');
After it set that value in $('#modal-add-person-hidden') - I guess it is hidden input.
$('#modal-add-person-id-text').html(personId);
And last thing it's do draw the value in $('#modal-add-person-id-text') element.
$('#modal-add-person-id-text').html(personId);
And also you should look at jQuery reference for elements, selectors and etc.
$("#modal-add-person").on('show.bs.modal', function (e) {
'show.bs.modal' would be a event in html as a click is. So the above statement means on 'show.bs.modal' of an element with id modal-add-person ("anythig appended with a # means it is an id of a html element.") execute the steps in the function (e) where e seems to be another html element.
var personId = $(e.relatedTarget).attr('data-id');
Get the attribute 'data-id' from the element passed in e.(For example if it was attr('id') it would return the id of the element passed to personid )
$('#modal-add-person-hidden').val(personId);
Set the html element with id "modal-add-person-hidden" by the value in personId
$('#modal-add-person-id-text').html(personId);
Set the element's (where id = modal-add-person-id-text) inner html with personId
});
note: '#' stand for id of the html element '.' stands for class of the
element or you can give the tag as it is, for example "input" means
all elements with input tag
Hope this helps. Please let me know if this was helpful.

What is the meaning of this code in Javascript

I am newbie to Javascript, I have difficulties getting the meaning of this code properly. I would like to share my thought over the code,and I need your guidance to understand it correctly.
<body>
<form>
<input type="button" value="Click Me!" id="say_hi" />
</form>
<script type="text/javascript" src="js_event_01.js"></script>
</body>
function hi_and_bye() {
window.alert('Hi!');
window.alert('Bye!');
}
var hi_button = document.getElementById("say_hi");
hi_button.onclick = hi_and_bye;
My understanding: the event "onclick" calls the function "hi_and_bye" when ID is "get_alerts". Similarly this could be applied to any event, and I can give an id attribute to any element and that id would be responsible to make an accessible corresponding input element.
Your understanding is correct. You could give an id to any DOM element, not only inputs. Then using the getElementById you could retrieve a reference to this element.
In this example that's what you are doing:
// Get a reference to a DOM element that has id="say_hi"
var hi_button = document.getElementById("say_hi");
// subscribe to the onclick event handler of the DOM element we retrieved on
// the previous line and attach this handler to the hi_and_bye javascript function
hi_button.onclick = hi_and_bye;
I don't think that the body of the function itself requires any more explanation: it will just display 2 alerts once after the other when this function executes.

Removing the event listener on a button programatically

I have a button which is registered with a onclick event as shown
<Input type="Button" name="Register" Value="Register" onclick="CallMe();"/>
Is it possible to programatically remove or deregister the onclick event on this button?
You could set the onclick attribute to null.
var el = document.getElementById('inputId');
el.onclick = null;
or better just remove the attribute altogether with the removeAttribute() docs method of the element.
var el = document.getElementById('inputId');
el.removeAttribute('onclick');
you will need to add an id to the element though for this..
example code at http://jsfiddle.net/gaby/PBjtZ/
document.getElementsByName("Register")[0].onclick = ""
or
document.getElementsByName("Register")[0].removeAttribute("onclick")
Make sure to place this in a JS tag at the end of your document. So the DOM is available when this script is running.
the first example gets all elements with the name "Register" in your dom and returns the first, then it finds and sets the onclick attribute to an empty string. (could be null to)
the second example does the same, but removes the attribute "onclick".
Be careful if you have more then one element with the name "Register" you should do it like Gaby aka G. Petrioli told you to.

Categories

Resources