Passing a javascript value - javascript

I want to pass a numeric value through to the following Javascript function.
function swap2() {
var oldDiv = document.getElementById("product-grid");
var newDiv = document.getElementById("product-page");
oldDiv.style.display = "none";
newDiv.style.display = "block";
}
I want to be able to call the function with a number in the bracket like...
onclick="swap2(2)"
And then have the newDiv variable change based on that number like so...
var newDiv = document.getElementById("product-page2");
How can I go about doing this?

function(variable){
// process using 'variable'
}
that's how you pass a variable to a function. Thus:
function swap2(n) {
var oldDiv = document.getElementById("product-grid");
var newDiv = document.getElementById("product-page" + n);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}

Related

create multiple elements (list) with onclick event

I'm trying to add multiple elements to a list and each element should execute the same on click function with different parameters, the problem is the variable x gets always contains the same value for all elements of the list.
How can I add elements and call the onclick event with a different parameter?
var addQuickLabelList = function(txtList,ul) {
for (i = 0; i<txtList.length ; i++) {
var li = document.createElement("li");
li.setAttribute("data-icon", "false");
var a = document.createElement("a");
a.innerHTML = txtList[i];
li.appendChild(a);
var x = "#"+txtList[i];
a.addEventListener("click", function(){
y = x.clone();
alert(x);
} , false);// add
$(ul).append(li);
}
};
x always gets the same value because all your event handlers share the same var x variable. To scope a variable to a block, use let (or const if it won't change) instead of var.
Or you could use .forEach() on the txtList Array so that the var is scoped to the invocation of the callback.
var addQuickLabelList = function(txtList,ul) {
txtList.forEach(function(txtItem) {
var li = document.createElement("li");
li.setAttribute("data-icon", "false");
var a = li.appendChild(document.createElement("a"));
a.innerHTML = txtItem;
var x = "#"+txtItem;
a.addEventListener("click", function(){
console.log(x);
} , false);
ul.appendChild(li);
});
};
But you also don't really even need the x variable. You already set the text as the content of the a, so you can just grab that instead. Which means you could also reuse the function, which is nicer.
function handler() {
console.log("#" + this.textContent);
}
var addQuickLabelList = function(txtList,ul) {
txtList.forEach(function(txtItem) {
var li = document.createElement("li");
li.setAttribute("data-icon", "false");
var a = li.appendChild(document.createElement("a"));
a.innerHTML = txtItem;
var x = "#"+txtItem;
a.addEventListener("click", handler, false);
ul.appendChild(li);
});
};

onclick passing on value of button

I want to send to my onClick function, the value of the button that pressed on it.
I have this function
numfunc = function (val) {
var t = document.createTextNode(val);
document.body.appendChild(t);
};
I have 5 buttons. I want them all to use this function onClick, but each send a different value,
their value.
var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";
var two = document.createElement("input");
two.type = "submit";
one.onclick = numfunc;
two.value = "2";
and so on....
I'm trying to do this, on javascript not on the html file.
Thanks!
You can use this.value to get value inside you function numfunc, you don't need to send parameter, check example bellow.
Hope this helps.
numfunc = function (val) {
var t = document.createTextNode(this.value);
document.body.appendChild(t);
};
var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";
var two = document.createElement("input");
two.type = "submit";
two.onclick = numfunc;
two.value = "2";
document.body.appendChild( one );
document.body.appendChild( two );
Can you use this code instead?
one.addEventListener("click", function () {
numfunc(this.value);
}, false);
two.addEventListener("click", function () {
numfunc(this.value);
}, false);

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

how to remove the child node in js

i have one parent node name orgdiv and one child node name newdiv. I am trying to remove the child node but its not working here is the code.
function ajxsrch(str) {
if (str.length != 0) {
if (count == 0) {
var newdiv = document.createElement('DIV');
newdiv.className = "newsearch";
var orgdiv = document.getElementById("search");
orgdiv.appendChild(newdiv);
count = 1;
alert("firstif");
} else alert("first if else");
} else {
alert(str);
count = 0;
alert(count);
newdiv.orgdiv.removeChild(newdiv);
}
}
There are a few issues with your approach, and your JavaScript console will typically assist in debugging most of these.
First of all, consider the objects newdiv and orgdiv. Inside your else block, you reference both of these, but they are not declared or initialized anywhere. There is a declaration in your if block, but of course that doesn't get run the second time this method is called. When the else block is executing, the if block is ignored altogether.
So you need to correct your object references:
function ajxsrch(str) {
var orgdiv = document.getElementById("search");
var newdiv = document.getElementById("newDivId"); // assuming div has an ID
...
Then of course, in your if block, you will initialize newdiv correctly since it doesn't exist yet.
newdiv = document.createElement('DIV');
newdiv.id = "newDivId";
newdiv.className = "newsearch";
Finally, when removing the element, you're incorrectly referencing the parent as a property of the child (newdiv.orgdiv.removeChild(newdiv);). Instead, just access the parent directly:
orgdiv.removeChild(newdiv);
So your final solution becomes:
function ajxsrch(str) {
var orgdiv = document.getElementById("search");
var newdiv = document.getElementById("newDivId");
if (str.length != 0) {
if (count == 0) {
newdiv = document.createElement('DIV');
newdiv.id = "newDivId";
newdiv.className = "newsearch";
orgdiv.appendChild(newdiv);
count = 1;
alert("firstif");
} else alert("first if else");
} else {
alert(str);
count = 0;
alert(count);
orgdiv.removeChild(newdiv);
}
}
See also Node.removeChild MDN docs

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