How to Get Input Field Value JavaScript - javascript

I'm trying to create a guessing game that if the user enters a number into an input field and click a button, a text shows up saying if the number is bigger or smaller than a random number that's been created by JavaScript. I seem to have figured out everything else, but I'm having a hard time getting the value that is entered into the input field.
I'd appreciate your help.
<div class="wrap" >
Project: Guessing Game
<input type="text" name="inputField" value="" id="inputField"/>
<button id="guess">Guess!</button>
<br>
<p id="result"></p>
</div>
<script type="text/javascript" charset="utf-8">
var $ = function(selector) {
return document.querySelector(selector);
};
var randomRange = function(min,max){
return Math.random(((Math.random()*(max-min))+min));
};
var randomNumber = randomRange(1,4);
var myButton = $("#guess");
var myNumber = $("#inputField").value;
var myResult = $("#result");
if ( myNumber > randomNumber) {
myButton.onclick = function () {
myResult.innerHTML += "Your number is bigger than the random number";
}
}
else if ( myNumber < randomNumber){
myButton.onclick = function () {
myResult.innerHTML += "Your number is smaller than the random number";
}
}
else if ( myNumber === randomNumber ){
myButton.onclick = function () {
myResult.innerHTML += "Your number matches the random number";
}
}
</script>

Your input is being read when there is no data, and when you click, you don't check if the data has changed. You should place the decision blocks to check the input inside the event handler, like this:
myButton.onclick = function () {
var myNumber = $("#inputField").value;
myNumber = parseInt(myNumber, 10);
if ( myNumber > randomNumber) {
myResult.innerHTML = "Your number is bigger than the random number";
} else if ( myNumber < randomNumber){
myResult.innerHTML = "Your number is smaller than the random number";
} else if ( myNumber === randomNumber ){
myResult.innerHTML = "Your number matches the random number";
}
}

var $ = function(selector) {
return document.querySelector(selector);
};
var randomRange = function(min,max){
return Math.round(((Math.random()*(max-min))+min));//notice here,Math.round
};
var randomNumber = randomRange(1,4);
var myButton = $("#guess");
var myNumber = $("#inputField");
var myResult = $("#result");
myButton.onclick = function(){
var val = parseInt(myNumber.value, 10);
if(val < randomNumber){
//smaller code
}else if(val > randomNumber){
//bigger code
}else{
//equal code
}
}

Related

Custom Form Validation Messages

