I'm trying to build a Trivia game, right now I've one question and 3 answers (radio buttons), the user will choose one answer and then click submit. If it's the wrong answer the button will show "Retry" instead of "Submit.
First I only started to learn Javascript and I'm pretty sure there's a simple/better way to use one button to submit and then "retry" if the answer is wrong. I just created two functions, first function() that will check the answer, if it's the wrong answer it'll jump to wrongAnswer() This function suppose to change the text of the button, changing the button onclick (so I can increase the number of "clicks") and will check if there's more than 1 click (if true: location.reload) I couldn't think on a better way to let the user try again answering the question (I made the other radio buttons gray after "wrong" answer).
Also why when I put
var clicks = 0; outside the function it's NaN... Why?
My main problem, the second click will give me this error instead of increasing the "clicks" (it's not defined on HTML but this's why I change the attribute as you can see in the code
Uncaught ReferenceError: wrongAnswer is not defined
at HTMLInputElement.onclick (index.html:1)
Though I can see on the button inspect that the onclick is now = wrongAnswer();
My HTML:
<input class="submit" id="mybtn" onclick="userChoose()" type="submit" value="Submit!">
<p>Clicks: <a id="clicks">0</a></p>
My javaScript:
function wrongAnswer() {
var clicks = 0; // for how many button clicks
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
var btn = document.getElementById("mybtn");
btn.value = 'Try again'; // Will just add a hidden value
btn.innerHTML = 'Try again'; // Even without inner it works ??? (not sure why)
btn.style.fontSize = "x-large"; // Made the text a little bit smaller
document.getElementById( "mybtn" ).setAttribute( "onclick", "wrongAnswer();" );
}
}
In the end I'll be happy if someone can explain what I did wrong and if there's a better way instead of doing this to reload the page by clicking the button again after "wrong answer".
if (clicks = 2){
location.reload;
}
If i understood your question here there is an example:
In this example i have a question and 3 radio buttons (answer1, answer2 and answer3).. if the user click on radio button1(answer1) he gets an alert with good job else an alert with retry and the button value is retry!. The user when click on the reTry the page is reload...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> test</title>
<style>
</style>
<script type="text/javascript">
function userChoose(){
//control the value button if it is submit or retry
let btn=document.getElementById('mybtn');
if(btn.value=="Submit!"){
//user have to answer
let answer= document.getElementById('answer1');
if(answer.checked){
alert('good job!');
}
else{
//wrong answer
alert("Retry!");
document.getElementById('mybtn').value="Tryagain!"
}
}
else{
//call function wrongAnswer()
wrongAnswer();
}
}
function wrongAnswer(){
location.reload();
}
</script>
</head>
<body>
<p>QUESTION....</p><br>
<div>
<input type="radio" name="answer" id="answer1" value="a1">answer1<br>
<input type="radio" name="answer" id="answer2" value="a2">answer2<br>
<input type="radio" name="answer" id="answer3" value="a3">answer3<br>
</div>
<br>
<input class="submit" id="mybtn" onclick="userChoose()" type="submit" value="Submit!">
</body>
</html>
Hope this helps
Related
I am trying to make an online questionnaire that will only show the next question after answering the current question. I am very new at this and trying to learn as I go. How do I make the 2nd set of buttons appear only when you answer yes to question 1?
<html>
Question 1
<p>
<button onclick="myFunction1()">Yes</button>
<script>
function myFunction1() {
document.getElementById("demo").innerHTML = "Yes on question 1, display question 2";document.getElementById("demo").style.color = "black";}
</script>
<button onclick="myFunction2()">No</button>
<script>
function myFunction2() { document.getElementById("demo").innerHTML ="No on question 1 negative answer to question 1 display negative response";document.getElementById("demo").style.color = "red";}
</script>
</html>
<p id="demo"></p>
</script>
</p></p></p>
</html>
<head>
<script>
function showImg() {
document.getElementById("map_img").style.display = "";
}
</script>
</head>
<body>
<button onclick="myFunction3()">Yes</button>
<script>
function myFunction3() { document.getElementById("demo2").innerHTML = "Yes to question 2";}</script>
</html>
<button onclick="myFunction4()">No</button>
<script>
function myFunction4() {
document.getElementById("demo2").innerHTML = "No to question 2";}
</script>
</body>
<p id="demo2"></p>
Use css display: none; to hide the second question, then when the user clicks the yes button, you change it to display:block;
Here is an example: https://jsfiddle.net/mrpbtbgy/2/
document.querySelector("#q1Btn").addEventListener("click",()=>{
document.querySelector("#question2").style.display="block";
});
In my opinion, you have to put your second, third and ... questions into div's tags with style="display:none"
When the users click on the Yes button, you can easily change the display to block and show the next question.
Another thing is that your html is not formatted well.
Here is an example of html.
<html>
<head>
</head>
<body>
<div>Your first question</div>
<div style="display:none" id="question2">Your second question</div>
<script>
You can put all your functions here
</script>
</body>
</html>
I did a very simple example for you, you can check on the following link:
https://jsfiddle.net/L7gp4c5g/
Hope to help you!
Put the what you want to hide in a div hidden:
<div id="question2" style="visibility: hidden">
<button onclick="onClick(2)">Yes</button>
<button onclick="onClick(2)">no</button>
</div>
Use javascript to programmatically hide or show next div:
<script>
function onClick(button) {
document.getElementById('question' + (button + 1)).style.visibility = "visible"
}
</script>
As other I would have said :
If you want to get the results at the end of all the questions. (if user leave, you won't get nothing.)
A solution would be to put each question in hidden divs, on the same page, displaying them after each validation. This way you won't need to put and remove content. Example:
function showquestion(number){
$("#question"+number).removeClass("hidden"); // Show the next question
$("#question"+(number-1)).addClass("hidden"); // Hide the current question
}
.hidden{display:none;
visibility : hidden;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="question1" class=""> Mauvaise réponse</div>
<div id="question1" class=""> Question 1 <button type="button" onclick="showquestion(0)">yes</button><button type="button" onclick="showquestion(2)">No</button></div>
<div id="question2" class="hidden"> Question 2 <button type="button" onclick="showquestion(0)">yes</button><button type="button" onclick="showquestion(3)">no</button></div>
<div id="question3" class="hidden"> Question 3 <button type="button" onclick="showquestion(0)">yes</button><button type="button" onclick="showquestion(4)">no</button></div>
But we forgot the "yes / no" part, nor talk about the visibility of the question solution inside the source code.
The correct way of doing this would be an ajax call on each question validation : The user send the response to a php script, this script validate the response, or not, then send the content that will be inserted on the user page.
It's the only way for the user don't cheat, and it allow you to save his response on each step (if you save something).
Please look at the following code:
**page.html**:
<!DOCTYPE html>
<html>
<head>
<title> Playing with JavaScript </title>
<script src="myjs.js"> </script>
</head>
<body id="body">
<ul id="mylist">
<li> David </li>
<li> Aharon </li>
</ul>
<form>
<input type="text" name="user_input"> <br>
<button onclick="add_item(user_input.value)"> add_item </button>
</form>
</body>
</html>
**myjs.js**
function add_item(user_input) {
var new_li = document.createElement("li");
var new_text = document.createTextNode(user_input);
new_li.appendChild(new_text);
document.getElementById("mylist").appendChild(new_li);
}
This code creates a list of two names and displays a button and an input line. Once the user enters a new name in the input line and clicks the button, the new name is supposed to be added to the list.
It happens for a very short period of time and then the new element in the list disappears. Do you know what can I change in the code so the new element in the list will stay permanently?
I think it's because your form is submited and page is reload
add a type="button" at your button
Working Example
function add_item(user_input) {
var new_li = document.createElement("li");
var new_text = document.createTextNode(user_input);
new_li.appendChild(new_text);
document.getElementById("mylist").appendChild(new_li);
}
<form>
<input type="text" name="user_input"> <br>
<button type="button" onclick="add_item(user_input.value)"> add_item </button>
</form>
<ul id="mylist"></ul>
<button> element have 3 type :
submit : default type if no type are specified who submit a form
reset : who reset/clear input in a form
button : no specific action
I imagine the page is reloading because your button element is a submit button inside a form - when no type attribute is specified for a button it becomes a submit button by default. Your form doesn't have an action specified so submitting reloads the current page.
Add type="button" to the button.
That will mean that the button has no default behaviour and does only what the JS does explicitly.
I'm new to JavaScipt and HTML and only need it as a side issue. I have some buttons and I want their backround color to change after clicked. That I could solve partly with:
<input class="choice" onclick="this.style.background='blue';" type="submit" value='V' id='0' />
However, when the button is clicked a second time it should change back. Preferably would be a one line statement like above. Would appreciate any help.
I broke your code out into seperate JS, it's cleaner that way and easier to maintain.
If you disable the button, then it stops recieving click events. I assume that's not what you want.
Here, I've made it so that when the button is clicked, it toggles the background color between red and blue.
http://jsbin.com/huqoyixuhe/edit?html,css,js,output
// select the button
var input = document.querySelector('input.choice');
// add a click event listener
input.addEventListener('click', function () {
// if the button is red, make it blue
if (this.style.background === 'red') {
this.style.background = 'blue';
}
// otherwise, it is already blue, so make it red!
else {
this.style.background = 'red';
}
});
EDIT
here, as a one-liner:
http://jsbin.com/bolowuceqa/edit?html,output
<input class="choice" onclick="this.style.background==='red' ? this.style.background = 'blue' : this.style.background = 'red'" style="background:red;" type="submit" value='V' id='0' />
You can use toggole between class Name through pure javascript.
HTML:
<button id="toggole" class="red" onclick="toggolecolor()">
Click Please
</button>
CSS:.red{
background-color:red;
}
.blue{
background-color:blue;
}
Javascript:
function toggolecolor(){
var element = document.getElementById("toggole");
element.classList.toggle("red");
element.classList.toggle("blue");
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<body bgcolor="(color)"/>
How do you replace a button with whatever words were on the button before? I was looking at an answer to another similar question, which said to use something like:
var myBtn = document.getElementById("buttonId"),
mySpan = document.createElement("span");
mySpan.innerHTML = myBtn.innerHTML ;
myBtn .parentNode.replaceChild(mySpan, myBtn);
but that had made what other buttons do change. Does anyone know another way to change a button to regular text?
I know that that code works just by itself, but it doesn't work with my code for some reason, so I don't really care what's wrong with that code. I'm just wondering if anyone knows another way to do it.
Thanks
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<div id="myDiv">
<input type="button" value="Change into Text" id="submit" onClick="change()"> <!--button input that will trigger an event named change-->
</div>
</body>
</html>
<script type="text/javascript">
function change(){ //function to run when you click on the button...
var buttonValue = document.getElementById("submit").value; //stores the button value
document.getElementById("myDiv").innerHTML = buttonValue; // displays the value as a plain text inside "myDiv" - removing the button input entirely
}
</script>
EDIT:
I've just noticed you had multiple buttons in your page, which will make my previous example wrong. heres something that will make you work easier i think in case you will add extra buttons:
first heres the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<li id="id_1"><input type="button" value="Change into Text" onClick="change(1)" id="button_1"></li>
<li id="id_2"><input type="button" value="Change into Text" onClick="change(2)" id="button_2"></li>
<li id="id_3"><input type="button" value="Change into Text" onClick="change(3)" id="button_3"></li>
</ul>
</body>
</html>
<script type="text/javascript">
var id;
function change(id){
var buttonValue = document.getElementById("button_"+id).value;
document.getElementById("id_"+id).innerHTML = buttonValue;
}
</script>
In the HTML part, you can create a list (li) of buttons if that's your layout...
each list will have its own id, in this case id_x that will be used later when you replace its content. each button calls a function change(id) while id is just a unique number for each button.
In the JS part, the change(id) gets the id of the button that was clicked, takes its value, and replaces the innerHTML (content) of the relative list items with a plain text.
Let me know if you still need any other help.
Seems that you are looking for another way to replace the buttons with plain text, well I'll show you the jQuery way.
HTML
<div>
<button id="btn1" class="change-button">A button with some text 1</button>
<button id="btn2" class="change-button">A button with some text 2</button>
<button id="btn3" class="change-button">A button with some text 3</button>
</div>
jQuery
// When we click a button with a "change-button" class
$(".change-button").on("click", function(event){
// First we get the ID value of the clicked button
// example: "btn2"
var buttonId = $(this).attr('id');
// Then we get the html value of the clicked button
// example: "A button with some text 2"
var buttonText = $(this).html();
// We use the function replaceWith, to replace the button to a <span>
// with the buttonText variable we have
$('#' + buttonId).replaceWith("<span>" + buttonText + "</span>");
});
As you can see, it's a lot more cleaner with jQuery. You should try it!
Here is the fiddle so you can test it.
<html>
<script>
function fun()
{
var a = document.getElementById("hello").value;
document.getElementById("ad").innerHTML = a;
}
</script>
<body>
<div id="ad">
<input type="button" value="hello" id="hello" onClick="fun()">
</div>
</body>
</html>
sorry, edited the wrong post
I want to disable link button after clicking of it & other enable. toggle enable/ disable between both link buttons using javascript
<a id="a1" href="page1.aspx">One</a><a id="a2" href="page2.aspx">Two</a>
Simple, just add listeners to the onclick events on both links, that disable the link in question and enable the other one.
Something like
document.getElementById('a1').onclick = function() {
document.getElementById('a1').disabled = true;
document.getElementById('a2').disabled = false;
};
document.getElementById('a2').onclick = function() {
document.getElementById('a2').disabled = true;
document.getElementById('a1').disabled = false;
};
Of course if you're going to be extending this to multiple buttons then you could easily abstract the above out to registration methods, looping over arrays of buttons etc. (possibly those that implement a particular class rather than explicitly specifying the array).
The simplest way is to hide the link rather than to make it disabled.
You can use this code to hide the link after click on it.
Its tested code & it worked perfect for me. :-)
<script type="text/javascript">
onclick = function() {
var chk= document.getElementById('myElementId');
chk.style.display="none";
};
</script>
To disable a LINK rather than a BUTTON, the only thing you can do apart from hiding it is to set it not to go anywhere.
onclick="this.href='javascript: void(0)';"
Your question can have any one of the following 3 possible scenario. Choose whichever suites your problem.
Case1) A catch in your question is that since they are links pointing to page1.aspx and page2.aspx respectively once you click on a link a new page loads in the browser. So the effect you want to achieve doesn't really matter.
Case 2) If, you have both the links 'One' and 'Two' on each of aspx pages then you can as well hardcode the disabling of the link pointing to itself. (Or as well not have the link at all).
Case 3) If you have a frame to display the links 'One', 'Two' and you have a another frame to load content of both links then your question has a meaning disabling the other link. Here is the code for the same.
<html>
<a id="a1" href="javascript:void(0)" onclick="toggle(objA1,objA2,'page1.aspx')">One</a>
<a id="a2" href="javascript:void(0)" onclick="toggle(objA2,objA1,'page2.aspx')">Two</a>
<br><iframe id="ifrm" src=""></iframe>
<script>
var objA1 = document.getElementById('a1');
var objA2 = document.getElementById('a2');
// d=element to disable, e=element to enable
function toggle(d,e,link)
{
//if already disabled do nothing(don't follow url)
if(d.disabled) return;
//enable/disable
d.disabled = true;
d.style.cursor = 'default';
e.disabled = false;
e.style.cursor = 'hand';
//follow link
ifrm.src = link;
}
</script>
</html>
You can access and set the "disabled" attribute like this:
if(somebutton.disabled == true){
somebutton.disabled = false;
}
I recommend using a JavaScript framework like jQuery.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<style type="text/css">
.submit{
padding:8px;
border:1px solid blue;
}
</style>
</head>
<body>
<h1>Disabled submit form button after clicked with jQuery</h1>
<form action="#">
<p>
I'm a form ~
</p>
<input type="submit" value="Submit"></input>
<button>Enable Submit Button</button>
</form>
<script type="text/javascript">
$('input:submit').click(function(){
$('p').text("Form submiting.....").addClass('submit');
$('input:submit').attr("disabled", true);
});
$('button').click(function(){
$('p').text("I'm a form ~").removeClass('submit');
$('input:submit').attr("disabled", false);
});
</script>
</body>
</html>
<script type="text/javascript">
function validateForm(formObj) {
if (formObj.username.value=='') {
alert('Please enter a username');
return false;
}
formObj.submitButton.disabled = true;
formObj.submitButton.value = 'Please Wait...';
return true;
}
</script>
<form name="frmTest" action="" method="post" onsubmit="return validateForm(this);">
Username: <input type="text" name="username" value="" /><br />
<input type="submit" name="submitButton" value="Submit" />
</form>