How to return an 'onclick' Attribute? - javascript

If I remove an onclick attribute, how can I set it back on the same element with the first function that was applied on the onclick event.
For example function show(clicked_id) // gets the user id by clicking.
I dont want the user to click twice on the same id so I use a remove attribute.
Then I want to change it back the way it was.
function getthepic(m) {
GetPic.setAttribute("src", randomImages[m]);
x.appendChild(GetPic);
StorePics[i] = randomImages[m];
StoreIds[i] = x;
counter++;
i++;
CheckValve = false;
StoreIds[0].removeAttribute("onclick");
}
setTimeout(function() {
if (counter == 2) {
StoreIds[0].innerHTML = "";
StoreIds[1].innerHTML = "";
var getCard = document.createElement('img');
getCard.setAttribute("src", 'images/blank.png');
StoreIds[0].appendChild(getCard);
var getCard2 = document.createElement('img');
getCard2.setAttribute("src", 'images/blank.png');
StoreIds[1].appendChild(getCard2);
counter = 0;
i = 0;
StorePics[0] = "";
StorePics[1] = "";
StoreIds[0] = "";
StoreIds[1] = "";
StorePics.pop();
StoreIds.pop();
StorePics[0].setAttribute('onclick', show(clicked_id);
}
CheckValve = true;
}, 1000);

Related

How to change content of first Child dynamic

for(let i = 0; i < 8; i++) {
let childDiv = document.createElement('div');
divi.id = "addDay";
childDiv.className = "boxName";
divi.appendChild(childDiv);
childDiv.textContent = "0";
}
document.querySelector('#map');
map.appendChild(divi);
divi.firstChild.style.backgroundColor = "green";
change();
}
function change(){
n = document.getElementById('addDay');
n.firstChild.textContent = 'something';
}
I need to change content of first child of addDay on every click,but this function makes it only once. What do you think where is problem?

Unable to edit input field added via javascript

I have a simple table with cells. When the user clicks on a cell, a textbox is added inside the cell where they can edit the content. However, when i double click a cell to edit it's content, the attributes of the input field show up. It does not allow me to edit and add another value. Here is the script I'm using.
window.onload = function() {
var cells = document.getElementsByTagName("td");
var theads = document.getElementsByTagName("th");
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
highlightCell(i);
});
}
function highlightCell(x) {
var txtBox = document.createElement("input");
txtBox.id = "myTxt";
txtBox.type = "text";
for (var i = 0; i<9; i++) {
if (i == x) {
txtBox.value = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(txtBox);
cells[i].style.backgroundColor = "lightBlue";
}
}
}
}
Found the solution, just needed to use select(). This highlights the selected field, adds a input box which the user can update, then save the value in the cell when enter is pressed.
function highlightCell(x) {
//add input field inside cell
var txtBox = document.createElement("input");
txtBox.id = x;
txtBox.type = "text";
for (var i = 0; i<9; i++) {
if (i == x) {
txtBox.value = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(txtBox);
txtBox.select();
cells[i].style.backgroundColor = "lightBlue";
cells[x].onkeypress = function(){
var event = window.event;
var btnPress = event.keyCode;
if(btnPress == 13)
{
var elem = document.getElementById(x);
cells[x].innerHTML = elem.value;
elem.parentNode.removeChild(elem);
}
}
} else {
cells[i].style.backgroundColor = "white";
}
}
}

Passing One's Self to OnClick Event JavaScript

The on click event that I add to an input in javascript isn't working in the proper manner.
My code so far looks like so:
function order(option) {
if(option.checked) {
document.getElementId("col_order").value = document.getElementById("col_order").value + " " + option.value;
}
}
...//somewhere further down
for(var i = 0; i < options.length; i++) {
var check = document.createElement("input");
var label = document.createElement("label");
var description = document.createTextNode(options[i]);
check.type = "checkbox";
check.name = "order_list[]";
check.value = options[i];
check.onclick = "order(check)"; //Problem here
label.appendChild(check);
label.appendChild(description);
element.appendChild(label);
}
I have also tried:
check.onclick = (function() { var option = check; return function() {order(option);}})();
The problem that I am having is the check.onlick line of code. When I add this with normal HTML:
<input type = "checkbox" name = "order_list[]" onclick = "order(this)" value = "randVal">randVal</input>
I don't have any problem whatsoever; the method executes with the intended results. Any thoughts?
Let me clarify: I make it to the order function just fine, but I never get into the if statement, even though the checkbox was just clicked
Use addEventListener instead, and even if it looks like it should work, you're overwriting the same variables on each iteration as there is no closure in for loops, so I would probably add a closure to avoid issues.
For a checkbox you would listen for the change event, not click
for(var j = 0; j < options.length; j++) {
(function(i) {
var check = document.createElement("input");
var label = document.createElement("label");
var description = document.createTextNode(options[i]);
check.type = "checkbox";
check.name = "order_list[]";
check.value = options[i];
check.addEventListener('change', function() {
if (this.checked) {
var col_order = document.getElementById("col_order");
col_order.value = col_order.value + " " + this.value;
}
}, false);
label.appendChild(check);
label.appendChild(description);
element.appendChild(label);
})(j);
}
FIDDLE
check.onclick = "order(check)"; assigns a String as an on-click handler. That doesn't work; the browser expects a function there:
check.onclick = function() {
order(check);
}

