I need to paginate an array using previous and next or by specifying the position, onchange of the index the value associated with the corresponding must be displayed.
I have tried with the below code, however i fail to achive
I need to paginate an array using previous and next or by specifying the position, onchange of the index the value associated with the corresponding must be displayed.
I have tried with the below code, however i fail to achive
var resultBox = $('#result')
var messages = ["cat", "dog", "fish"];
var idx = $("#pageNumber").val();
var length = messages.length;
var getNextIdx = (idx = -1, length, direction) => {
switch (direction) {
case '1':
{
$("#pageNumber").val((idx + 1) % length + 1)
return (idx + 1) % length;
}
case '-1':
{
$("#pageNumber").val(((idx == 0) && length - 1 || idx - 1) + 1);
return (idx == 0) && length - 1 || idx - 1;
}
default:
{
return idx;
}
}
}
var getNewIndexAndRender = function(direction) {
idx = getNextIdx(idx, length, direction);
console.log(idx)
$("#result").val(messages[idx])
}
$(document).ready(function() {
$("#pageNumber").change(function() {
getNewIndexAndRender()
});
});
getNewIndexAndRender()
$( "#prev" ).trigger( "click" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="result"></textarea>
<input type="text" id="pageNumber" value="0"></input>
<button id="prev" onclick="getNewIndexAndRender('-1')">prev</button>
<button id="next" onclick="getNewIndexAndRender('1')">next</button>
In your change function, you need to reassign idx with the current input value - 1.
$("#pageNumber").change(function() {
idx = $(this).val() - 1;
getNewIndexAndRender();
});
Demo:
var resultBox = $('#result')
var messages = ["cat", "dog", "fish"];
var idx = $("#pageNumber").val();
var length = messages.length;
var getNextIdx = (idx = -1, length, direction) => {
switch (direction) {
case '1':
{
$("#pageNumber").val((idx + 1) % length + 1)
return (idx + 1) % length;
}
case '-1':
{
$("#pageNumber").val(((idx == 0) && length - 1 || idx - 1) + 1);
return (idx == 0) && length - 1 || idx - 1;
}
default:
{
return idx;
}
}
}
var getNewIndexAndRender = function(direction) {
idx = getNextIdx(idx, length, direction);
$("#result").val(messages[idx]);
}
$(document).ready(function() {
$("#pageNumber").change(function() {
idx = $(this).val() - 1;
getNewIndexAndRender();
});
});
getNewIndexAndRender()
$("#prev").trigger("click");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="result"></textarea>
<input type="text" id="pageNumber" value="0"></input>
<button id="prev" onclick="getNewIndexAndRender('-1')">prev</button>
<button id="next" onclick="getNewIndexAndRender('1')">next</button>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code bellow works fine, though as u can see, everything is hand wrote and if i want to push something to that arrays i will have to change whole code.
working example:
for (var s = 0; s < myButtons.length; s++) {
if (
(myButtons[s].className == "1" && colorIndex[0] > 1)
||
(myButtons[s].className == "2" && colorIndex[1] > 1)
||
(myButtons[s].className == "3" && colorIndex[2] > 1)
||
(myButtons[s].className == "4" && colorIndex[3] > 1)
||
(myButtons[s].className == "5" && colorIndex[4] > 1)
||
(myButtons[s].className == "6" && colorIndex[5] > 1)
) {continue;}
alert("things need to be done")
}
the best solution came to my mind(not working one):
for (var s = 0; s < myButtons.length; s++) {
for (var i = 0; i < colorIndex.length; i++) {
if ((myButtons[s].className == (i + 1) && colorIndex[i] > 1)) {
continue;
}
alert("things need to be done")
}
}
So what i want is: to check if all elements of array myButtons.classname==variable from cycle && colorIndex[variable from cycle]>1 OR same thing again but on next step
working code for the first algorithm
const colorIndex = []
colorIndex[0] = 201
colorIndex[1] = 30002
colorIndex[19] = -25
colorIndex[3] = 89
colorIndex[-7] = 89
colorIndex[-9] = -26
const myButtons = [...document.querySelectorAll("button")]
for (var s = 0; s < myButtons.length; s++)
{
if ( (myButtons[s].className == "1" && colorIndex[0] > 1)
|| (myButtons[s].className == "2" && colorIndex[1] > 1)
|| (myButtons[s].className == "3" && colorIndex[2] > 1)
|| (myButtons[s].className == "4" && colorIndex[3] > 1)
|| (myButtons[s].className == "5" && colorIndex[4] > 1)
|| (myButtons[s].className == "6" && colorIndex[5] > 1)
)
{ continue }
alert("things need to be done")
}
console.log('test ending')
<button class="1">1</button>
<button class="2">2</button>
<button class="4">3</button>
<button class="4">4</button>
<button class="4">5</button>
<button class="4">6</button>
<button class="4">7</button>
<button class="2">8</button>
<button class="4">9</button>
Here a pretty short and less hard coded version of the original code
var myButtons = document.querySelectorAll("button");
var colorIndex = [0, 1, 2, 0, 2, 1];
for (var index = 0; index < myButtons.length; index++) {
if (myButtons[index].className == String(index + 1)
&& colorIndex[myButtons[index].className - 1] > 1) continue;
console.log("Button at index '" + index + "' needs to get fixed");
}
<button class="1">1</button>
<button class="2">2</button>
<button class="3">3</button>
<button class="4">4</button>
<button class="5">5</button>
<button class="6">6</button>
Full code attempt:
// Create Buttons Start
var buttonDom = document.getElementById("a1");
var buttonList = [],
buttonCount = 12;
while (buttonList.length < buttonCount) {
var newInput = document.createElement("input");
newInput.type = "button";
buttonList.push(newInput);
buttonDom.appendChild(newInput);
}
var randomList1 = [];
while (randomList1.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList1.indexOf(random) === -1) randomList1.push(random);
}
var randomList2 = [];
while (randomList2.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList2.indexOf(random) === -1) randomList2.push(random);
}
randomList1.forEach((random, index) => buttonList[index].setAttribute("class", random));
randomList2.forEach((random, index) => buttonList[index + buttonCount / 2].setAttribute("class", random));
// Game Start
var myButtons = document.querySelectorAll("input[type='button']");
var click = 1;
var colorIndex = "0".repeat(6).split("").map(Number);
var color = ["red", "blue", "green", "black", "gold", "grey"];
myButtons.forEach(button => button.addEventListener("click", game));
function clickTrun() {
click = !click | 0;
}
function win() {
if (colorIndex.every(i => i == 2)) {
alert("YOU WON mdfker!");
location.reload();
}
}
function resetColorIndex() {
if (click === 1) {
colorIndex = colorIndex.map(function(colorValue) {
return colorValue < 2 ? 0 : colorValue;
});
}
}
function mainGameRules() {
setTimeout(function() {
resetColorIndex();
if (click === 1) {
myButtons.forEach(function(button) {
if (colorIndex[button.className - 1] > 1) return;
button.setAttribute("style", "background-color: none;");
button.disabled = false;
});
}
}, 700);
}
function game() {
this.disabled = true;
var index = this.className - 1;
if (index in colorIndex) {
this.setAttribute("style", "background-color:" + color[index]);
colorIndex[index]++;
mainGameRules();
clickTrun();
}
win();
}
<div id="a1">
</div>
You just need to formulate what you want to do and express it in code. Without sticking to concrete index, try to figure out how any possible index corresponds to particular color. Looking at your example you want to take className for every button, subtract 1 and take color from colorIndex and do something if that color is less than or equal to 1
for (let i = 0; i < myButtons.length; i++) {
// className for current button
const className = myButtons[i].className
// parse it into number
const num = Number(className)
// if number is valid, take element from colorIndex at number-1 position
// and see if that's not bigger than 1
if (num && colorIndex[num - 1] <= 1) {
console.log('things need to be done for index ' + i)
}
}
but my suggestion would be to reconsider your existing setup with myButtons and colorIndex into something more sophisticated
I have to format an account number input field like below:
Desired format: 123456 1234 12 1
But, the regex which I wrote formats the text field as below:
Current format: 1234 1234 1234 1
Can someone please help me with the correct regex or logic to implement this?
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,13}/g);
var match = matches && matches[0] || ''
var parts = []
for (i = 0, len = match.length; i < len; i += 4) {
parts.push(match.substring(i, i + 4))
}
if (parts.length) {
return parts.join(' ')
} else {
return value
}
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
You can get groups of 6, instead of groups of 4, then, as soon as your second group gets over 4 characters long, you can insert a space at the desired position. Here's a proof of concept:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{6,13}/g);
var match = matches && matches[0] || ''
var parts = []
for (i = 0, len = match.length; i < len; i += 6) {
parts.push(match.substring(i, i + 6))
}
if (parts.length > 1 && parts[1].length > 4) {
parts[1] = [parts[1].slice(0, 4), ' ', parts[1].slice(4)].join('');
}
if (parts.length) {
return parts.join(' ')
} else {
return v
}
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
A slightly more elegant solution would be to use .slice() and .join() for the whole thing, which cleans up the code nicely. Here's an example:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
if (v.length > 6)
v = [v.slice(0, 6), ' ', v.slice(6)].join('');
if (v.length > 11)
v = [v.slice(0, 11), ' ', v.slice(11)].join('');
if (v.length > 14)
v = [v.slice(0, 14), ' ', v.slice(14)].join('');
if (v.length > 16)
v = v.slice(0, 16);
return v;
}
onload = function() {
document.getElementById('account-number').oninput = function() {
this.value = cc_format(this.value)
}
}
<form>
<div>AccountNumber</div><br/>
<input id="account-number" value="" placeholder="123456 1234 12 1">
</form>
You can use following code, to format the code properly when user is typing. It works dynamically.
const normalize = elem => {
let value = elem.target.value;
const onlyNums = value.replace(/[^\d]/g, '');
if (onlyNums.length <= 6) {
return onlyNums;
} else if (onlyNums.length <= 10) {
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6)}`;
} else if (onlyNums.length <= 12) {
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6, 10)} ${onlyNums.slice(10, 12)}`;
}
return `${onlyNums.slice(0, 6)} ${onlyNums.slice(6, 10)} ${onlyNums.slice(10, 12)}
${onlyNums.slice(12, 13)}`;
};
const input = document.getElementById('input');
input.addEventListener('input', (e) => e.target.value = normalize(e));
<input type='text' id='input' value=''>
I wrote this code to validate credit card digits, saved it as an html file. It's not working though.
<html>
<head>
<script>
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
</script>
</head>
<body>
<form>
<input type="text"
name="cc_number"
onblur="if(mod10_check(this.value)){$('#cc_error').hide(); } else { $('#cc_error').show(); }"
value="" />
<span id="cc_er`enter code here`ror" style="display:none;">The card number is invalid.</span>
</form>
</body>
</html>
Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?
Try re-writing your inline code as an event handler.
var ccInp = document.getElementById('cc_no');
ccInp.addEventListener('blur', function() {
if(!mod10_check(ccInp.value)) {
document.getElementById('cc_error').style.display = '';
}
});
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
<form>
<input type="text"
name="cc_number"
value=""
id="cc_no"/>
<span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
jsFiddle: http://jsfiddle.net/8kyhtny2/
I am writing a function that will return an array with prime numbers.
The function should return an array with n elements. (n is a parameter) But it returns only one element. Why?
My codes:
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
else if (res == 0 && initNum == currCompose)
{
arr[currIndex] = initNum;
++currIndex;
break;
}
else if (res != 0 && initNum != currCompose)
{
continue;
}
else
{
console.log("Impossible result!");
}
}
}
return arr;
}
findPrimes(2); //return 2
findPrimes(10); //return 2 too
Jsbin
You should not be comparing initNum to currCompose. Keep in mind that initNum is the number you are checking (say, 71), and currCompose will be at most ceil(sqrt(initNum)) (say 9), so the two will never be equal.
Also note that it is best to append to the list and verify that no divisors where found only after the inner loop has finished.
This modified version works.
function findPrimes(n)
{
var arr = [];
var currIndex = 0;
var sqrtNum;
var ceiledNum;
var ceiledIndex = 0;
var currCompose;
var res;
var initNum;
for (initNum = 2; arr.length < n; ++initNum)
{
sqrtNum = Math.sqrt(initNum);
ceiledNum = Math.ceil(sqrtNum);
for (currCompose = 2; currCompose <= ceiledNum; ++currCompose)
{
res = initNum % currCompose;
if (res == 0 && initNum != currCompose)
{
break;
}
}
if (currCompose == ceiledNum+1)
{
arr[currIndex] = initNum;
++currIndex;
}
}
return arr;
}
var primes = findPrimes(6);
document.write(primes);
correct Line 14 of your code as follows and it works like charm.
for (currCompose = 2; currCompose <= initNum; ++currCompose)
function FindPrime(numbers){
if(numbers.constructor === Array){
output = [];
for (var i = numbers.length - 1; i >= 0; i--) {
if(isPrime(numbers[i]) == true){
output.push(numbers[i]);
};
};
return output;
}
}
function isPrime(numb){
if (numb % 2 == 0) return false;
for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
if (numb % i == 0) {
return false;
}
}
return true;
}
numbers = [1,2,3,4,5];
test = FindPrime(numbers);
console.log('testing', test);
I'm trying to make a palindrome checker that changes the currently compared letters as it recurs.
Essentially, callback will do:
r aceca r
r a cec a r
ra c e c ar
rac e car
My JS Bin shows that the compared letters change green sometimes, but if you run it again, the letters won't change. Why is there a difference in results? It seems to sometimes run in Chrome, more often in FireFox, but it's all intermittent.
Code if needed (also available in JS Bin):
var myInterval = null;
var container = [];
var i, j;
var set = false;
var firstLetter, lastLetter;
$(document).ready(function(){
$("#textBox").focus();
$(document).click(function() {
$("#textBox").focus();
});
});
function pal (input) {
var str = input.replace(/\s/g, '');
var str2 = str.replace(/\W/g, '');
if (checkPal(str2, 0, str2.length-1)) {
$("#textBox").css({"color" : "green"});
$("#response").html(input + " is a palindrome");
$("#palindromeRun").html(input);
$("#palindromeRun").lettering();
if (set === false) {
callback(str2);
set = true;
}
}
else {
$("#textBox").css({"color" : "red"});
$("#response").html(input + " is not a palindrome");
}
if (input.length <= 0) {
$("#response").html("");
$("#textBox").css({"color" : "black"});
}
}
function checkPal (input, i, j) {
if (input.length <= 1) {
return false;
}
if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) {
return true;
}
else {
if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) {
return checkPal(input, ++i, --j);
}
else {
return false;
}
}
}
function callback(input) {
$("#palindromeRun span").each(function (i, v) {
container.push(v);
});
i = 0;
j = container.length - 1;
myInterval = setInterval(function () {
if (i === j || ((j-i) === 1 && input.charAt(i) === input.charAt(j))) {
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
$(container[i]).css({"color": "green"});
$(container[j]).css({"color": "green"});
i++;
j--;
}, 1000);
}
HTML:
<input type="text" id="textBox" onkeyup="pal(this.value);" value="" />
<div id="response"></div>
<hr>
<div id="palindromeRun"></div>
I directly pasted the jsLettering code in the JSBin, but here is the CDN if needed:
<script src="http://letteringjs.com/js/jquery.lettering-0.6.1.min.js"></script>
Change:
myInterval = setInterval(function () {
if (i === j) {
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
to:
myInterval = setInterval(function () {
if (i >= j) {//Changed to prevent infinite minus
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
demo