The code is simple:
var td1 = document.createElement("td");
td1.id="td_radio_"+nr_int+"_"+nr_var2;
td1.style.border = "0";
td1.style.width = "5%";
td1.onclick="adaugare_varianta_simplu(\'"+nr_int+"\',\'"+nr_var2+"\');";
but the function doesn't fire when I click the cell; what am I doing wrong? I'm not using bind because later on there's gonna be a removeAttr working on it so I want it set up as an attribute.
You are assigning a string as event handler so it can not be executed, below is more what you are after I think.
var td1 = document.createElement("td");
td1.id="td_radio_"+nr_int+"_"+nr_var2;
td1.style.border = "0";
td1.style.width = "5%";
td1.onclick = function() {
adaugare_varianta_simplu(nr_int,nr_var2);
};
Think you need this:
td1.onclick="function(){adaugare_varianta_simplu(\'"+nr_int+"\',\'"+nr_var2+"\');}";
You have to wrap the event in a function.
Related
This question already has an answer here:
addEventListener in Javascript triggers the click event automatically
(1 answer)
Closed 1 year ago.
I am creating a list of buttons inside a table, like this:
let tbody = document.createElement("tbody");
tbody.className = "table-responsive";
let id = 0;
for (let c of rows) {
let tr = document.createElement("tr");
tr.className = "table";
for (const v of c) {
let td = document.createElement("td");
td.className = "table";
let txt = document.createTextNode(v);
td.appendChild(txt);
tr.appendChild(td);
}
id++;
let button = document.createElement("button");
button.innerHTML = "ACTUALIZAR DATOS";
button.className = "btn btn-outline-primary";
button.id = id++;
button.onclick = upgradePet();
tr.appendChild(button);
tbody.appendChild(tr);
}
the table shows correctly, but when i try to add the .onclick, but when the table load, it call immediately the function upgradePet() without me clicking it.
i try doing:
button.addEventListener("click", upgradePet());
button.onclick = upgradePet();
but both call the function when the table finish render.
Remove the parentesis from your upgradePet as that represents a function call (meaning you are not just defining the function on the click event, but you're calling it straight away).
So this works fine,
button.onclick = upgradePet;
In case you will ever need to define functions with parameters, you can write them as followed,
button.onclick = () => upgradePet(param);
Remove the parentesis.
addEventListener
onclick
button.addEventListener("click", upgradePet);
button.onclick = upgradePet;
Two things to fix:
Add function objects as event listeners, not the value returned from calling a handler function. The return value is often undefined or, more rarely, a boolean value:
element.addEventListener( eventName, handler); ✔️
element.addEventListener( eventName, handler()); ❌
Do not append a <button> element to a table row - they are not valid child elements of a <tr> element. Create an extra td element, put the button element inside it and append the table data element created to the table row.
I'm struggling to make the onclick event listener work in my results.
here is my code:
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
temp1 = text.replace("/","-");
temp2 = res1.replace("/","-");
a.onclick=function(){goMainMenuFromResults();};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
The line in question is:
a.onclick=function(){goMainMenuFromResults();};
The function is present in another section but works in the hardcoded html events. I just can't make it work when its imported into the element in javascript.
Any help will be greatly appreciated!
James, it seems to work fine, just a var called res1 was getting error here. Take a look:
temp2 = res1.replace("/","-");
http://jsfiddle.net/MarcelKohls/23tBM/291/
I removed the lines containing variables that were not defined. I then added a call to preventDefault() on the event raised inside the event handler. And it now works fine. New elements are created and the click handler works on the new elements.
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
//temp1 = text.replace("/","-");
//temp2 = res1.replace("/","-");
a.onclick = function(e) {
e.preventDefault();
goMainMenuFromResults();
};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
I am trying to create a row of a table on the check action of a checkbox which is created dynamically. The flow is not entering the function on the check event.
addCheckboxItems : function(form){
var newBox = ('<input type="checkbox" name="checkBoxItem" onCheck="JavaScript:addRowItems(this)"; id="checkBoxItemId" value="' + form.combobox.value +'"'+ '>'+form.combobox.value);
document.getElementById("divCheckbox").innerHTML = newBox;
}
addRowItems : function(element){
alert('Hi');
if(document.getElementById("checkBoxItemId").checked){
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var td1 = document.createElement("td")
var strHtml1 = document.getElementById('checkBoxItemId').value;
td1.innerHTML = strHtml1.replace(/!count!/g,count);
var td2 = document.createElement("td")
var strHtml2 = "NA";
td2.innerHTML = strHtml2.replace(/!count!/g,count);
var td3 = document.createElement("td")
var strHtml3 = "<a>Remove</a>";
td3.innerHTML = strHtml3.replace(/!count!/g,count);
newRow.appendChild(td1);
newRow.appendChild(td2);
newRow.appendChild(td3);
tableRef.appendChild(newRow);
}
}
How can I achieve this.....Thanks in advance..
First of all your syntax gives an idea that you're creating functions in some object addCheckboxItems : function(form) but in your html event handlers onCheck search global scope for the function. So you should define functions like addCheckboxItems = function(form) in global scope.
Besides there is no oncheck event. There is onclick event.
Here is a jsfiddle with this corrections where you can get the idea (and debug) what I am talking about. It however crashes inside addRowItems because there is not enough context in your code the build a working app... But you got your handler running and can continue now
Hi in your function can u try this
addCheckboxItems : function(form){
var newBox = ('<input type="checkbox" name="checkBoxItem"
onchange="JavaScript:addRowItems(this)";
id="checkBoxItemId" value="' + form.combobox.value +'"'+
'>'+form.combobox.value);
document.getElementById("divCheckbox").innerHTML = newBox;
}
I added the onchange event of the input element. This should do the trick.
EDIT
Also you can try with the onclick event of the checkbox. It seems that the change event behaves differently in IE, so many users prefer the click event which is fired post change in the state of the input element. You can refer Getting value of HTML Checkbox from onclick/onchange events
I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element
I'm trying to insert an onmouseover when creating new rows within my table however it's not appearing. Am I missing something stupid?
var row = document.createElement("TR");
row.id = i;
row.onmouseover = hover(i);
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
The variable 'i' is the current number in the loop. The ID of the row appears fine, but not the onmouseover.
Use an anonymous function to create a closure for the value of i, and make sure you're setting a function to onmouseover, rather than the result of calling a function:
var row = document.createElement("TR");
(function (i) {
row.onmouseover = function () { hover(i) };
})(row.id);
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
Taking a proper look at your code, it appears that you're not actually setting the id attribute of the TR element. However, you might want to avoid that entirely and use this context inside the hover function:
var row = document.createElement("TR");
row.onmouseover = hover;
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
function hover() {
alert(this.rowIndex); // <-- `this` refers to the row element
}
You are assigning the result of the function to the event.
Needs to be something like
row.onmouseover=function(){hover(this);}
And it is better to use this since you have the DOM object and do not have to look up anything.
function hover( row ){
row.style.color = "red";
}
If you still what to go the i way, you need to change your id so it is valid. Ids can not start with a number.
var row = document.createElement("TR");
row.id = "row_i";
row.onmouseover = function(){ hover(this.id); }
var td1 = document.createElement("TD");
row.appendChild(td1);
tbody.appendChild(row);
Maybe try:
row.onmouseover = function() { hover(i); };