Check if Number entered is correct By ID - JavaScript - javascript

Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/

OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}

See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →

Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}

Related

Need some assistance with an user not being able to send a message when the length of the input is 0

At the moment ive got my code set up so that the user can send a message to the chatbot on my website.
What i would like to do is, prevent the user from sending a message if userText is empty. Below is what i have so far:
function getUserResponse(){
var userText = $('#textInput').val();
if(userText.val() == 0){
}else{
var userHTML = "<p class='userText'><span>"+userText+" </span> <img src= {% static 'images/userIcon.png' %} width=50px height=50px style='vertical-align: middle;' > </p>";
$('#textInput').val("");
}
$('#chatbot').append(userHTML);
$.get('/chatbotModel/getResponse',{userMessage:userText}).done(function(data){
var returnedMessage = "<p class='botText'> <img src= {% static 'images/chatbot.png' %} width=50px height=50px style='vertical-align: middle;' > <span>"+data+"</span/></p>";
$('#chatbot').append(returnedMessage)
})
}
$('#buttonInput').click(function(){
getUserResponse()
})
So check if the string is empty by looking at the length and if it is, exit....
var userText = $('#textInput').val().trim();
if(userText.length === 0) {
return;
}
Try with:
if ( userText.val().length == 0 ){
It would read the number of characters of the input, if it´s 0, it would return true.
You can abbreviate it like this:
if ( !userText.val().length ){
Using the ! operator, which transform a number into a boolean: if number is 0 it would return true, else, returns false.
A more complex way to do it
The verify_input() function would read each character. If there isn´t any valid character (from ascii code 33 to 165) it would return false:
function submit() {
var val = document.getElementById("myinput").value;
if (verify_input(val)) {
console.log("Verified");
} else {
console.log("Denied");
}
}
function verify_input(myval) {
var myval_arr = myval.split("");
for (var i = 0; i < myval_arr.length; i++) {
if (myval_arr[i].charCodeAt(0) >= 33 && myval_arr[i].charCodeAt(0) <= 165) {
return true;
}
}
return false;
}
<input id="myinput">
<button onclick="submit()">Submit</button>
PD: do not declare the userText variable like this:
var userText = $('#textInput').val();
Just declare with the input element:
var userText = $('#textInput');

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.

jquery does not support mask,any altenative? [duplicate]

I want to mask the text in an input box without changing the actual value. I can not use any plugins.
I am currently doing this - but as you can see the issue is that the actual value is changed on submit. How can I just change the display value?
$("input[name='number']").focusout(function(){
var number = this.value.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
this.value = number;
}
You need two inputs
Two inputs should get the job done. One input will contain the masked text and the other will be a hidden input that contains the real data.
<input type="text" name="masknumber">
<input type="text" name="number" style="display:none;">
The way I approached the masking is to build a function for both masking and unmasking the content so everything stays uniform.
$("input[name='masknumber']").on("keyup change", function(){
$("input[name='number']").val(destroyMask(this.value));
this.value = createMask($("input[name='number']").val());
})
function createMask(string){
return string.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
}
function destroyMask(string){
return string.replace(/\D/g,'').substring(0,8);
}
Working JSFiddle
or also
<input type="text" onkeypress="handleMask(event, 'data: 99/99/9999 99:99 999 ok')" placeholder="data: ok" size=40>
with
function handleMask(event, mask) {
with (event) {
stopPropagation()
preventDefault()
if (!charCode) return
var c = String.fromCharCode(charCode)
if (c.match(/\D/)) return
with (target) {
var val = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
var pos = selectionStart + 1
}
}
var nan = count(val, /\D/, pos) // nan va calcolato prima di eliminare i separatori
val = val.replace(/\D/g,'')
var mask = mask.match(/^(\D*)(.+9)(\D*)$/)
if (!mask) return // meglio exception?
if (val.length > count(mask[2], /9/)) return
for (var txt='', im=0, iv=0; im<mask[2].length && iv<val.length; im+=1) {
var c = mask[2].charAt(im)
txt += c.match(/\D/) ? c : val.charAt(iv++)
}
with (event.target) {
value = mask[1] + txt + mask[3]
selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\D/, pos) - nan)
}
function count(str, c, e) {
e = e || str.length
for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
return n
}
}
A more robost version of accepted answer without having two input's which may pollute transmitted form fields and also being aware of key-repetitions and other quirks when pressing a key too long:
<input type="text" name="masknumber" data-normalized="">
and
$("input[name='masknumber']").on("input", function(){ // input event!
let n = destroyMask(this.value);
this.setAttribute("data-normalized", n); // saved as attribute instead
this.value = createMask(n);
})
function createMask(string){
return string.replace(/(\d{2})(\d{3})(\d{2})/,"$1-$2-$3");
}
function destroyMask(string){
return string.replace(/\D/g,'').substring(0, 7); // 7 instead of 8!
}
JSFiddle

Why my else condition is beeing executed?

I am new to Javascript and I was making a little chat bot, nothing to fancy, but I am stuck in a problem where if I input something to it that matches a value inside an array it will execute the if and the else condition.
function readInput(){
var words = ["hello", "hi", "holis", "holus"];
var userInput = document.getElementById("userInput").value.toLowerCase();
console.log(" Users says: " + userInput);
for(var i = 0; i < words.length; i++){
if(userInput == words[i]){
console.log("bot says: " + "hi!");
}else {
console.log("bot says " + "i dont understand");
}
}
//clean user input
var clearInput = document.getElementById("userInput").value="";
}
<input type="text" id="userInput" value="">
<button type="button" name="button" onclick="readInput()">Say</button>
Any help will be appreciated
Modify your for statement.
Define a variable to check if your script know the word. In the for statement, if the input word is in the words, then set the variable true then break. Finally if the check variable is false, than say I don't understand:
var check = false
for (var i = 0; i < words.length; i++) {
if (userInput == words[i]) {
console.log("bot says: " + "hi!");
check = true;
break
}
}
if (!check) {
console.log("bot says " + "i dont understand");
}

Allow to select only predifened combination from available values

let us say we have parameter with A,B,C and D values. Now we want to force the user to choose only A,B,C or A,C,D or A or B or C.
Instead of Allowing all possible 16 combination, we want to allow only 5 predefined combination. I tried it but for this i have to put condition for each and every selection.
If we assume this values are bind with checkbox and we need to check whether selected values are as per our predifined combination or not.
I need to achieve this in javascript or either angular.js. Please help me with proper algorithm for such operation.
I tried below logic to achieve this but this will not infor user instantly, alert only after final submission
// multi-dimentional array of defined combinations
var preDefinedCombinations = [['a','b','c'], ['a','c','d'], ['a'], ['b'], ['c']];
// Combination user select
var selectedvalues = [];
// Function called on selection or removing value (i.e a,b,c,d)
function selectOption(value){
var checkIndex = selectedvalues.indexof(value);
if(checkIndex == -1){
selectedvalues.push(value);
}else{
selectedvalues.splice(checkIndex, 1);
}
}
// function called on submition of combination
function checkVaildCombination(){
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
alert('Invalid Combination');
}else{
alert('Valid Combination');
}
}
This code gives information only about combination is valid or not, not about which may be possible combinations as per selections.
stolen from https://stackoverflow.com/a/1885660/1029988 :
function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = new Array();
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
then in your code:
function checkVaildCombination(){
function get_diff(superset, subset) {
var diff = [];
for (var j = 0; j < superset.length; j++) {
if (subset.indexOf(superset[j]) == -1) { // actual missing bit
diff.push(superset[j]);
}
}
return diff;
}
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
missing_bits = [];
diffed_bits = [];
for (var i = 0; i < preDefinedCombinations.length; i++) {
var intersection = intersect_safe(preDefinedCombinations[i], selectedvalues);
if (intersection.length == selectedvalues.length) { // candidate for valid answer
missing_bits.push(get_diff(preDefinedCombinations[i], intersection));
} else {
var excess_bits = get_diff(selectedvalues, intersection),
missing_bit = get_diff(preDefinedCombinations[i], intersection);
diffed_bits.push({
excess: excess_bits,
missing: missing_bit
});
}
}
var message = 'Invalid Combination, if you select any of these you`ll get a valid combination:\n\n' + missing_bits.toString();
message += '\n\n Alternatively, you can reach a valid combination by deselected some bits and select others:\n';
for (var j = 0; j < diffed_bits.length; j++) {
message += '\ndeselect: ' + diffed_bits[j].excess.toString() + ', select: ' + diffed_bits[j].missing.toString();
}
alert(message);
} else {
alert('Valid Combination');
}
}
you will of course want to format the output string, but that code will (hopefully, it is napkin code after all) give you the missing bits to make valid combos with what you've got selected already
May be following code could help you to solve ur problem
<script>
function validateForm(){
var checkBoxValues = this.a.checked.toString() + this.b.checked.toString() + this.c.checked.toString() + this.d.checked.toString();
if( checkBoxValues == 'truetruetruefalse' || // abc
checkBoxValues == 'truefalsetruetrue' || // acd
checkBoxValues == 'truefalsefalsefalse' || // a
checkBoxValues == 'falsetruefalsefalse' || // b
checkBoxValues == 'falsefalsetruefalse' ){ // c
return true;
}
return false;
}
</script>
<form onsubmit="return validateForm()" action="javascript:alert('valid')">
<input type="checkbox" name="mygroup" id="a">
<input type="checkbox" name="mygroup" id="b">
<input type="checkbox" name="mygroup" id="c">
<input type="checkbox" name="mygroup" id="d">
<input type="submit">
</form>

Categories