I'm trying to count the number of common letters between the user's input and the number generated. I am counting it so that the placement doesn't matter between them (so 411 and 004 should say "1 number in common").
I've placed my code in a snippet below. It works fine, except for that, when the generated string has two of the same numbers, it doesn't work properly. You can see that by typing "4", it will say that there are two chars. in common, when there is really only one (it counts the four twice.)
So, after all this, I'm asking what is the best way to show the common letters between the input and the generated number?
I'm fine with using jQuery and/or JavaScript, and sorry if my code isn't very good, I'm not very advanced at all.
Thanks for any help in advance! :)
// on ".check" click...
$(".check").click(function() {
var nmb = $(".number").text();
var ltr = $(".input").val();
var count = $(".cnt");
// Set logged text to 0
count.text("0");
// Test for numbers in common
if (ltr.includes(nmb.charAt(0))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
if (ltr.includes(nmb.charAt(1))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
if (ltr.includes(nmb.charAt(2))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
if (ltr.includes(nmb.charAt(3))) {
count.html(function(i, val) {
return val * 1 + 1
});
}
$(".res1").html(" numbers in common");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
First you can reduce each of the strings to only include unique characters, ie 4410 can be reduced to 410 as you don't need to test 4 more than once. You can do this by creating a Set of each string:
var numberSet = new Set(nmb);
var inputSet = new Set(ltr);
Then you can iterate over one of them, for least amount of iterations which ever is shortest, and use the has() method to see if that character was in the other Set
var counter = 0;
for(letter of inputSet){
if(numberSet.has(letter)){
counter++;
}
}
// on ".check" click...
$(".check").click(function() {
var nmb = new Set( $(".number").text() );
var ltr = new Set( $(".input").val() );
var count = $(".cnt");
var counter = 0;
for(let letter of nmb){
if(ltr.has(letter)){
counter++;
}
}
//No need to continually update text / html as each update wont be
//seen anyway so just set it once outside the loop.
count.text(counter);
$(".res1").html(" numbers in common");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
You can do something like:
$(".check").click(function() {
var nmb = $(".number").text().trim().split(''); //Get the text and convert to string
var ltr = $(".input").val().trim().split(''); //Get the value and convert to string
var commonLetters = []; //The common letters will be stored on this variable
ltr.forEach(function(v) { //Loop thru the user's input letters
var idx = nmb.indexOf(v); //Find its index
if (idx !== -1) { //Check if found
commonLetters.push(4); //If found, push the letters to commonLetters
nmb[idx] = ''; //Clear the index
}
})
$(".cnt").text(commonLetters.length);
$(".res1").html(" numbers in common");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" placeholder="Try typing 4 to see the issue" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
It's not entirely trivial. For example, you can't simply use filter or includes or has tests on their own because once a character is found, you have to remove it from each collection so it doesn't get matched again. I would use reduce and splice the array of characters to remove the found character every time a match is found. (No need for jQuery for this)
document.querySelector('.check').addEventListener('click', () => {
const numChars = [...document.querySelector('.number').textContent];
const inputChars = [...document.querySelector('.input').value];
const matchingCharCount = inputChars.reduce(
({ remainingNumChars = numChars, matchCount = 0 } = {}, inputChar) => {
if (remainingNumChars.includes(inputChar)) {
remainingNumChars.splice(remainingNumChars.indexOf(inputChar), 1);
matchCount++;
}
return { remainingNumChars, matchCount };
}, { remainingNumChars: numChars, matchCount: 0 })
.matchCount;
document.querySelector('.cnt').textContent = matchingCharCount;
document.querySelector('.res1').textContent = " numbers in common"
});
Generated Number: <span class="number">4410</span><br><br>
<input type="text" class="input" maxlength="4">
<input class="check" type="submit" value="CHECK">
<br><br>
<span id="full_res">
<span class="cnt"></span>
<span class="res1"></span>
</span>
Related
I'm trying to compare a input value with two paragrapah to check if the input value exists in both paragraph. So, I did this below. But the code is not working well :/. Could someone explain how to do it?
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
jQuery(function ($) {
var a = $('#billing_district').val().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split();
var b = $('.regions').text().normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().split(", ");
var index = $.grep(b, function (element, index) {
if ($.inArray(element, a) != -1) {
console.log(element);
}
});
});
This works, though you did not specify that the code should look at whole terms between commas. This code outputs true even if two letters occur in all the p's.
But you could add an extra loop to check the splitted strings.
jQuery(function($) {
const $input = $('#billing_district');
const b = $('.regions');
$('#billing_district').on('keyup', function(){
let a = $input.val();
let count = 0
$.each(b, function(i, p) {
console.log($(p).text().replace(/\s/g, ""),a);
if ($(p).text().replace(/\s/g, "").includes(a)) {
count++;
}
});
let valueIsInAllParagraphs = (count == 3);
console.log(valueIsInAllParagraphs);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input-text" name="billing_district" id="billing_district" placeholder="" value="">
<p class="regions">Dias Macedo, Itaperi, Passaré, Taquara, Serrinha</p>
<p class="regions">Dias Macedo, Dendê, Edson Queiroz, Taquara</p>
<p class="regions">Jereissati, Dendê, Forquilha, Centro, Taquara</p>
I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">
I am fairly new to javascript. Building a custom javascript calculator to set pricing for some products. There is sometimes a fee that is added. This fee is either a percentage of cost or an actual dollar amount. If it is a percentage, it will have a percentage sign. After researching, came up with the following solution that works only if a dollar amount is entered but not if percentage is entered. Is there a better solution?
<form name="calculator">
<input type="text" name="cost" placeholder="Cost" onkeyup="calculate()">
<input type="text" name="fee" placeholder="fee" onkeyup="calculate()">
<br>
<p>The answer is: </p>
<p id="testAnswer"></p>
</form>
<script type="text/javascript" >
function calculate(){
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
if(b==""){
var result1= a;
} else {
if (/^\d+(\.\d+)?%$/.test(b)) {
result1 =(1+b)*a;
} else {
var result1 = b+a;
}
}
document.getElementById("testAnswer").innerHTML = result1;
}
</script>
Because you are converting the input to a number with:
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
Any symbols will cause that conversion to fail and therefore you wouldn't be able to perform your test.
var num = Number("234.50%");
console.log(num); // Not a Number
Instead, before doing the conversion, just simply test for the presence of the symbol with .indexOf which returns -1 when the test can't find a match.
var a = document.getElementById("num1");
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
var unit = null;
if(input.indexOf("%") > -1){
unit = "Percent";
} else if(input.indexOf("$") > -1) {
unit = "Dollar";
}
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<input type="text" id="num1">
Having said all of that, I agree with the comments that a better way to handle this is by not asking the user to input the unit at all and just provide radio buttons:
var a = document.getElementById("num1");
// Set up click event for radio buttons that enables number input
Array.prototype.slice.call(document.querySelectorAll("input[name='unit']")).forEach(function(btn){
btn.addEventListener("click", function(){
a.removeAttribute("disabled");
});
});
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
// Just get the value of the selected radio button
var unit = document.querySelector("input[name='unit']:checked").value;
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<!-- If you expect only digits, you can use a number type -->
<input type="radio" name="unit" value="%">%
<input type="radio" name="unit" value="$">$
<input type="number" id="num1" disabled>
I am validating certain input by using RegEx in jQuery which is working as expected. I want to add an addition where it adds 0 prior to decimal point if user don't add it.
For example,
.50 to 0.50
-.50 to -0.50
How to do that?
Code:
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
Change [0-9]+ to [0-9]*, so that it allows zero digits instead of requireing at least one.
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]*([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
You can fix the value like this if you need to convert it later:
if(currentSetTextBoxValue.indexOf('.') === 0){
currentSetTextBoxValue = '0' + currentSetTextBoxValue;
}
if(currentSetTextBoxValue.indexOf('.') === 1 && currentSetTextBoxValue.indexOf('-') === 0){
currentSetTextBoxValue = '-0.' + currentSetTextBoxValue.split('.')[1];
}
https://jsfiddle.net/str59woa/3/
You can replace the input using regex! This regex looks for . or -. at the beginning of the string and it will replace it by 0. or -0. depending on what it found, if it does not match the string will be the same.
$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val().replace(/^(\-)?\./, "$10.");
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />
https://jsfiddle.net/punsm9o0/1/