I'm trying to build an interactive text with Javascript. I can do it by using a new function each element I create, but if I do that I'll have too many functions.
Could somebody tell me what is wrong with the following code and what I should do so it works?
Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>
<p>Name:</p>
<button id="peter" onclick="includeName1(peter)">Peter</button>
<button id="paul" onclick="includeName1(paul)">Paul</button>
<p>Wife's name</p>
<button id="mary" onclick="includeName2(mary)">Mary</button>
<button id="emma" onclick="includeName2(emma)">Emma</button>
<p>How long have you been married?</p>
<input id="years" type="number" oninput="includeTime()">
</div>
<br/>
<div>
<p>My name is <span id="name1"></span>. I'm married to <span id="name2"></span>. We've been married for <span id="time"></span> years.
</p>
</div>
<script>
function includeName1(manName){
if (manName == "peter") {
document.getElementById("name1").innerHTML = "Peter";}
else if (manName == "paul") {
document.getElementById("name1").innerHTML = "Paul";
}
}
function includeName2(womanName){
if (womanName == "mary") {
document.getElementById("name2").innerHTML = "Mary";}
else if (womanName == "emma") {
document.getElementById("name2").innerHTML = "Emma";
}
}
function includeTime(){
var x = document.getElementById("years").innerHTML;
document.getElementById("time").innerHTML = x;
}
</script>
</body>
</html>
You need to wrap the names in apostrophes, at the moment you're trying to pass an object called 'peter' to the function. On the input, you need to use value instead of innerHtml.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>
<p>Name:</p>
<button id="peter" onclick="includeName1('peter')">Peter</button>
<button id="paul" onclick="includeName1('paul')">Paul</button>
<p>Wife's name</p>
<button id="mary" onclick="includeName2('mary')">Mary</button>
<button id="emma" onclick="includeName2('emma')">Emma</button>
<p>How long have you been married?</p>
<input id="years" type="number" oninput="includeTime()">
</div>
<br/>
<div>
<p>My name is <span id="name1"></span>. I'm married to <span id="name2"></span>. We've been married for <span id="time"></span> years.
</p>
</div>
<script>
function includeName1(manName){
if (manName == "peter") {
document.getElementById("name1").innerHTML = "Peter";}
else if (manName == "paul") {
document.getElementById("name1").innerHTML = "Paul";
}
}
function includeName2(womanName){
if (womanName == "mary") {
document.getElementById("name2").innerHTML = "Mary";}
else if (womanName == "emma") {
document.getElementById("name2").innerHTML = "Emma";
}
}
function includeTime(){
var x = document.getElementById("years").value;
document.getElementById("time").innerHTML = x;
}
</script>
</body>
</html>
For the record...
this code should be more readable on this way:
const inTexts = document.getElementById('interractiv-texts')
, outText = document.getElementById('Out-Text')
, tVals = { man: '', wife: '', years: '' }
;
const setText = e =>
{
if (!e.target.matches('[data-part]')) return
tVals[e.target.dataset.part] = e.target.value
outText.textContent = `My name is ${tVals.man}, I'm married to ${tVals.wife}. We've been married for ${tVals.years} years.`
}
inTexts.oninput = setText
inTexts.onclick = setText
<div id="interractiv-texts">
<p>Name:</p>
<select data-part="man">
<option value="Peter">Peter</option>
<option value="Paul">Paul</option>
<option value="John">John</option>
</select>
<p>Wife's name</p>
<button value="Mary" data-part="wife">Mary</button>
<button value="Emma" data-part="wife">Emma</button>
<p>How long have you been married?</p>
<input data-part="years" type="number" >
</div>
<p id="Out-Text"></p>
Related
I'm trying to make a quiz, here is the html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>English Test</title>
<link rel="stylesheet" href="testCss.css">
</head>
<body>
<br>
<div style="font-size:20px">
<p>Please choose the correct answer and at the end tap the score button. </p>
<br>
<div>
2. I
<select id="question2">
<option value="_">_</option>
<option value="Am">am</option>
<option value="Is">is</option>
<option value="Are">are</option>
</select>
22 years old.
<span id="question2_answer"></span>
</div>
<br>
<br>
<div>
101. When can we meet again?
<span id="question101_answer"></span>
<div>
<input type="radio" name="question101" > When are you free?<br>
<input type="radio" name="question101" > It was two days ago. <br>
<input type="radio" name="question101" > Can you help me?
</div>
</div>
<br>
<br>
<div>
8. What is your father like?
<span id="question8_answer"></span>
<div>
<input type="radio" name="question8" > He likes listenning to music.<br>
<input type="radio" name="question8" > He likes to play football. <br>
<input type="radio" name="question8" > He is friendly.<br>
<input type="radio" name="question8" > He has a car.
</div>
</div>
<br>
<br>
<button id="button1" class="button" onclick="viewScore()">Score Result</button>
<br>
<input type="text" id="grade1" value="" readonly>
<br>
<script src="testJs.js"></script>
and here is the testJs.js that i used:
var score = 0;
function viewScore() {
var answer2 = document.getElementById("question2").value;
var answer8 = document.getElementsByName("question8");
var answer101 = document.getElementsByName("question101").value;
if (answer2 == "Am") {
document.getElementById("question2_answer").style.color = "green";
document.getElementById("question2_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question2_answer").style.color = "red";
document.getElementById("question2_answer").innerHTML = "✖ Wrong!";
}
if (answer8[2].checked) {
document.getElementById("question8_answer").style.color = "green";
document.getElementById("question8_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question8_answer").style.color = "red";
document.getElementById("question8_answer").innerHTML = "✖ Wrong!";
}
if (answer101[0].checked) {
document.
getElementsById("question101_answer").style.color = "green";
document.getElementsById("question101_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementsByID("question101_answer").style.color = "red";
document.getElementsByID("question101_answer").innerHTML = "✖ Wrong!";
}
if (score<=5) {
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Elementary.";
} else if(score<=8){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Pre Intermediate.";
}else if(score<=15){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Intermediate.";
}else{
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Upper Intermediate.";
}
console.log(score);
score = 0;
}
However, I'm getting following error on question 101. I check it several times and I have no idea where does this error coming from ! It refers to question 101 and mentions cannot read property '0' of undefined.
Thanks for any help in advance.
testJs.js:26 Uncaught TypeError: Cannot read property '0' of undefined
at viewScore (testJs.js:26)
at HTMLButtonElement.onclick (testHTML.html:57)
This is happening because in this line:
var answer101 = document.getElementsByName("question101").value;
you are putting the value of the input (which is NULL or UNDEFINED because the HTMLCollection returned by getElementsByName (note the plural) doesn't have a value property) into the var answer101 and NOT the input itself.
To fix this, change the above line to:
var answer101 = document.getElementsByName("question101");
You have to select array (not value) for var answer101
var answer101 = document.getElementsByName("question101");
And correct if content for answer101
if (answer101[0].checked) {
document.getElementById("question101_answer").style.color = "green";
document.getElementById("question101_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question101_answer").style.color = "red";
document.getElementById("question101_answer").innerHTML = "✖ Wrong!";
}
I'm working on a tax calculator using HTML and Javascript. It needs to accept two user inputs ("Total owed" and "Your payment") and calculate what percentage "Your payment" is of "Total owed". Then they should be displayed within the "answerParagraph" tag. What is the best way to do this?
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text">
</div>
<button onclick="handlers.getPercentage()">Get percentage</button>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
var taxes = {
getPercentage: function(total, payment) {
var percentage = (Math.floor((payment / total) * 100));
},
}
var handlers = {
getPercentage: function() {
var totalInput = document.getElementById('totalInput');
var paymentInput = document.getElementById('paymentInput');
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
}
}
</script>
</body>
</html>
You have to return the answer from taxes.getPercentage function
getPercentage: function (total, payment) {
var percentage = (Math.floor((payment / total) * 100));
return percentage;
}
And display in your answerParagraph. So, in handlers.getPercentage :
...
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
answerParagraph.innerHTML = answer;
the following modified code should work
var taxes = {
getPercentage: function(total, payment) {
var percentage = (Math.floor((payment / total) * 100));
return percentage
},
}
var handlers = {
getPercentage: function() {
var totalInput = document.getElementById('totalInput');
var paymentInput = document.getElementById('paymentInput');
var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
document.getElementById('answerParagraph').innerHTML = answer
}
}
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text">
</div>
<button onclick="handlers.getPercentage()">Get percentage</button>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
</script>
</body>
</html>
You can leave out the button if you trigger the calcpercentage() function by the keyup-event on either of the two input fields:
// define shorthand notation byId(id):
const byId=id=>document.getElementById(id);
// delegated event binding: affects INPUT elements only
byId('getPercentage').addEventListener('keyup',function(ev){
if(ev.target.tagName!='INPUT') return false;
byId('answerParagraph').innerHTML=
(byId('paymentInput').value*100 /
byId('totalInput').value).toFixed(2)+"%";
});
// trigger event manually ...
byId('totalInput').dispatchEvent(new Event('keyup',{bubbles:true}));
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="getPercentage">
<div id="total">
Total owed:
<input id="totalInput" type="text" value="1000">
</div>
<div id="payment">
Your payment:
<input id="paymentInput" type="text" value="25">
</div>
</div>
<div>
<p id="answerParagraph">
</p>
</div>
<script>
</script>
</body>
</html>
I have a form that asks for info about employees, their name, age, position and details, this then has to be added to a div when a "Add Record" button is pressed.
Currently I have the Object Constructor setup but i'm a little lost on how to push the details to the div and how i should write the function to do so, previously i used a Canvas to display it.
Here's my HTML
<!DOCTYPE html>
<html>
<head>
<title>52DA session 5</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../css/employee_styles.css"/>
</head>
<body>
<div id="container">
<header>
<h1 id="heading" class="blueTxt">Employee Records</h1>
</header>
<div class="left">
<form>
<fieldset>
<legend><h2>Employee Details Entry</h2></legend>
<p class=><label>Name: <input class="text" type="text" id="name" /></label></p>
<p><label>Age: <input class="text" type="text" id="age" /></label></p>
<p><label>Position: <input class="text" type="text" id="position" /></label></p>
<p><label>Details: <textarea type="text" id="details" maxlength="114" ></textarea></label></p>
<input class="button" type="button" id="addRecord" onclick="" value="Add Record"/>
</fieldset>
</form>
<div class="sort">
<h3>Sort</h3>
<button class="button" id="sortByName">By Name</button>
<button class="button" id="sortByAge">By Age</button>
<br/><button class="button" id="reset">Reset Details</button>
<br /><br />
</div>
</div>
<section>
<div id="employeeRecords">
</div>
</section>
</div>
<script src="../js/employee_script.js"></script>
</body>
</html>
and here's my Javascript:
var employees = [];
//--------------------------------------------------------------------------------------------------------------
function Person(name, age, pos, dtls, img){
this.fullName = name;
this.employeeAge = age;
this.position = pos;
this.details = dtls;
this.avatarSrc = img;
this.createProfile = function(){
var profile = document.createElement("div");
profile.className = "profileStyle";
var avatar = document.createElement("img");
avatar.src = this.avatarSrc;
avatar.alt = this.fullName();
profile.appendChild(avatar);
var profileTxt = document.createElement("p");
profileTxt.innerHTML = "<b>" + this.fullName() +
"</b><br />" + this.age +
"</b><br />" + this.pos +
"</b><br />" + this.dtls;
profile.appendChild(profileTxt);
return profile;
}
employees.push(this);
}
for(var i=0; i < staff.length; i++){
document.getElementById("staff_list").appendChild(staff[i].createProfile());
}
//-----------------------------------------------------------------------------------------------------------
function compareNames(a, b){
var nameA = //TODO - needs to refer to the employee name
var nameB = //TODO - needs to refer to the employee name
var result = 0;
if (nameA < nameB){
result = -1;
}
else if(nameA > nameB){
result = 1;
}
return result;
}
//--------------------------------------------------------------------------------------------------------------
function sortName(){
}
//--------------------------------------------------------------------------------------------------------------
function sortAge(){
}
//--------------------------------------------------------------------------------------------------------------
function addRecord(){
}
//--------------------------------------------------------------------------------------------------------------
function writeRecords(){
//--------------------------------------------------------------------------------------------------------------
function resetArray(){
}
//--------------------------------------------------------------------------------------------------------------
function arrayButtons(){
}
I understand there's probably a lot of simple mistakes and stuff missing but i'm really having trouble grasping this,
Kind regards
I have developing a quiz app in JavaScript and the problem is the questions are not iterating through. In other words, after a user takes the first question by clicking a multiple choice answer and then clicking next button, it does not go to the next question, simultaneously, JS does not recognize I answered the question via Answer the question! being the only output from the if conditional.
$(function (){
startQuiz();
answerResponse();
answerSubmitted();
renderQuestionPage();
});
const data = {
questions:[
// this is object 1 but we won't name it because it is inside an array
{
question: 'Question 1 what is that thing?',
answers:[
'this 1',
'that 2',
'something 3',
'allodat 4'
],
correctAnswer: 'allodat 4'
},
// this is object 2 but we won't name it because it is inside an array
{
question: 'Question 2 what is that other thing?',
answers: [
'bloop',
'dope',
'FIRE',
'HOTZ'
],
correctAnswer: 'dope'
}
],
currentQuestionIndex: 0,
totalScore: 0,
startedQuiz: false,
};
function resetQuiz(){
data.totalScore = 0;
data.currentQuestionIndex = 0;
}
function renderQuestionPage() {
var currentQuestionObj = data.questions[data.currentQuestionIndex];
renderQuestion();
renderQuestionOptions(currentQuestionObj.answers);
}
function renderQuestion() {
var progressHTML = "<span>(" + (data.currentQuestionIndex + 1) + '/' + data.questions.length + ")</span>"
var questionText = data.questions[data.currentQuestionIndex].question;
$(".js-question-text").html(progressHTML + questionText);
console.log(renderQuestion);
}
function renderQuestionOptions(answers){
$(".myForm label").each(function(index, label) {
$(this).find("input").attr("value", answers[index]);
$(this).find("input").prop("checked", false);
$(this).find("span").text(answers[index]);
});
}
function finalResults(){
$("#questionPage").addClass("hidden");
$("#results-page").removeClass("hidden");
$('#retake-button').removeClass("hidden");
var element = $('.js-final-results');
element.html("<h2>" + "You got" + '' + data.correctChoice + ' ' + "out of" + ' ' + data.questions.length + ' ' + "correct" + "</h2>");
retakeQuiz();
}
function checkAnswer(userChoice) {
var correctChoice = data.questions[data.currentQuestionIndex].correctAnswer;
console.log(data.currentQuestionIndex, data.questions[data.currentQuestionIndex]);
if (userChoice === correctChoice) {
data.totalScore++;
renderQuestionFeedback(true);
data.currentQuestionIndex++;
} else if (userChoice === undefined) {
renderQuestionFeedback("unanswered");
} else {
renderQuestionFeedback(false);
data.currentQuestionIndex++;
}
if (data.currentQuestionIndex == data.questions.length) {
finalResults();
} else {
renderQuestionPage();
}
}
function renderQuestionFeedback(response){
var feedback = $(".popup-inner");
if (response === true) {
feedback.find("h2").text("That was correct");
} else if (response === false) {
feedback.find("h2").text("That was incorrect");
} else if (response === "unanswered") {
feedback.find("h2").text("Answer the question!");
}
}
function startQuiz(){
$("#startQuiz").click(function(e){
$("#questionPage").removeClass("hidden");
$("#startQuiz").addClass("hidden");
console.log("take quiz clicked");
});
}
function retakeQuiz(){
$("#retake-button").click(function(e){
$("#questionPage").removeClass("hidden");
$("#retake-button").addClass("hidden");
resetQuiz();
renderQuestionPage();
});
}
function answerSubmitted(){
$("#submit-answer").click(function(e){
e.preventDefault();
var userChoice = $("input[name='answerChoice']:checked").val();
renderQuestionFeedback()
checkAnswer(userChoice);
});
}
function answerResponse(){
$("#submit-answer").on("click", function(e){
e.preventDefault();
var targetPopupClass = $(this).attr("data-popup-open");
$(`[data-popup="' + targetPopupClass + '"]`).fadeIn(250);
e.preventDefault();
renderQuestionFeedback();
});
}
function resetQuiz(){
data.totalScore = 0;
data.currentQuestionIndex = 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Brian's Quiz</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="quizstyle.css">
</head>
<body>
<header id="title" role="banner">
<h1>Brian's Quiz</h1>
</header>
<div id="container">
<section id="startPage" role="region">
<h2>Thinkful is in da House!</h2>
<button type="submit" id="startQuiz" role="button">Start Quiz</button>
</section>
<section id="results-page" class="hidden">
<div class="js-final-results text-center"></div>
<button class="hidden" id="retake-question"></button>
</section>
<section class="popup" data-popup="popup-feedback">
<div class="popup-inner">
<h2 id="text-feedback"></h2>
</div>
</section>
<section id="questionPage" role="region">
<h3 class="js-question-text">
<span>(1/10)</span>
</h3>
<form class="myForm" action="form" role="form">
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<button type="submit" id="submit-answer" data-popup-open="popup-feedback">Next</button>
<p><span id="questionNo">5</span> out of <span id="outOf">10</span></p>
</form>
</section>
<section id="showAnswer" role="region">
<h2>Correct</h2>
<button type="submit" id="continue" role="button">Continue Quiz</button>
</section>
<section id="finalPage" role="region">
<h2>Your Result</h2>
<p>You got <span id="correctNo">5</span> out of <span id="total-outof">10</span> correct</p>
<button type="submit" id="retake-button">Retake Quiz</button>
</section>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="quizJS.js" type="text/javascript"></script>
</html>
In the console, when I click the next button, I just get the same question object or question number 1 over and over.
You will find that something is wrong when you compare these lines of code:
<input type="radio" name="answerResponse">
and
function answerSubmitted(){
$("#submit-answer").click(function(e){
e.preventDefault();
var userChoice = $("input[name='answerChoice']:checked").val();
renderQuestionFeedback()
checkAnswer(userChoice);
});
}
Either your input name='answerResponse' or input name='answerChoice'
Give it a try.
I have just started using Phonegap, I wanted to clear the textbox content when the user clicks on the textbox.
HTML:
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
JavaScript
function clear() {
document.getElementsByTagName('input').value = '';
}
But the clear function is not getting called. Also, just tried putting alert in clear()
function(did not help). Everything else working okay. Any help would be appreciated.
Full HTML Code:
<!DOCTYPE html> <html> <head>
<title>Age Calculator</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
alert('welcome');
}
function calAge() {
var x = confirm('Click here to calculate the age');
if(x == true) {
document.getElementById('ageId').style.display = block';
} else {
navigator.app.exitApp(); }
}
function submitValues() {
var todaysDate = new Date();
var y = todaysDate.getFullYear();
var m = todaysDate.getMonth() + 1;
var d = todaysDate.getDate() + 1;
var myYear = document.getElementById('yearVal').value;
var myMonth = document.getElementById('monthVal').value;
var myDate = document.getElementById('dateVal').value;
var myYear = (y-myYear);
var myMonth = (m-myMonth);
var myDate = (d-myDate);
document.getElementById('ageId').style.display = 'none';
document.getElementById('result').innerHTML = 'You are '+myYear+'years '+myMonth+' months and '+myDate + ' days old :-)';
} function clear() { document.getElementsByTagName('input').value = ''; }
</script> </head> <body>
<button onclick="calAge();">Age Calculator</button> <br>
<div id="ageId" style="display:none;">
<b>Please Enter your Date Of Birth in (dd/mm/yyyy) format:</b>
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
<input type="text" class="clear" id="monthVal" name="month" value="month" />/
<input type="text" class="clear" id="yearVal" name="year" value="year" />
<input type="button" value="submit" onclick = "submitValues();" />
</div>
<div id="result">
</div> </body> </html>
In HTML5 there is a placeholder attribute.
Ex:
<input type="text" placeholder="Enter Date" id="dateVal" name="date" />
We could use this to get what I desired.
Thanks, might be helpful to somebody.