im trying to change a line of text if a link is clicked, however it doesnt seem to be calling my script to change it.
<script >
var paragraphToChange = document.getElementById("q1");
paragraphToChange.innerHTML ="Quotation is by:" + Antole France
</script>
<div id="body">
<p>javascript.html - JavaScript page</p>
<a href id="q1">Quotaion is by:</a>
</div>
What you're trying to accomplish is probably something like this:
HTML
<div id="q1">
<a onClick="javascript:clickFunction()">Quotation is by</a>
</div>
JavaScript
clickFunction = function() {
document.getElementById("q1").innerHTML = "<a href='http://www.quotationspage.com/quote/1463.html'>Antole France</a>";
}
JSFiddle
Sir you have to set the value of "newValue" to the quotation.
var newValue = '"Quotation is by:" + Antole France'
paragraphToChange.innerHTML = newValue;
You are missing the click event on the Html tag. Hence, this paragraphToChange.innerHTML ="Quotation is by:" + Antole France"
never gets call.
Why don't you start with this example first:
<p id="display"></p>
<button onclick="displayBob">Bob</button>
<button onclick="displayTom">Tom</button>
<script>
displayBob = function ()
{
document.getElementById("display").innerHTML = "Hello Bob";
}
displayTom = function ()
{
document.getElementById("display").innerHTML = "Hello Tom";
}
</script>
Related
I'm generating a dynamic list of from/inputs and buttons from JSON. The button triggers a JavaScript function that reads the current content of the input in a form. However when the button is clicked I get the following error code Uncaught TypeError: Cannot read property '0' of undefined.
This tells me there are no elements in the form but I don't know why. Tryed 0-3 just to make sure.
Length also return undefined. I am able to edit the innerHTML of the form.
A striped down code I'm trying to get a value from.
<!DOCTYPE html>
<html>
<body onload="gen_form()">
<div id="connectResult"></div>
<p id="demo">RESULT HERE</p>
<script>
const connect_result = document.getElementById("connectResult");
function gen_form(){
var div = document.createElement("DIV");
div.setAttribute("id", "div0");
div.innerHTML += "sometxt<br/>";
var form1 = document.createElement("FROM");
form1.setAttribute("id", 'form_sometxt2_0');
var input1 = document.createElement("input");
input1.setAttribute("type",'text');
input1.setAttribute("name",'textbox');
form1.appendChild(input1);
div.appendChild(form1);
var btn4 = document.createElement("BUTTON");
btn4.setAttribute("id", 'WRITE_sometxt2_0');
btn4.innerHTML = 'WRITE';
btn4.setAttribute("onclick", "myFunction(this)");
div.appendChild(btn4);
connect_result.appendChild(div);
}
function myFunction(param) {
var text = document.getElementById("form_sometxt2_0").elements[0].value + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
</html>
The following does exactly what I want but it is static. The above is based off this.
<!DOCTYPE html>
<html>
<body>
<form id="frm1">
<input type="text">
</form>
<button onclick="myFunction()">Try it</button>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var text = document.getElementById("frm1").elements[0].value + "<br>";
document.getElementById("demo").innerHTML = text;
}
</script>
</html>
My question is: What is the difference between these two code snippets and how do I fix said error?
I would prefer not to use a submit input as there will be a second button that edits the contents of the input value.
PS: I'm fairly new to JavaScript and its terminology.
Using Chrome as my debugger.
Tipo error.comment
var form1 = document.createElement("FROM");
should be:
var form1 = document.createElement("FORM");
I have the following piece of code, which changes one line of text in a click of a button:
<!DOCTYPE html>
<html>
<body>
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'This is JavaScript!'">
Click Me!</button>
</body>
</html>
This is quite easy since there is no script, no function needed to handle the button. Now, I want this same button to change back to the first content when I click it again. I assume that now I need to have a function, but not sure how to write it. An ideas?
You don't have to use a function. You could do it with a ternary operator ? and :, or you could even just write an if else statement all on one line.
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML === 'This is JavaScript!' ? document.getElementById('demo').innerHTML = 'Watch this HTML content changes..' : document.getElementById('demo').innerHTML = 'This is JavaScript!';">
Click Me!</button>
However, that is a lot of code to cram into one line and it would be much cleaner in a separate function, as such.
function changeText() {
var demo = document.getElementById('demo');
if (demo.innerHTML === 'This is JavaScript!') {
demo.innerHTML = 'Watch this HTML content changes..';
} else {
demo.innerHTML = 'This is JavaScript!';
}
}
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Well. Although the way you are trying is not the best practice.... But the following way will give you some hope. try to do more research.
function myFunction() {
var x=document.getElementById("demo").innerHTML;
if(x=="A Paragraph."){
document.getElementById("demo").innerHTML="Back Again";}
if(x=="Back Again")
document.getElementById("demo").innerHTML="A Paragraph.";
}
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
More simply, this function works:
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Javascript:
function changeText() {
e = document.getElementById('demo');
e.innerHTML = e.innerHTML == "Watch this HTML content changes.." ? "This is JavaScript!" : "Watch this HTML content changes..";
}
You can see it working at this JS Fiddle: http://jsfiddle.net/0yLb4a3j/
You can have something like a toggle function:
<script type="text/javascript">
function toggleContent() {
var message1 = "This is JavaScript!";
var message2 = "Watch this HTML content changes..";
var element = document.getElementById('demo');
if (element.innerHTML===message1)
element.innerHTML = message2;
else
element.innerHTML = message1;
return false;
}
</script>
You get it called by setting onclick="toggleContent();" on the button.
You could use an IIFE, an array, an incremented counter, and a modulo operator to achieve this.
document.getElementById('button').onclick = (function(){
var demo = document.getElementById('demo');
var text = [demo.textContent,'This is JavaScript!'];
var count = 0;
return function() {
demo.textContent = text[++count % 2];
}
})();
<p id="demo">Watch this HTML content changes..</p>
<button type="button" id="button">Click Me!</button>
var btn = document.getElementById("<btn_id>");
var previous = "";
btn.addEventListener("click", clickHandler);
function clickHandler() {
var demo = document.getElementById("demo");
if (!previous) {
previous = demo.innerHTML;
} else {
demo.innerHTML = "This is JS";
btn.removeEventListener("click", clickHandler);
}
}
first of all , you ll need to do the code in a seperate script, in brief , append the intial text to the div then wheck button clicked, change it to second text, and according to your question you ll need a second button who will change the div text to the intial text , logically that ll give something like tht :
<script>
window.onload = function(){
document.getElementById('demo').innerHTML = 'Watch this HTML content changes..'
}
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = 'This is JavaScript!'
};
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = ''Watch this HTML content changes..'
};
</script>
Im trying to make an 'online' (HTML document) file that has an input to solve math, and I need a way to type in the numbers, and insert a 'solve me' button. I have the button, and the form by ID and class as well.
This is what I inserted into a "try it" prompt box through w3schools.com site, tried looking almost everywhere within that site to try to input it in.
<div id="A"></div>
<div id="B"></div>
<script>
var A = 1;
var ele = document.getElementById('A');
var y = 2;
var z = A + y;
document.getElementById("demo").innerHTML = z;
</script>
Is there a way to do this? And thank you guys for your help!
<!DOCTYPE html>
<html>
<body>
<input id="A"/>
<input id="B"/>
<div id="demo"></div>
<button onclick="add();">ADD</button>
<script>
function add () {
var A = document.getElementById('A').value *1;
var B = document.getElementById('B').value *1;
var z = A + B;
document.getElementById("demo").innerHTML = z;
}
</script>
</body>
</html>
Hope this helps you, here you need to use input to have a user editable field,a div as you guessed to display your answer and button which triggers some logic.
Very new to html and javascript here. I get the following form up and it calculates correctly but the result shows up in a new page. I'd like it to stay in the same page. Not sure what I did wrong here. Also, is there any way to shorten the function? Seems like a lot of work to do a simple calculation. Any help would be great.
<html>
<head>
<title>Help!</help>
<script type="text/javascript">
function add(x,y){
var x = document.add1.add2.value;
var y = document.add1.add3.value;
var x = Number(x);
var y = Number(y);
var z = x+y;
return (z);
}
</script>
</head>
<body>
<h3>Help me stack overflow you're my only hope!</h3>
<form name="add1">
Input first number to add: <input type="number" name="add2">
2nd number: <input type="number" name="add3">
<input type="button" value="Result"
onclick = "document.write('The total is: ' + add() + '.');" />
</body>
</html>
Dont' use document.write to display data, it overwrites entire document. You don't want that. It's better to create new function which would render result into some other element:
<input type="button" value="Result" onclick="showResult('The total is: ' + add() + '.');" />
and the showResult function can be for example:
function showResult(result) {
document.getElementById('result').innerHTML = result;
}
HTML:
<div id="result"></div>
Demo: http://jsfiddle.net/7ujzn35c/
Here are also a couple of general improvements you can make your code:
move string manupulations to showResult completely:
<input type="button" value="Result" onclick="showResult()" />
http://jsfiddle.net/7ujzn35c/1/
call add from inside showResults
onclick="showResult(this.form.add2.value, this.form.add3.value)"
http://jsfiddle.net/7ujzn35c/2/
<title>Help!</help>
First of all, This should be <title> Help! </title>
Secondly, document.write function actually starts writing the entire page anew.
You should either replace onclick = "document.write('The total is: ' + add() + '.');" with
onclick = "alert('The total is: ' + add() + '.');"
Better still, you could create a div element like so
<title> Help! </title>
<script>
.....
</script>
</header>
<body>
<div id = 'output'> </div> ...
then
`onclick = "document.getElementById("output").innerHTML = 'The total is: ' + add() + '.';"
And don't give up. Hope this helps you
I am making a puzzle website where you select a puzzle, I was wondering if there was a way of, instead of it being in pop up boxes it would be printed to the website. I don't mind what code we are using as I am fluent in most,
This is the code I have so far:
<body>
<script type="text/javascript">
function myFunction()
{
function ask() {
var a = (Math.round(Math.random()*1000000))
alert (a)
return prompt("What was the number?") == eval( a );
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction()">Remember the number</button>
</body>
<body>
<script type="text/javascript">
function myFunction2(){
function ask() {
var a = Math.floor(Math.random() * 10) + 1;
var b = Math.floor(Math.random() * 10) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random()*4)];
return prompt("How much is " + a + " " + op + " " + b + "?") == eval( a + op + b);
}
var questions = [ask(), ask(), ask(), ask(), ask()],
total = questions.length,
correct = questions.filter(Boolean).length;
alert( "You got "+correct+"/"+total+" correct");
}
</script>
<button onClick="myFunction2()">Quick math</button>
</body>
</html>
</html>
So I was wondering if there was a way to make it show up as text and have a text box on the page to type into that would still work. And the design is able to be changed, so I can make a larger text box, or a larger font so it's not just an un-editable onclick.
All help greatly appreciated.
Thanks.
I did what I thought that you wanted to the "Remember the number" button click.
Sorry, had no time to do the other one.
HTML:
<body>
<button id="rmbrBtn">Remember the number</button>
</body>
<body>
<button id="quivkBtn">Quick math</button>
<div id="question_area">
</div>
</body>
</html>
</html>
JS & jQuery code:
$("#rmbrBtn").click(function()
{
// Answers collection
var questions = [];
// Check the correctness of the answer
function checkAnswer (){
total = questions.length,
correct = questions.filter(Boolean).length;
if(total < 5)
{
ask();
}else{
var answer = '<div>You got '+correct+'/'+total+' correct <input type="button" value="Ok" id="ansOk"/></div>';
$("#question_area").append(answer);
$("#ansOk").click(function(){
$(this).parent().empty();
$(this).parent().remove();
});
}
}
// Get the question
function ask() {
var a = (Math.round(Math.random()*1000000));
// View the generated number
var viewNumber = '<div>'+a+'<input type="button" id="ok" value="OK"/>'+'</div>';
// Prompt user with a text box
var promptVal = '<div>Enter your value: <input type="text" id="ans" /> <input type="button" id="prmtOk" value="Ok"/></div>';
// Append
$("#question_area").append(viewNumber);
$("#ok").click(function(){
$(this).parent().empty();
$(this).parent().remove();
$("#question_area").append(promptVal);
$("#prmtOk").click(function(){
var prmt = $("#ans").val();
var addVal = prmt == a;
questions.push(addVal);
checkAnswer();
$(this).parent().empty();
$(this).parent().remove();
});
});
}
// Run the function.
checkAnswer();
});
Online solution:
JSFiddle
Try to do the other one same as this.
Sorry had no time to comment also.
I think you can figure this out.
Just add a div at the top of your page and use jqueries .html() and you will be done
like
$('.header').html('You are correct.');
here is a fiddle http://jsfiddle.net/AMISingh/8nWKD/3/
This can also be done without JQuery and just JavaScript.
http://jsfiddle.net/8nWKD/4/
<div id="header" class="header">This is the header</div>
<div class="button" onClick="test_click()"> Click me!</div>
and the JavaScript
function test_click()
{
document.getElementById("header").innerHTML = "CORRECT!";
}