Hey everyone reading this!
I am trying to validate a form and have that text field showing in case something's left empty. It does show indeed but too many time and I can't figure out why the counter doesn't work. Open to any ideas ... Thanks!
// For checking if the fields are filled and creating an html element
var newP = document.createElement("p");
var alertText = document.createTextNode("You should fill both fields!");
newP.appendChild(alertText);
var counter = 0;
// Declaring the canvas
var canvas = document.getElementById("draw");
var ctx = canvas.getContext('2d');
var formValue = document.getElementById("gameForm");
var submit = document.querySelector("#submitGameForm");
submit.addEventListener('click', function(e){ e.preventDefault(); validateForm();});
//global machen
function validateForm(){
var name = document.getElementById("name").value;
var hours = document.getElementById("hours").value;
var expressionName = new RegExp("^[a-zA-Z\s]+$");
var expressionHours = new RegExp("[0-9 ]+");
var correct = true;
var showMessage = false;
//Test if empty
if(name == "" || name == null || hours == "" || hours == null){
showMessage= true;
correct= false;
}
if(showMessage && counter == 0){
formValue.appendChild(newP);
console.log(newP);
counter++;
}
if(!expressionName.test(name)) {
document.getElementById("name").style.background='#8e3733';
correct = false;
}
else{
document.getElementById("name").style.background='#FFFFFF';
}
if(!expressionHours.test(hours)) {
document.getElementById("hours").style.background='#8e3733';
correct = false;
}
else{
document.getElementById("hours").style.background='#FFFFFF';
}
}
<main class="game" id="mainIndex">
<div class= "divGameForm">
<h2>Confess in order to play</h2>
<form id="gameForm">
<label for="name">Enter your name:</label>
<input id="name" type="text" >
<label for="hours">How many hours per day do you spend playing?</label>
<input id="hours" type="text" >
<p>Press the button if you would like to increase them!</p>
<input id="submitGameForm" type="submit" value="Submit" >
</form>
</div>
<div class="divGame">
<canvas id="draw"> </canvas>
<div>
<p>You can only draw circles. The dimentions are 240 (width) and 300 (height). Try it out!s</p>
<label for="xPos">Enter value for x: </label>
<input id="xPos" type="text">
You can use the counter In the test scenario empty as counter++ then should change showmessage and counter > 0
var newP = document.createElement("p");
var alertText = document.createTextNode("You should fill both fields!");
newP.appendChild(alertText);
var counter = 0;
// Declaring the canvas
var canvas = document.getElementById("draw");
var ctx = canvas.getContext('2d');
var formValue = document.getElementById("gameForm");
var submit = document.querySelector("#submitGameForm");
submit.addEventListener('click', function(e) {
e.preventDefault();
validateForm();
});
//global machen
function validateForm() {
var name = document.getElementById("name").value;
var hours = document.getElementById("hours").value;
var expressionName = new RegExp("^[a-zA-Z\s]+$");
var expressionHours = new RegExp("[0-9 ]+");
var correct = true;
var showMessage = false;
//Test if empty
if (name == "" || name == null || hours == "" || hours == null) {
showMessage = true;
correct = false;
counter++;
}
if (showMessage && counter > 0) {
formValue.appendChild(newP);
console.log(newP);
}
if (!expressionName.test(name)) {
document.getElementById("name").style.background = '#8e3733';
correct = false;
} else {
document.getElementById("name").style.background = '#FFFFFF';
}
if (!expressionHours.test(hours)) {
document.getElementById("hours").style.background = '#8e3733';
correct = false;
} else {
document.getElementById("hours").style.background = '#FFFFFF';
}
}

how to replace input numbers with commas after key presses

I want to replace a number over 100 with commas. Like 1000 to 1,000 and 1000000 to 1,000,000 etc. in HTML. I have found the code on here to do so but it only works with predetermined numbers being passed. I don't want it to work for a predetermined number but for any number typed into the box.
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="text" id="turnover" maxlength="11"
name="turnover" size="10" required>*
<br /><br />
<script type="text/javascript">
$('#turnover').keydown(function(){
var str = $(this).val();
str = str.replace(/\D+/g, '');
$(this).val(str.replace(/\B(?=(\d{3})+(?!\d))/g, ","));});
</script>
I created a solution using pure javascript.
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ',';
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
<label>Number</label>
<input id="numbers" onkeyup="onChange(this)">
There are a couple of issues with your code:
It runs once when the page loads, not after that. I added a button to fix that.
The id used in your code does not match the actual id of the input field.
Input fields must be read and written using .val(). .text() works only for divs, spans etc.
Note that the conversion now works one time, after that it fails to properly parse the new text which now contains the comma(s).
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function ShowComma() {
console.clear();
var val = parseInt($("#comma").val());
console.log(val);
val = numberWithCommas(val);
console.log(val);
$("#comma").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="value" id="comma" maxlength="30" name="turnover" size="10" required>*
<button onclick="ShowComma()">Show Comma</button>
To finalise this I have putgetElementById functions in so that this will work with a wordpress contact form 7. This must be with a text field though as it will not work with the number field as it will now accept commas:
<script>
document.getElementById("averagetrans").onkeyup = function() {onChange(this)};
document.getElementById("Turnover").onkeyup = function() {onChange(this)};
</script>
<script type="text/javascript">
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ','; // put commas into numbers 1000 and over
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
</script>

How to remove innerHTML value to be shown initially

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";
}

result output disappears too quickly