Unable to define a click event on a href tag

I am trying to write a click event for an anchor tag in my tampermonkey script.
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link1>Click me</a>");
var link = document.getElementById('link1');
link.addEventListener("click", function() {
window.alert('I am clicked');
}, false);
}
}
The alert message never gets triggered when I click on the link in the page dispalyed, even though I have a a click event listener defined. What am I doing wrong here?
It's the way you're adding HTML, you're reappending the link when you do this in the next iteration.
link.innerHTML += something
So the event handler is lost, and you can actually prove that by adding the event handler to the last element instead.
If you do it the proper way, creating elements and appending them, it works fine
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
for (var i = 0; i < 20; i++) {
if (i !== 15) {
var txt = document.createTextNode(lines[i] || ''),
br = document.createElement('br');
contentTag.appendChild(txt);
contentTag.appendChild(br);
} else {
var link = document.createElement('a');
link.id = 'link1';
link.innerHTML = 'Click me';
link.addEventListener("click", function () {
alert('clicked')
}, false);
contentTag.appendChild(link)
}
}
FIDDLE
Shoud be contentTag.innerHTML+=("<a id='link1'>Click me</a>");
Try this:
<script>
var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;
contentTag.innerHTML = "";
var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);
for(var i=0; i<20; i++) {
if(i!==15)
contentTag.innerHTML+=(lines[i]+"<br>");
else {
contentTag.innerHTML+=("<a id=link"+i+">Click me</a>");
var link = document.getElementById('link'+i);
var att=document.createAttribute('onclick');
att.value="alert('Clicked !')";
link.setAttributeNode(att);
}
}
</script>
Demo: http://jsfiddle.net/TmJ38/

assign parameter value of an object javascript

I have been looking at this code for a long time trying to figure this out, but I am having no luck. This issue is that I want to assign a value to the parameter boxId. When I click on a box in the webpage an alert will come up displaying that id. I have tried many things, but nothing seems to work. I'm a beginner, so I feel at this point there just must be something that I don't know how to do.
constructor function:
function Box (boxId, name, color, number, coordinates) {
this.boxId = boxId;
this.name = name;
this.color = color;
this.number = number;
this.coordinates = coordinates;
}
global variables:
var boxes = [];
var counter = 0;
var boxId = 0;
init function:
window.onload = init;
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = getBoxValues;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
function to get values and create new boxes:
function getBoxValues() {
var nameInput = document.getElementById("name");
var name = nameInput.value;
var numbersArray = dataForm.elements.amount;
for (var i = 0; i < numbersArray.length; i++) {
if (numbersArray[i].checked) {
number = numbersArray[i].value;
}
}
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (name == null || name == "") {
alert("Please enter a name for your box");
return;
}
else {
var newbox = new Box(boxId, name, color, number, "coordinates");
boxes.push(newbox);
counter++;
var boxId = counter;
}
addBox(newbox);
var data = document.getElementById("dataForm");
data.reset();
}
function that adds boxes to the page:
function addBox(newbox) {
for (var i = 0; i < newbox.number; i++) {
var scene = document.getElementById("scene");
var div = document.createElement("div");
div.className += " " + "box";
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
div.style.left = x + "px";
div.style.top = y + "px";
scene.appendChild(div);
div.onclick = display;
}
}
function to display alert when box is clicked:
function display(e) {
var a = e.target;
alert(a.counter);
}
function to clear boxes:
function clear() {
var elems = document.getElementsByClassName("box");
for ( k = elems.length - 1; k >= 0; k--) {
var parent = elems[k].parentNode;
parent.removeChild(elems[k]);
}
}
All of the other functions work just fine. I keep running into the id showing up as "undefined" when I click it, or the counter displaying "0" in the console log, for everything I've tried.
You can do it like this.
First, in addBox() embed boxId as an tag's attribute like this:
div.setAttribute('data-boxId', newbox.boxId);
Then in display() you can retrieve it back:
alert(e.target.getAttribute('data-boxId'));
Please tell if you do not prefer this approach and I will post an alternative (closure things).
Edit: Add jsfiddle example http://jsfiddle.net/runtarm/8FJpU/
One more try. Perhaps if you change:
var boxId = counter;
to
boxId = counter;
It will then use the boxId from the outer scope instead of the one defined in the function getBoxValues()

Categories

Resources