Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When I click on this button the button disappears. im trying to make it so the button sticks on the screen and always adds one to the money variable. (sorry for the unclear explanation)
<!DOCTYPE html>
<html>
<body>
<script>
var money = 0;
function addMoney() {
money += 1;
document.write("Money: <b>" + money + "</b>");
}
</script>
<button type="button" onclick="addMoney()">Get a money</button>
</body>
</html>
I did not understand exacly what you want to do. But if you want to print the money variable on an element as you click the button, you can try:
<script>
var money = 0;
function addMoney() {
money += 1;
//document.write("Money: <b>" + money + "</b>");
document.getElementById('money-div').innerHTML = money;
}
</script>
<button type="button" onclick="addMoney()">Get a money</button>
<div id="money-div"></div>
You are overwriting document so you won't see your button after clicking. You do the rewriting this way:
document.write("Money: <b>" + money + "</b>");
Create an additional container for entering values into this content:
<div class="count">Money: <b>0</b></div>
And declare this content as a selector and then assign the value on click:
document.querySelector(".count b").textContent = money;
var money = 0;
function addMoney() {
money += 1;
document.querySelector(".count b").textContent = money;
}
<button type="button" onclick="addMoney()">Get a money</button>
<div class="count">Money: <b>0</b></div>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to add input fields to a page dynamically, when a user clicks a button.
I have the following code, which is being called, but doesn't work as expected
var a= document.getElementsByTagName("button");
a[0].addEventListener("click", clicked);
function clicked(){
var input = document.createElement("input");
document.appendChild("input");
}
The error I am facing is this:
"error"
"TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at HTMLButtonElement.clicked (sofodipabe.js:5:12)"
What is causing this issue?
Do you wish to use jQuery? If you are using jQuery you can follow my easy solution below other wise #kira-sen had provided good solution.
Here is the fiddle you may look at.
HTML
<input type="text" id="n" placeholder="How may elements to add">
<button id="addElements">Add elements</button> <br>
<div id="addElementsHere">
</div>
JS
$("#addElements").click(function(e){
var n = parseInt($(this).siblings("#n").val());
for(var i = 0; i<n; i++){
$("#addElementsHere").append("<input class='xyz' type='text' placeholder=' Enter value for input number " + (i + 1) + "' id='inp-"+(i+1)+"'>");
}
});
Hope this helps.
Try This
// Creating 10 Input textboxes
var div = document.createElement('div');
for(var i = 0; i < 10; i++) {
var inputElement=document.createElement('input');
inputElement.setAttribute('type','text');
inputElement.setAttribute('id','id' + i);
inputElement.value='My Value ' + (i+1);
div.appendChild(inputElement);
}
document.getElementById("container").appendChild(div);
// Adding class
var inputElements = document.querySelectorAll('input');
for(var i=0; i < inputElements.length; i++) {
inputElements[i].className='MyClass' + i;
// Getting value
console.log(inputElements[i].value);
}
<div id="container"></div>
You can use this as an example to do what you want.
var container = document.querySelector('#container')
for (var i = 0; i < 10; i++) {
var input = document.createElement('input') // create a new element
input.classList.add('input') // Add .input class to the created element
input.placeholder = 'Input ' + i // set an attribute
input.id = 'input' + i // set the ID
container.append(input) // Append the element to a parent element (container in this case)
}
.input {
width: 100%;
}
<div id="container"></div>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm very new to JavaScript and am attempting to make a simple maths game.
I'm holding the correct answer to my randomly generated maths questions in a variable named correctAnswer. I would like the value of this variable to be displayed in a button - so that when the user clicks it, they see a "Well done!" message.
This is what I've got so far - just the code to create my random questions:
var firstNumber;
var secondNumber;
var correctAnswer;
var userAnswer;
function additionQuestion() {
firstNumber = Math.floor(Math.random() * 10) + 11
secondNumber = Math.floor(1 + Math.random() * 9);
document.getElementById("additionQuestion").innerHTML = + firstNumber + " + " + secondNumber + " = ";
correctAnswer = (firstNumber + secondNumber);
}
Would anyone be able to help me with this?
Thanks in advance.
You can display value in a button, by accessing its value property.
For example you have a button like this
<input type="button" id="correct" />
you can display value in it like this:
document.getElementById("correct").value = correctAnswer;
use this line of code to change your button display text:
document.getElementById("yourButtonID").innerHTML= correctAnswer;
check this for more info: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
use jquery;
var yourVariable = 48;
$(document).ready(function(){
$('.your-button').data('answer', 48);
$('body').on('click', '.your-button', function(e){
if($(this).data('answer') === yourVariable){
alert('good answer');
}else{
alert('try again');
}
});
});
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to localStore the history but it does not work. I tried JSON.stringify and a script called JStorage but I couldn't get either to work.
function updateHistory(video) {
getHistory();
blacklist[video["id"]] = true;
myhistory.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
saveHistory();
}
function saveHistory() {
localStorage.setItem(myhistory, myhistory.innerHTML);
}
(The alert does show up)
function getHistory() {
localStorage.getItem(myhistory);
alert("working");
}
The point is, instead of storing the html part you better store the video object instead, you can store videos based on their id, and instead of array use javascript object:
function setVideo(video) {
var videos = JSON.parse(localStorage.getItem("myhistory") || "{}");
videos[video["id"]]=video;
localStorage.setItem("myhistory", JSON.stringify(videos));
}
function getVideos() {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return {};
else return JSON.parse(myhistory);
}
function getVideo(id) {
var myhistory = localStorage.getItem("myhistory");
if(!myhistory) return null;
var videos = JSON.parse(myhistory);
return videos[id] || null;
}
now you can use getVideo to retrieve the video object by id.you can separate the part which shows the video, like:
function showVideo(video) {
blacklist[video["id"]] = true;
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchHistoricVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myhistory").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
let's say you want to show the whole videos in the history:
var videos = getVideos();
for(var id in videos){
showVideo(videos[id]);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the following javascript code for a rotating image. Those images are in a separate folder from the javascript. I want to link the rotation itself to another page. All images will go to the same link. The current code works great but I just don't know where I add the a href code or its syntax.
// JavaScript Document
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
FirstPart = '<img src="domain/rotatingimages';
LastPart = '.gif" height="250" width="388">';
function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}
Try this format
<img src='image_src' border="0"/>
It is up to you if you want to define the target attribute in <a> tag.
// JavaScript Document
//
// Type the number of images you are rotating.
var numberOfImagesToRotate = 3;
// Edit the destination URl here
var linkUrl = 'example.html';
// HTML-partials
var imgFirstPart = '<img src="domain/rotatingimages';
var imgLastPart = '.gif" height="250" width="388" border="0">';
var anchorFirstPart = '<a href="';
var anchorSecondPart = '">';
var anchorLastPart = '</a>';
function printImage() {
var r = Math.ceil(Math.random() * numberOfImagesToRotate);
document.write(anchorFirstPart + linkUrl + anchorSecondPart + imgFirstPart + r + imgLastPart + anchorLastPart);
}