the correct or wrong answer outputs and quickly disappears. How do I get the answer to remain on the screen. I want to keep the html and js files separate. What I want to do later is add other phrases to the program.
INDEX.HTML
<head> </head>
<body>
<form name="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput">
<button id="myBtn">Click here</button>
<div id ="feedback"></div>
</form>
<script src = "phraseScrambler.js"></script>
</body>
</html>
PHRASESCRAMBLER.JS
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myBtn").onclick = checkAnswer;}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent= "correct";}
else {
elMsg.textContent= "wrong answer";}}
function shuffle(newWords) {
var counter = newWords.length, temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;}
return newWords;}
First of all don't bind click event if you want to handle form submission, forms have dedicated event called onsubmit. When form is submitted default browser behavior is to navigate to form action (in your case reload the page). You need to prevent this by returning false from the onsubmit handler.
Corrected HTML will be (I gave an id to the form):
<form name="myForm" id="myForm"> ... </form>
And then event handling will look like (note return false; in checkAnswer function):
var words = ['how', 'are', 'you', 'today?'];
var correctInput = "how are you today";
var userInput = 'how are you today?';
var newWords = words.slice(0);
shuffle(newWords);
question();
function question() {
var el = document.getElementById('phrase');
el.textContent = newWords.join(' ');
document.getElementById("myForm").onsubmit = checkAnswer;
}
function checkAnswer() {
var elMsg = document.getElementById('feedback');
if (document.myForm.textinput.value == correctInput) {
elMsg.textContent = "correct";
} else {
elMsg.textContent = "wrong answer";
}
return false;
}
function shuffle(newWords) {
var counter = newWords.length,
temp, index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = newWords[counter];
newWords[counter] = newWords[index];
newWords[index] = temp;
}
return newWords;
}
<form name="myForm" id="myForm">
<div id ="phrase"></div>
<input type = "text" id = "textinput" />
<button>Click here</button>
<div id ="feedback"></div>
</form>

Word count jquery and stop user from typing

$(document).ready(function(){
$("input").keyup(function(){
if($(this).val().split(' ').length == 10){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Enter your name: <input type="text">
If the input is 1 2 3 4 5 6 7 8 9 the alert fired, I know it included the space. But how to stop user from adding more character (even space) when the limit is reached?
The problem can easily be simplified to disabling the spacebar when the max word count is reached:
this should work: http://jsfiddle.net/wznervgz/6/
<input data-max-words="10" />
js:
$('input[data-max-words]').on('keydown', function (e) {
var $txt = $(this),
max = $txt.data('maxWords'),
val = $txt.val(),
words = val.split(' ').length;
if (words === max && e.keyCode === 32)
return false;
});
Hope this will help you.
<textarea name="txtMsg" id="word_count" cols="1" rows="1"> </textarea>
<span style="padding-left:10px;">Total word Count :
<span id="display_count" style="font-size:16px; color:black;">0</span> words &
<span id="count_left" style="font-size:16px; color:black;">2</span> words left.</span>
<br>
jquery code:
var max_count = 2;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function (k, v) {
finalCount += v;
});
var vl = this.value;
if (finalCount > max_count) {
vl = vl.substring(0, vl.length - 1);
this.value = vl;
}
var countleft = parseInt(max_count - finalCount);
$('#display_count').html(finalCount);
$('#count_left').html(countleft);
am_cal(finalCount);
});
}).keyup();
Fiddle link: http://jsfiddle.net/aVd4H/32/
Thank you.
Think about storing the value of the input after each keyup and if the wordcount is greater than your limit just setVal back to the "previously" saved amount. So it would start off as var previousVal = ''; and then increment accordingly until the comparison returns true, set the val and return.
Demo: http://jsfiddle.net/robschmuecker/wznervgz/1/
$(document).ready(function(){
var previousValue = '';
$("input").keydown(function(){
if($(this).val().split(' ').length >= 10){
alert();
$(this).val(previousVal);
return;
}
previousVal = $(this).val();
});
});
You can try this:
$("input").keydown(function(e){
if($(this).val().split(' ').length == 10){
alert();
e.preventDefault();
return false;
}

Categories