I have a variable called Asset1
I want everytime I click on the button that Asset1 goes to Asset2, Asset3, Asset4 etc. It increases by 1.
But I don't know how to set up a variable which can change after you click on a button. I thought of something like this.
var Asset[x]; [x]++; // after the mouseclick event
I'm stuck, can someone assist?
You can use an array like below:
var assets = []
// Add to this array
assets.push(house_location + " " + "Cost" + " " + cost + " " + "Downpay"+ " " + downpay)
// Access a particular element eg. first
assets[0]
// Check if already have a house
assets.length > 0
Increases value each time the button is clicked by calling a function.
//initialize number
var i = 0;
function clicked(n) {
//increase value by number of times clicked
i = i + n;
//get number element
var number = document.getElementById("number");
//Set number element to Document
number.innerHTML = i;
};
Codepen: https://codepen.io/AMSteffensen/pen/oNjjmaQ
Related
The code below gets info from xml file.
I succesfully presents the id and name of each planet with a button.
I want to add an onclick event on the button.
Problem now is: it does add the onclick event but only on the last button created in the loop.
What am i doing wrong? Why doesnt it create a onclick event for each button, but only for the last one in loop?
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
valDiv = ''; // clear valDiv each time loop starts
// Get the id and the name from the xml info in current <planet> tag
valDiv += planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
valDiv += planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (i + 1);
valButton.object = this;
//
// Here is the problem i cant get fixed
//
//valButton.onclick = function(){ showinfo(); }
valButton.addEventListener('click', showinfo);
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}
}
// simple function to check if it works
function showinfo() {
console.log(this.object);
console.log(this.id);
}
The trouble is this line:
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
When you set innerHTML the content currently in there gets destroyed and replaced with the new html, meaning all your old buttons are now destroyed and new ones are created. The previously attached event listeners do not get attached to the new buttons.
Instead simply create a div/span or whatever container would best help, add your planet text or whatever to it and then use appendChild
valDiv = document.createElement("div");
var id = planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
valDiv.innerHTML = id+"<br>"+name+"<br>";
document.getElementById("planetenID").appendChild(valDiv);
You could also use insertAdjacentHTML
var id = planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
valDiv = id+"<br>"+name+"<br>";
document.getElementById("planetenID").insertAdjacentHTML("beforeend",valDiv);
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
(function(num){
valDiv = document.createElement("div");
// Get the id and the name from the xml info in current <planet> tag
var id = planets[num].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
var name = planets[num].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
valDiv.innerHTML = id+"<br>"+name+"<br>";
document.getElementById("planetenID").appendChild(valDiv);
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (num + 1);
valButton.object = this;
// FIX: PASS showinfo TO AN ANONYMOUS FUNCTION CONTAINING THE OBJECT
valButton.addEventListener('click', function(){
showinfo(valButton);
});
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}(i));
}
}
// simple function to check if it works
function showinfo(valButton) {
console.log(valButton.object);
console.log(valButton.id);
}
I am building an HTML form, and for one section of it, a cluster of HTML input fields inside of a div needs to be pushed to an array. The div and all of the fields get unique ids/names when created - in particular, one of the inputs is a select.
All of this works fine - the fields are created and pushed to the array, everything id'd correctly, etc., but I can't seem to access the select element for a jQuery change function that is supposed to come later, after the fields have been created. I tested out an inline Javascript "onchange = myFunction()" type thing and this was able to access the select element - I get why this works, but it's not going to be an acceptable solution... I really need to use a $("#id").change function.
How can I use jQuery to access a select element that's stored in an array?
this['input_array' + siteName] = [];
for (y = 0; y < numberFound; y++){
this['input_array' + siteName].push('<div id="'+routeValue+''+siteName+'Details'+y+'" class="details">Species: <select id="'+siteName+'Species'+y+'" name="species['+y+']" data-speciesNumber="'+y+'">'+speciesList+'</select></div>);
$("#"+siteName+"Species"+y+"").change(function(){
species = this.value;
speciesNumber = this.getAttribute("data-speciesNumber");
siteSpeciesNumber = displayName + "" + species + "" + speciesNumber;
document.getElementById(""+siteName+"compileField"+speciesNumber+"").value = siteSpeciesNumber;
});
};
$("#"+routeValue+""+siteName+"Details").append(this['input_array' + siteName]);
The issue is not that the select is inside an array, it's that it is not yet attached to the DOM.
Try attaching the event handler as part of the element. Now when jQuery inserts the element into the document, the event binding is registered.
function $newSelect(y) {
return $('<select />', {
html: speciesList,
id: siteName + 'Species' + y,
name: 'species[' + y + ']',
data: {
speciesNumber: y
},
on: {
change: function(){
species = this.value;
speciesNumber = this.getAttribute("data-speciesNumber");
siteSpeciesNumber = displayName + "" + species + "" + speciesNumber;
document.getElementById(""+siteName+"compileField"+speciesNumber+"").value = siteSpeciesNumber;
}
}
}
}
function $newField (idNum) {
return $("<div id="'+routeValue+''+siteName+'Details'+y+'" class="details"></div>", {
html: $newSelect(idNum)
});
}
this['input_array' + siteName] = [];
for (y = 0; y < numberFound; y++){
this['input_array' + siteName].push($newField(y));
};
$("#"+routeValue+""+siteName+"Details").append(this['input_array' + siteName]);
I'm trying to make javascript application where a user can enter the kind of cookie she/he wants to make, and then select the amount of cookies they want. Once the user makes this selection and presses the "bake" button, the cookies appear randomly in the page. I had an assignment once where I had to generate random divs on a page, and it kind of gave me the idea for this, which is just for fun and practice.
My problem is that I want the user to be able to get unique information about the cookies he/she creates by clicking on them, and I can't get this to work.
(1)
Click Event is not defined properly :
aCookie.onlclick = cookie.display();
// typing error onlclick
// cookie.display() actually it call display function, doesn't give reference
change to :
aCookie.onclick = cookie.display;
(2)
set id "kind" to input box
(3)
Current code set properties (id,kind,x,y) to instance of Cookie, not to element.
Change code so that, the element is a parameter & set properties to it.
//pass element to set properties
function Cookie(elem,id, kind, x, y) {
elem.id = id;
elem.kind = kind;
elem.x = x;
elem.y = y;
this.display = function () {
alert("Cookie number: " + this.id + "; is a: " + this.kind + "; cookie : " +
" and it is situated on coordinates ; " + this.y + " and " + this.x + " on the cookie pan");
}
}
Fiddle : http://jsfiddle.net/aslancods/CzgLj/
The is(:focus) was the aproach. The final code is listed below:
setInterval(function(){
if($j("SELECT[name='cf20_field_7']").is(":focus")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").val();
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
hovered = true;
}
,100
);
Is there some possibility to fire function when there is no hover in SELECT field.
And also there may be aproach that to check is there is no hover on SELECT field.
It cause problemms. When you are trying to select another option cursor is begging while setInterval is working.
The best approach that i find is listed below:
//every 100 mil secconds update info
setInterval(function(){
$j("SELECT[name='cf20_field_7']").trigger('change');
if ( $j("SELECT[name='cf20_field_7']").on("change")) return false;
var information = '';
var i = 1;
$j("#cf20_field_1").html();
//add new information to hidden field
$j("#cforms20form .info_for_email").each(function(){
var name = $j(this).find("INPUT[name='cf20_field_5']").val();
var inn = $j(this).find("INPUT[name='cf20_field_6']").val();
var view = $j(this).find("SELECT[name='cf20_field_7']").attr("value");
//render
information += i + ")";
information += "Наименование организации: " + name + ".<br/>\n";
information += "Реквизиты организации: " + inn + ".<br/>\n";
information += "Стоимость заказа: выписка " + view + ".<br/>\n";
i++;
})
$j("#cf20_field_1").html(information);
}
,100
);
More information:
I can discribe situation more. So i had a form. onsubmit event didn`t work because there is another event is attachet. So i deside to update value of first field of form every 100 milisecs. The value is containing all dynamictly created "selects and inputs". But when i try to change value of the select by mouse. The function is fired and function check value of select and cause mouse begging. So i need somehow to check if that select is hovered to prevent firing of the function.
Invalid here:
if ( SELECT[name='cf20_field_7'].on("change"))
I guess you need this:
if ( $("SELECT[name='cf20_field_7']").on("change"))
But still, the above is invalid. You need some handler like:
$("SELECT[name='cf20_field_7']").on("change", function(){
return false;
});
if ($j("SELECT[name='cf20_field_7']").on("change")) return false
Not clear what should be checked here. I assume you want to run some function attached to onchange even of select. In that case you should use .trigger instead of .on. But in both cases return value will be jquery object (for chaining purposes) so basically your statement will always be true both with trigger and on If you want to test some value of select, you should do something like next:
if(someTestFunct($j("SELECT[name='cf20_field_7']"))) return false;
function someTestFunct(jObj) {
//some other code?
return jObj.val() == "some value to test";
}
Possibly some better approach may be used, but without more details it is hard to suggest something.
I have a simple script showing the character count for a text input element or a textarea element.
$("input[type=text],textarea").keyup(function(){
var currentLength = ($(this).val().length);
var maximum = 100;
var spanLimit = $("span[name=Limit]");
spanLimit.html("("+ currentLength + " of " + maximum + ")");
});
While the script performs its function, I noticed that the user loses the ability to undo his/her typing with either Ctrl+Z or the right click menu option. If I comment out the following line, the undo function is not lost:
spanLimit.html("("+ currentLength + " of " + maximum + ")");
Is there any way to not lose the undo stack after performing DOM manipulation?
P.S. This behavior is visible when using IE8
You forgot a quote in var spanLimit = $("span[name=Limit]);.
It should be var spanLimit = $("span[name=Limit]");