How to remove innerHTML value to be shown initially - javascript

I am trying to create a multiplication table in JavaScript. The user is prompted to provide the Table number (1 to 10) after which all the question marks ('?') are replaced with that number. The user then needs to enter the answers in all the provided text fields. Finally, the user will have the option to check the answer (i.e. whether it is right or wrong).
When I run my code. After entering the user data to prompt it shows Incorrect infront of each textfield and the user entered value just before the Check answers button. How can I remove them to be shown initially.
Output:
My code:
function result() {
var value = document.getElementById("a1").value;
var checkMessageSpan1 = document.getElementById("checkMessage1");
var checkMessageSpan2 = document.getElementById("checkMessage2");
var r = x * 1;
if (value == x) {
checkMessageSpan1.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan1.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
var value = document.getElementById("a2").value;
var r = x * 2;
if (value == r) {
checkMessageSpan2.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan2.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
</script>
<button onClick="alert_field()"> Generate Question</button><br><br>
<p id="s1">
? x 1 = <input type="text" id="a1"><span id="checkMessage1"></span><br>
? x 2 = <input type="text" id="a2"><span id="checkMessage2"></span><br>
</p><br><br>
<p id="a"></p>
Check answers

For replacing all special characters, you may leverage regular expressions in js
var res=str.replace(/[^a-zA-Z0-9]/g,x); instead of
var res = str.replace("?",x);
More on Regular expressions in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Try to add this code:
var value = document.getElementById("a1").value;
if (checkMessageSpan1.style.display === "none") {
checkMessageSpan1.style.display = "inline-block";
} else {
checkMessageSpan1.style.display = "none";
}
var value = document.getElementById("a2").value;
if (checkMessageSpan2.style.display === "none") {
checkMessageSpan2.style.display = "inline-block";
} else {
checkMessageSpan2.style.display = "none";
}

Related

How to compare 2 text input values?

I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.

How can I set a variable to a text input and then make it appear on screen

I am making a text based game for school and I am stuck with trying to set a variable as an text input. What I would like to happen is the player type start into the input and it do what is inside of the if statement. However from there I would like the player to enter a username and then it set the variable of "name" to what they input but with out it saving the name as "start".
//js
var name = "";
var beginBeenTo = false;
if (beginBeenTo == false) {
if (input == "START") {
beginBeenTo = true;
page = page + 1;
healthPoints = 25;
soundEveningBreeze.play();
$("#welcome_message").show().insertBefore("#placeholder").delay(3000).fadeOut(3000);
$("<br><p class='text'>You there, what is your name?</p>").hide().insertBefore("#placeholder").delay(7000).fadeIn(3000);
if (input != "" || namingBeenTo == false) {
name = input;
}
}
}
document.getElementById("print_name").innerHTML = name;
Quite simply, watch for some event (keyup in my case), check if the input value is START, if so ask for a username.
var started = false;
var username = '';
$('input').on('keyup', function(){
var tmpValue = $(this).val();
if(started){
username = tmpValue
}
if(tmpValue === 'START') {
started = true;
$(this).val('')
$(this).attr('placeholder','Username')
}
$('#username').text(username)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="username"></span>
<br>
<input type="text" placeholder="Type START to play">
it could be done with use of function like this :
var name = "";
$("form").submit(function() {
var input = $("#command_input").val().toUpperCase();
if (input == "START") {
name = $("#input_form").val();
}
}
document.getElementById("print_name").innerHTML = name;
you were missing one of #(hashtag)
And this code would work
Thanks & Cheers

Don't run function if field empty

I'm new here, and very new to Javascript and programming concepts in general. Part of the form I'm working on simlpy needs to calculate the difference between two prices. I do know float numbers are screwy, so I have that part figured out. And it calculates, and inputs it into field 3. The only thing I can't seem to figure out is making it so that if either field 1 or 2 is empty, the function doesn't run. It should only run when both fields are filled. Here's my example code:
<input type="text" id="1"> </input><br/>
<input type="text" id="2"> </input><br/>
<input type="text" id="3"> </input><br/>
<br/><br/><br/>
<p id="test"></p>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function emptyCheck(){
if ($("#1") = ""){
$("#3").val("");
}
else if ($("#2") = ""){
$("#3").val("");
}
else{
rateDiff();
}
}
function rateDiff(){
var clientRate = $("#1").val() * 100;
var agentRate = $("#2").val() * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);
</script>
I don't get what I'm doing wrong here. Can anyone point me in the right direction?
if ($("#1") = ""){
should be
if ($("#1").val() == ""){
same for $("#2") = ""
$("#1") is a jquery element, not the value.
Also you put = instead of ==
$("#1") = "")
Should be
$("#1").val() == "")
One = is used to assign a value, while two == is to do a comparison.
Just use the "falsey" of JavaScript and the values:
function emptyCheck(){
if (!$("#1").val() || !$("#2").val()){
$("#3").val("");
}
else{
rateDiff();
}
}
NOTE: you would be better parsing the numbers to handle alpha entry:
function emptyCheck() {
if (!parseFloat($("#1").val()) || !parseFloat($("#2").val())) {
$("#3").val("");
} else {
rateDiff();
}
}
function rateDiff() {
var clientRate = parseFloat($("#1").val()) * 100;
var agentRate = parseFloat($("#2").val()) * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);

Javascript shows NaN in wrong form-field in IE - works in Firefox and chrome

I am trying to setup a small article chooser. While it works in Firefox and Chrome, as well as IE7, it has problems on IE8 and IE9.
In IE 8 and 9 it changes to "increase" field to "NaN" when clicked. (edit: solved by placing a letter in front of the number)
In IE9 it updates the "Warenkorb", but places "NaN" or "\/" in
the field for "Anzahl". (edit: solved by placing a letter in front of the number)
In IE8 it completely ignores the update function. (edit: is related to the innerHTML-Bug)
To me it seems that somehow I can not reach the form itself. I have already tried to use document.forms[0] and document.getElementById["bestmult"] instead, in case the delivered object is not the field inside the form, but that did not change anything.
I feel like the solution is very simple, but I just can not put my finger on it.
Here is the code:
<script>
var sumarray = new Array();
var artarray = new Array();
var costarray = new Array();
var counter=0;
function increase(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements[field].value, 10);
value++;
form.elements[field].value = value;
updateCosts(obj, field, type);
}
function decrease(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements[field].value, 10);
if(value > 0){
value--;
form.elements[field].value = value;
updateCosts(obj, field, type);
}
}
function updateCosts(obj, field, type){
var form = obj.form;
var exist = artarray.indexOf(form.elements[field].name);
var preis = 0;
if (type == 'b'){
preis = 19.95;
}else if (type == 'p') {
preis = 29.95;
}
if (exist != -1){
if (form.elements[field].value == 0){
sumarray.splice(exist , 1);
artarray.splice(exist , 1);
costarray.splice(exist , 1);
counter--;
}else {
sumarray[exist] = form.elements[field].value;
artarray[exist] = form.elements[field].name;
costarray[exist] = preis;
}
}else {
sumarray[counter] = form.elements[field].value;
artarray[counter] = form.elements[field].name;
costarray[counter] = preis;
counter++;
}
var completestring = "";
if (counter > 0) {
var product = 0;
completestring += "<h1>Warenkorb</h1><table border=0><tr style='background:gray;' align='center'><td width=110 align='center'>Artikel</td><td width=80>Anzahl</td><td align='center' width=60>Preis</td><td align='center' width='40'>Del</td></tr>";
for(var i=0;i<counter;i++){
completestring += "<tr><td>"+artarray[i].replace("_", " ")+"</td><td align=center>"+sumarray[i]+"</td><td align=center>"+costarray[i]+"</td><td align=center><img src='img/trash.png' onclick='setZero(\""+artarray[i]+"\")'></td></tr>";
product += parseInt(sumarray[i])*parseInt(costarray[i]);
}
completestring += "</table><h2>"+(product).toFixed(2)+"</h2>";
} else {
completestring += "<h1>Warenkorb</h1>";
}
document.getElementById("sum").innerHTML = completestring;
}
function setZero(element) {
var form = document.forms[0];
form.elements[element].value = "0";
var obj = form.elements[element];
updateCosts(obj, element, "b");
}
</script>
<div id="sum">
</div>
<form id="bestmult" action="test2.html" method="post">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td rowspan="2"><input type="text" name="1_Basis" value="0" onblur="updateCosts(this, '1_Basis', 'b')" /></td>
<td><input type="button" value=" /\ " onclick="increase(this, '1_Basis', 'b')" class="button" ></td>
</tr><tr>
<td><input type="button" value=" \/ " onclick="decrease(this, '1_Basis', 'b')" class="button" ></td>
</tr>
</table>
This code is of cause not everything there is (although everything that could potentially influence the problem at hand), so don't bother with the script tags, or the incomplete form, these where just added for completion, to show how it all fits together without having to post the whole code.
edit: it seems that IE8 and 9 have a problem with the way I named by textfields. I could resolve most of the problem by simply putting a z at the start which I can later simply strip to regain to proper text. Now it is just IE8 that does not seem to like innerHTML. I did find a lot on this on the Internet, yet nothing that really works.
Check my modifications in your script code
<script>
var sumarray = new Array();
var artarray = new String();
var costarray = new Array();
var counter=0;
function increase(obj, field, type){
var form1 = obj.form;
//alert(obj.form1.elements[0].value);
var value = parseInt(form1.elements(field).value, 10);
value++;
form1.elements(field).value = value;
updateCosts(obj, field, type);
}
function decrease(obj, field, type){
var form = obj.form;
var value = parseInt(form.elements(field).value, 10);
if(value > 0){
value--;
form.elements(field).value = value;
updateCosts(obj, field, type);
}
}
function updateCosts(obj, field, type){
var form = obj.form;
var exist = artarray.indexOf(form.elements(field).name);
var preis = 0;
if (type == 'b'){
preis = 19.95;
}else if (type == 'p') {
preis = 29.95;
}
if (exist != -1){
if (form.elements(field).value == 0){
sumarray.splice(exist , 1);
artarray.splice(exist , 1);
costarray.splice(exist , 1);
counter--;
}else {
sumarray[exist] = form.elements(field).value;
artarray[exist] = form.elements(field).name;
costarray[exist] = preis;
}
}else {
sumarray[counter] = form.elements(field).value;
artarray[counter] = form.elements(field).name;
costarray[counter] = preis;
counter++;
}
var completestring = "";
if (counter > 0) {
var product = 0;
completestring += "<h1>Warenkorb</h1><table border=0><tr style='background:gray;' align='center'><td width=110 align='center'>Artikel</td><td width=80>Anzahl</td><td align='center' width=60>Preis</td><td align='center' width='40'>Del</td></tr>";
for(var i=0;i<counter;i++){
completestring += "<tr><td>"+artarray[i].replace("_", " ")+"</td><td align=center>"+sumarray[i]+"</td><td align=center>"+costarray[i]+"</td><td align=center><img src='img/trash.png' onclick='setZero(\""+artarray[i]+"\")'></td></tr>";
product += parseInt(sumarray[i])*parseInt(costarray[i]);
}
completestring += "</table><h2>"+(product).toFixed(2)+"</h2>";
} else {
completestring += "<h1>Warenkorb</h1>";
}
document.getElementById("sum").innerHTML = completestring;
}
function setZero(element) {
var form = document.forms[0];
form.elements[element].value = "0";
var obj = form.elements[element];
updateCosts(obj, element, "b");
}
</script>
For ie8 indexOf() method for Array will give error. Check this
I think the problem is related to passing "this" to the function. It seems to be passing the button.
Try replacing
var form = obj.form;
with
var form=document.forms[0]
and ignore the reference to "obj"
Ok, so here is the solution packed together into one answer:
I was facing two problems:
the first one was, that an attribute name in XML can not start with a Number. I solved this by simply adding a letter in front, which i could delete for the String lateron using the replace-function.
The second problem was that the IE8 does not have the Array function indexOf(). Thank you 555k for your help here, you gave me the final piece to the puzzle. I wrote a small workaround, that suits my situation:
var exist = -1;
var needle = form.elements[field].name;
for (var i=0;i<counter;i++){
if (artarray[i].indexOf(needle) != -1){
exist = i;
}
}
This does exactly what I want, so it works for my problem. It is, of cause, not a solution to the problem of a nonexistant "indexOf()" for an aged browser, but maybe someone can use this.

Limiting character in textbox input

please be nice. I'm trying to create a page which sets limit and cut the excess (from the specified limit). Example: Limit is 3. then, I'll input abc if I input d it must say that its limit is reached and the abc will remain. My problem is that it just delete my previous input and make new inputs. Hoping for your great cooperation. Thanks.
<html>
<script type="text/javascript">
function disable_btn_limit(btn_name)
{
/* this function is used to disable and enable buttons and textbox*/
if(btn_name == "btn_limit")
{
document.getElementById("btn_limit").disabled = true;
document.getElementById("ctr_limit_txt").disabled = true;
document.getElementById("btn_edit_limit").disabled = false;
}
if(btn_name == "btn_edit_limit")
{
document.getElementById("btn_limit").disabled = false;
document.getElementById("ctr_limit_txt").disabled = false;
document.getElementById("btn_edit_limit").disabled = true;
}
}
function check_content(txtarea_content)
{
/*This function is used to check the content*/
// initialize an array
var txtArr = new Array();
//array assignment
//.split(delimiter) function of JS is used to separate
//values according to groups; delimiter can be ;,| and etc
txtArr = txtarea_content.split("");
var newcontent = "";
var momo = new Array();
var trimmedcontent = "";
var re = 0;
var etoits;
var etoits2;
//for..in is a looping statement for Arrays in JS. This is similar to foreach in C#
//Syntax: for(index in arr_containter) {}
for(ind_val in txtArr)
{
var bool_check = check_if_Number(txtArr[ind_val])
if(bool_check == true)
{
//DO NOTHING
}
else
{
//trim_content(newcontent);
newcontent += txtArr[ind_val];
momo[ind_val] = txtArr[ind_val];
}
}
var isapa = new Array();
var s;
re = trim_content(newcontent);
for(var x = 0; x < re - 1; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
}
function trim_content(ContentVal)
{
//This function is used to determine length of content
//parseInt(value) is used to change String values to Integer data types.
//Please note that all value coming from diplay are all in String data Type
var limit_char =parseInt(document.getElementById("ctr_limit_txt").value);
var eto;
if(ContentVal.length > (limit_char-1))
{
alert("Length is greater than the value specified above: " +limit_char);
eto = limit_char ;
etoits = document.getElementById("txtarea_content").value;
//document.getElementById("txtarea_content").value = "etoits";
return eto;
//for(var me = 0; me < limit_char; me++)
//{document.getElementById("txtarea_content").value = "";}
}
return 0;
}
function check_if_Number(ContentVal)
{
//This function is used to check if a value is a number or not
//isNaN, case sensitive, JS function used to determine if the values are
//numbers or not. TRUE = not a number, FALSE = number
if(isNaN(ContentVal))
{
return false;
}
else
{ alert("Input characters only!");
return true;
}
}
</script>
<table>
<tr>
<td>
<input type="text" name="ctr_limit_txt" id="ctr_limit_txt"/>
</td>
<td>
<input type="button" name="btn_limit" id="btn_limit" value="Set Limit" onClick="javascript:disable_btn_limit('btn_limit');"/>
</td>
<td>
<input type="button" name="btn_edit_limit" id="btn_edit_limit" value="Edit Limit" disabled="true" onClick="javascript:disable_btn_limit('btn_edit_limit');"/>
</td>
</tr>
<tr>
<td colspan="2">
<textarea name="txtarea_content" id="txtarea_content" onKeyPress="javascript:check_content(this.value);"></textarea>
<br>
*Please note that you cannot include <br>numbers inside the text area
</td>
</tr>
</html>
Try this. If the condition is satisfied return true, otherwise return false.
<html>
<head>
<script type="text/javascript">
function check_content(){
var text = document.getElementById("txtarea_content").value;
if(text.length >= 3){
alert('Length should not be greater than 3');
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<div>
<textarea name="txtarea_content" id="txtarea_content" onkeypress=" return check_content();"></textarea>
</div>
</body>
</html>
Instead of removing the extra character from the text area, you can prevent the character from being written in the first place
function check_content(event) { //PARAMETER is the event NOT the content
txtarea_content = document.getElementById("txtarea_content").value; //Get the content
[...]
re = trim_content(newcontent);
if (re > 0) {
event.preventDefault(); // in case the content exceeds the limit, prevent defaultaction ie write the extra character
}
/*for (var x = 0; x < re - 1; x++) {
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}*/
}
And in the HTML (parameter is the event):
<textarea ... onKeyPress="javascript:check_content(event);"></textarea>
Try replacing with this:
for(var x = 0; x < re - 6; x++){
document.getElementById("txtarea_content").value += momo[x];
document.getElementById("txtarea_content").value = "";
}
Any reason why the maxlength attribute on a text input wouldn't work for so few characters? In your case, you would have:
<input type="text" maxlength="3" />
or if HTML5, you could still use a textarea:
<textarea maxlength="3"> ...
And then just have a label that indicates a three-character limit on any input.

Categories