jQuery search input - javascript

I have got this HTML:
<input type="text" placeholder="Type country name" class="Cinp">
<div class="contres"></div>
And this jQuery code:
var country_list= ["Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan"];
var results = [];
var selected= [];
$(".Cinp").keyup(function(e) {
var value=$(this).val();
if (e.which >= 65 && e.which <= 90 || e.which==8) {
if (value.length!=0) {
function filter(letter) {
var len = country_list.length;
var i = 0;
while(i < len) {
if (country_list[i].indexOf(letter) == 0 || country_list[i].indexOf(letter.toUpperCase()) == 0 ) {
results.push(country_list[i]);
$(".contres").append(country_list[i]);
}
i++;
}
}
}
}
}
So it works perfectly when I type only first letter, but when I type Az it should return Azerbaijan only but it returns all countries that start with a.

$(".contres").clear(); /// whether need that?
while(i < len) {
if (country_list[i].indexOf(letter) == 0 || country_list[i].indexOf(letter.toUpperCase()) == 0 ){
results.push(country_list[i]);
$(".contres").append(country_list[i]);
}
i++;
}
}

Related

Input custom US telephone mask omitted while backspacing

I've created a custom US telephone mask on input using jQuery like -
(___) ___-____
It's working fine on keydown event.
var telMask = "(___) ___-____";
var phoneNumberBuffer = "";
$(document).ready(function () {
$(".telephone").focus(function () { handleFocus(this); });
$(".telephone").blur(function () { handleBlur(this); });
$(".telephone").keydown(function (event) { formatPhoneNumber(this, event); });
});
function mergePhoneMask() {
var tempMask = telMask;
var tempPos;
for (var i = 0; i < phoneNumberBuffer.length; i++) {
tempPos = tempMask.indexOf("_");
tempMask = tempMask.substr(0, tempPos) + phoneNumberBuffer.charAt(i) + tempMask.substr(tempPos + 1);
}
return tempMask;
}
function setPhoneNumCursor(elem) {
var position = $(elem).val().indexOf("_");
if (position < 0) { position = $(elem).val().length; }
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(position, position);
}
else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', position);
range.moveStart('character', position);
range.select();
}
}
function formatPhoneNumber(elem, e) {
var tempMask = telMask;
var tempPos;
if (e.which == 8) {
phoneNumberBuffer = phoneNumberBuffer.substr(0, phoneNumberBuffer.length - 1);
elem.value = mergePhoneMask();
}
if ((e.which > 47 && e.which < 58) || (e.which > 95 && e.which < 106)) {
if (phoneNumberBuffer.length < 10) {
// numpad keys don't match to charcode
if (e.which > 95 && e.which < 106) {
phoneNumberBuffer += (e.which - 96).toString();
} else {
phoneNumberBuffer += String.fromCharCode(e.which);
}
elem.value = mergePhoneMask();
}
}
//e.preventDefault();
if (phoneNumberBuffer.length == 10 || e.which == 9) {
//$(elem).parent().next().next().find("input").focus();
} else {
setPhoneNumCursor(elem);
}
}
function handleFocus(elem) {
if (elem.value == "") {
elem.value = telMask;
}
setPhoneNumCursor(elem);
}
function handleBlur(elem) {
if (elem.value == telMask) {
elem.value = "";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="control-input">
<input name="telephone" maxlength="14" class="telephone" type="tel" size="14" autocomplete="tel">
</div>
Problem is, while continuing to press the backspace/delete, it removes the "(" at the beginning. I'm not sure if I missed anything here! I've some limitations to use other plugins. Thanks!
I've created a JSFiddle here!

html5 phone input validation wont submit even tho the pattern is correct

I have some java script to help the user with the phone number and prevent the form from being submitted in till the field has a valid phone number.
How ever even with a valid number it keeps telling me to use the format thats already predetermined. What am I doing worng im going to assume it has something to do with the pattern.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var ua = navigator.userAgent,
iPhone = /iphone/i.test(ua),
chrome = /chrome/i.test(ua),
android = /android/i.test(ua),
caretTimeoutId;
$.mask = {
//Predefined character definitions
definitions: {
'9': "[0-9]",
'a': "[A-Za-z]",
'*': "[A-Za-z0-9]"
},
autoclear: true,
dataName: "rawMaskFn",
placeholder: '_'
};
$.fn.extend({
//Helper Function for Caret positioning
caret: function(begin, end) {
var range;
if (this.length === 0 || this.is(":hidden") || this.get(0) !== document.activeElement) {
return;
}
if (typeof begin == 'number') {
end = (typeof end === 'number') ? end : begin;
return this.each(function() {
if (this.setSelectionRange) {
this.setSelectionRange(begin, end);
} else if (this.createTextRange) {
range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
});
} else {
if (this[0].setSelectionRange) {
begin = this[0].selectionStart;
end = this[0].selectionEnd;
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return { begin: begin, end: end };
}
},
unmask: function() {
return this.trigger("unmask");
},
mask: function(mask, settings) {
var input,
defs,
tests,
partialPosition,
firstNonMaskPos,
lastRequiredNonMaskPos,
len,
oldVal;
if (!mask && this.length > 0) {
input = $(this[0]);
var fn = input.data($.mask.dataName)
return fn?fn():undefined;
}
settings = $.extend({
autoclear: $.mask.autoclear,
placeholder: $.mask.placeholder, // Load default placeholder
completed: null
}, settings);
defs = $.mask.definitions;
tests = [];
partialPosition = len = mask.length;
firstNonMaskPos = null;
mask = String(mask);
$.each(mask.split(""), function(i, c) {
if (c == '?') {
len--;
partialPosition = i;
} else if (defs[c]) {
tests.push(new RegExp(defs[c]));
if (firstNonMaskPos === null) {
firstNonMaskPos = tests.length - 1;
}
if(i < partialPosition){
lastRequiredNonMaskPos = tests.length - 1;
}
} else {
tests.push(null);
}
});
return this.trigger("unmask").each(function() {
var input = $(this),
buffer = $.map(
mask.split(""),
function(c, i) {
if (c != '?') {
return defs[c] ? getPlaceholder(i) : c;
}
}),
defaultBuffer = buffer.join(''),
focusText = input.val();
function tryFireCompleted(){
if (!settings.completed) {
return;
}
for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) {
if (tests[i] && buffer[i] === getPlaceholder(i)) {
return;
}
}
settings.completed.call(input);
}
function getPlaceholder(i){
if(i < settings.placeholder.length)
return settings.placeholder.charAt(i);
return settings.placeholder.charAt(0);
}
function seekNext(pos) {
while (++pos < len && !tests[pos]);
return pos;
}
function seekPrev(pos) {
while (--pos >= 0 && !tests[pos]);
return pos;
}
function shiftL(begin,end) {
var i,
j;
if (begin<0) {
return;
}
for (i = begin, j = seekNext(end); i < len; i++) {
if (tests[i]) {
if (j < len && tests[i].test(buffer[j])) {
buffer[i] = buffer[j];
buffer[j] = getPlaceholder(j);
} else {
break;
}
j = seekNext(j);
}
}
writeBuffer();
input.caret(Math.max(firstNonMaskPos, begin));
}
function shiftR(pos) {
var i,
c,
j,
t;
for (i = pos, c = getPlaceholder(pos); i < len; i++) {
if (tests[i]) {
j = seekNext(i);
t = buffer[i];
buffer[i] = c;
if (j < len && tests[j].test(t)) {
c = t;
} else {
break;
}
}
}
}
function androidInputEvent(e) {
var curVal = input.val();
var pos = input.caret();
if (oldVal && oldVal.length && oldVal.length > curVal.length ) {
// a deletion or backspace happened
checkVal(true);
while (pos.begin > 0 && !tests[pos.begin-1])
pos.begin--;
if (pos.begin === 0)
{
while (pos.begin < firstNonMaskPos && !tests[pos.begin])
pos.begin++;
}
input.caret(pos.begin,pos.begin);
} else {
var pos2 = checkVal(true);
var lastEnteredValue = curVal.charAt(pos.begin);
if (pos.begin < len){
if(!tests[pos.begin]){
pos.begin++;
if(tests[pos.begin].test(lastEnteredValue)){
pos.begin++;
}
}else{
if(tests[pos.begin].test(lastEnteredValue)){
pos.begin++;
}
}
}
input.caret(pos.begin,pos.begin);
}
tryFireCompleted();
}
function blurEvent(e) {
checkVal();
if (input.val() != focusText)
input.change();
}
function keydownEvent(e) {
if (input.prop("readonly")){
return;
}
var k = e.which || e.keyCode,
pos,
begin,
end;
oldVal = input.val();
//backspace, delete, and escape get special treatment
if (k === 8 || k === 46 || (iPhone && k === 127)) {
pos = input.caret();
begin = pos.begin;
end = pos.end;
if (end - begin === 0) {
begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
end=k===46?seekNext(end):end;
}
clearBuffer(begin, end);
shiftL(begin, end - 1);
e.preventDefault();
} else if( k === 13 ) { // enter
blurEvent.call(this, e);
} else if (k === 27) { // escape
input.val(focusText);
input.caret(0, checkVal());
e.preventDefault();
}
}
function keypressEvent(e) {
if (input.prop("readonly")){
return;
}
var k = e.which || e.keyCode,
pos = input.caret(),
p,
c,
next;
if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
return;
} else if ( k && k !== 13 ) {
if (pos.end - pos.begin !== 0){
clearBuffer(pos.begin, pos.end);
shiftL(pos.begin, pos.end-1);
}
p = seekNext(pos.begin - 1);
if (p < len) {
c = String.fromCharCode(k);
if (tests[p].test(c)) {
shiftR(p);
buffer[p] = c;
writeBuffer();
next = seekNext(p);
if(android){
//Path for CSP Violation on FireFox OS 1.1
var proxy = function() {
$.proxy($.fn.caret,input,next)();
};
setTimeout(proxy,0);
}else{
input.caret(next);
}
if(pos.begin <= lastRequiredNonMaskPos){
tryFireCompleted();
}
}
}
e.preventDefault();
}
}
function clearBuffer(start, end) {
var i;
for (i = start; i < end && i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
}
}
}
function writeBuffer() { input.val(buffer.join('')); }
function checkVal(allow) {
//try to place characters where they belong
var test = input.val(),
lastMatch = -1,
i,
c,
pos;
for (i = 0, pos = 0; i < len; i++) {
if (tests[i]) {
buffer[i] = getPlaceholder(i);
while (pos++ < test.length) {
c = test.charAt(pos - 1);
if (tests[i].test(c)) {
buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length) {
clearBuffer(i + 1, len);
break;
}
} else {
if (buffer[i] === test.charAt(pos)) {
pos++;
}
if( i < partialPosition){
lastMatch = i;
}
}
}
if (allow) {
writeBuffer();
} else if (lastMatch + 1 < partialPosition) {
if (settings.autoclear || buffer.join('') === defaultBuffer) {
// Invalid value. Remove it and replace it with the
// mask, which is the default behavior.
if(input.val()) input.val("");
clearBuffer(0, len);
} else {
// Invalid value, but we opt to show the value to the
// user and allow them to correct their mistake.
writeBuffer();
}
} else {
writeBuffer();
input.val(input.val().substring(0, lastMatch + 1));
}
return (partialPosition ? i : firstNonMaskPos);
}
input.data($.mask.dataName,function(){
return $.map(buffer, function(c, i) {
return tests[i]&&c!=getPlaceholder(i) ? c : null;
}).join('');
});
input
.one("unmask", function() {
input
.off(".mask")
.removeData($.mask.dataName);
})
.on("focus.mask", function() {
if (input.prop("readonly")){
return;
}
clearTimeout(caretTimeoutId);
var pos;
focusText = input.val();
pos = checkVal();
caretTimeoutId = setTimeout(function(){
if(input.get(0) !== document.activeElement){
return;
}
writeBuffer();
if (pos == mask.replace("?","").length) {
input.caret(0, pos);
} else {
input.caret(pos);
}
}, 10);
})
.on("blur.mask", blurEvent)
.on("keydown.mask", keydownEvent)
.on("keypress.mask", keypressEvent)
.on("input.mask paste.mask", function() {
if (input.prop("readonly")){
return;
}
setTimeout(function() {
var pos=checkVal(true);
input.caret(pos);
tryFireCompleted();
}, 0);
});
if (chrome && android)
{
input
.off('input.mask')
.on('input.mask', androidInputEvent);
}
checkVal(); //Perform initial check for existing values
});
}
});
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<?php
session_start();
$token= md5(uniqid());
$_SESSION['delete_customer_token']= $token;
session_write_close();
?>
<!DOCTYPE html>
<head>
<title>index</title>
<script src="js/jquery-1.9.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.mask.definitions['~'] = "[+-]";
$("#phone").mask("1 (999) 999-9999");
$("input").blur(function() {
$("#info").html("Unmasked value: " + $(this).mask());
}).dblclick(function() {
$(this).unmask();
});
});
</script>
</head>
<body>
<form id="msform" method="post" action=""/>
<input type="hidden" name="token" value="<?php echo $token; ?>"/>
<input type="hidden" name="miles" value=""/>
<div id="formwrap">
<div id="ftx1">FIRST NAME</div>
<input type="text" name="fname" class="box" maxlength="40" min="9" max="40" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">LAST NAME</div>
<input type="text" name="lname" class="box" maxlength="40" min="9" max="40" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">BUSINESS NAME:</div>
<input id="busname" name="busname" class="element text medium" type="text" maxlength="40" value="" placeholder=""/>
</div>
<div id="formwrap">
<div id="ftx1">TYPE OF BUSINESS:*</div>
<input id="bustype" type="bustype" name="bustype" size="" maxLength="64"
placeholder=""
title="">
</div>
<div id="formwrap">
<div id="ftx1">EMAIL: *</div>
<input id="email" type="" name="email" size="" maxLength="64"
placeholder=""
title="Please provide only a email address" novalidate/>
</div>
<div id="formwrap">
<div id="ftx1">PHONE NUMBER: *</div>
<input id="phone" name="phone" class="element text medium" maxlength="" value="" placeholder="PHONE NUMBER" type="tel" pattern="[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}" title="Phone Number Format:1 (614) 000-0000" />
</div>
<br><br><br><br>
<input id="submit" class="button_text" type="submit" name="submit" value="SUBMIT" />
<div id="error"></div>
<h2>contact you within 24h. Thank You!</h2>
</form>
</body>
</html>
Your regular expression and field mask combination is incorrect.
[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4} will never match because (a) your mask is configured for North American-style phone numbers (it will match phone numbers in the same format as +91(12)3456-7890), and (b) your mask is not configured with a + at the beginning of the input.
You may be looking for something similar to the following to validate the field itself:
1 \(\d{3}\) \d{3}\-\d{4}
Regex101

Check password strength against an API value

I get my password spec from an API which then I split the object into the needed fields and check that I have the required number of lower, upper, special and length of my password.
function isStrong(passwordChecker) {
if (!passwordChecker) {
return false;
}
debugger;
var securityOption = JSON.parse(localStorage.getItem("Security"));
var MinLength = securityOption.PasswordMinRequiredLength;
var SpecialChars = securityOption.PasswordMinRequiredNonalphanumericCharacters;
var MinLowercase = securityOption.PasswordMinRequiredLowercase;
var MinUppercase = securityOption.PasswordMinRequiredUppercase;
//LenghtCheck
if (passwordChecker.length < MinLength);
return false;
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
if (MinLowercase > 0) {
if (!CountLowerCase(passwordChecker) > MinLowercase) {
return false;
}
}
if (MinUppercase > 0) {
if (!CountUpperCase(passwordChecker) > MinLowercase) {
return false;
}
}
}
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
function MinLowercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 97 && text[i] <= 122) {
Count++;
}
}
}
function MinUppercase(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 65 && text[i] <= 90) {
Count++;
}
}
}
Now what I want to do is, check the different conditions as a whole and if all of the conditions are true then change the class to green..
$(pageId + ' #password').bind('keyup', function () {
var currentpassword = $(pageId + ' #password').val();
if (isStrong(currentpassword)) {
$(pageId + ' #password').addClass('green');
} else {
$(pageId + ' #password').addClass('red');
}
});
I am not sure how to check the conditions as a whole and return an overall true because as I start trying in my password it instantly changes to green as in my password spec you do not need any UpperCase or LowerCase letters so on any input of a char it returns true..
You should refactor your functions so that they accept both the string and the parameter and return true or false. For example:
function CountSpecialChars(text) {
var Count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
Count++;
}
}
}
if (!CountSpecialChars(passwordChecker) > SpecialChars) {
return false;
}
Should instead be:
function CountSpecialChars(text, min) {
var count = 0;
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (text[i] >= 33 && text[i] <= 63){
count++;
}
}
return count > min;
}
return CountSpecialChars(passwordChecker, SpecialChars);
Also, as a bonus, you could also avoid that for loop for those functions by using replace, like so:
function MinChars(text, min) {
return text.length > min;
}
function MinUppercase(text, min) {
var non_uppers = /[^A-Z]/g;
var uppers = text.replace(non_uppers, text);
return uppers.length > min;
}
function MinLowercase(text, min) {
var non_lowers = /[^a-z]/g;
var lowers = text.replace(non_lowers, text);
return lowers.length > min;
}
function MinSpecialChars(text, min) {
var non_specials = /[^!-\?]/g;
var specials = text.replace(non_specials, text);
return specials.length > min;
}
Now with those functions, you can have:
if !MinChars(pw, MinLength) return false;
if !MinSpecialChars(pw, SpecialChars) return false;
if !MinLowercase(pw, MinLowercase) return false;
if !MinUppercase(pw, MinUppercase) return false;
return true;

Game of life in JavaScript - using Table

I finished coding Conway's Game of Life in JavaScript and HTML table.
logic cells in a table will be assigned with unique id's and based on the id operations(based 4 rules) take place.
You can find the working code at Codepen or i have put the code below.
The thing is it works well with any number of rows and 9 columns and if more than 9 columns are given their wont be unique id's so it works in undesired manner.
Query Is their a way where i can assign the whole table with unique id's.
Code block tableInitialization is the initialization part.
(function(){
$(document).ready(function(){
var column = "", appendRow = "", inc = 1, selectedCells = [], toRemoveClass = [], toAddClass = [], maxValue;
var tableInitialization = function(noOfRow, noOfColumn){
for(var row=1; row<=noOfRow; row++){
for(var col=1; col<=noOfColumn; col++){
column += "<td id =" + inc+col + "> </td>";
}
appendRow += "<tr>"+column+"</tr>";
column= "";
inc++;
}
$(".table").append(appendRow);
};
$("#submit").click(function(data){
var noOfRow = parseInt($("#rowNo").val());
var noOfColumn = parseInt($("#columnNo").val());
maxValue = parseInt(noOfRow.toString() + noOfColumn.toString());
if(isNaN(noOfRow) || isNaN(noOfColumn)){
alert("Please enter number");
} else {
tableInitialization(noOfRow, noOfColumn);
$("#container").hide();
$("td").click( function(data){
selectedCells.push(parseInt(this.id));
$(this).addClass("valid");
});
}
});
var checkAgain = function(selectedCells){
var check = 0, toBeReplaced = [], inArray = [], livingCell;
var currentNumber = 0;
var north, northEast, East, southEast, south, southWest, west, northWest;
for(var i=0; i<selectedCells.length; i++){
check = 0;
currentNumber = parseInt(selectedCells[i]);
if($("#"+(currentNumber)).hasClass("valid")){
livingCell = true;
} else {
livingCell = false;
}
if(currentNumber > 0 && currentNumber < maxValue){
/*North*/
if((currentNumber-10) > 0 && (currentNumber-10) < maxValue){
if($("#"+(currentNumber-10)).hasClass("valid")){
check ++;
}
}
/*North East*/
if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){
if($("#"+(currentNumber-9)).hasClass("valid")){
check ++;
}
}
/*East*/
if((currentNumber+1) > 0 && (currentNumber+1) < maxValue){
if($("#"+(currentNumber+1)).hasClass("valid")){
check ++;
}
}
/*South East*/
if((currentNumber+11) > 0 && (currentNumber+11) < maxValue){
if($("#"+(currentNumber+11)).hasClass("valid")){
check ++;
}
}
/*South*/
if((currentNumber+10) > 0 && (currentNumber+10) < maxValue){
if($("#"+(currentNumber+10)).hasClass("valid")){
check ++;
}
}
/*South West*/
if((currentNumber+9) > 0 && (currentNumber+9) < maxValue){
if($("#"+(currentNumber+9)).hasClass("valid")){
check ++;
}
}
/*West*/
if((currentNumber-1) > 0 && (currentNumber-1) < maxValue){
if($("#"+(currentNumber-1)).hasClass("valid")){
check ++;
}
}
/*North West*/
if((currentNumber-11) > 0 && (currentNumber-11) < maxValue){
if($("#"+(currentNumber-11)).hasClass("valid")){
check ++;
}
}
if(livingCell){
if(check === 0 || check === 1 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 4 || check == 5 || check == 6 || check == 7 || check == 8 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 2 || check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
} else {
if(check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
}
}
}
};
var gol = function(selectedCells){
var check = 0, inArray = [];
var currentNumber = 0, livingCell;
for(var i=0; i<selectedCells.length; i++){
toBeReplaced = [];
check = 0;
currentNumber = parseInt(selectedCells[i]);
if($("#"+(currentNumber)).hasClass("valid")){
livingCell = true;
} else {
livingCell = false;
}
if(currentNumber > 0 && currentNumber < maxValue){
/*North*/
if((currentNumber-10) > 0 && (currentNumber-10) < maxValue){
if($("#"+(currentNumber-10)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-10)) == -1){
toBeReplaced.push(currentNumber-10);
}
}
/*North East*/
if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){
if($("#"+(currentNumber-9)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-9)) == -1){
toBeReplaced.push(currentNumber-9);
}
}
/*East*/
if((currentNumber+1) > 0 && (currentNumber+1) < maxValue){
if($("#"+(currentNumber+1)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+1)) == -1){
toBeReplaced.push(currentNumber+1);
}
}
/*South East*/
if((currentNumber+11) > 0 && (currentNumber+11) < maxValue){
if($("#"+(currentNumber+11)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+11)) == -1){
toBeReplaced.push(currentNumber+11);
}
}
/*South*/
if((currentNumber+10) > 0 && (currentNumber+10) < maxValue){
if($("#"+(currentNumber+10)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+10)) == -1){
toBeReplaced.push(currentNumber+10);
}
}
/*South West*/
if((currentNumber+9) > 0 && (currentNumber+9) < maxValue){
if($("#"+(currentNumber+9)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+9)) == -1){
toBeReplaced.push(currentNumber+9);
}
}
/*West*/
if((currentNumber-1) > 0 && (currentNumber-1) < maxValue){
if($("#"+(currentNumber-1)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-1)) == -1){
toBeReplaced.push(currentNumber-1);
}
}
/*North West*/
if((currentNumber-11) > 0 && (currentNumber-11) < maxValue){
if($("#"+(currentNumber-11)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-11)) == -1){
toBeReplaced.push(currentNumber-11);
}
}
if(livingCell){
if(check == 0 || check == 1 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 4 || check == 5 || check == 6 || check == 7 || check == 8 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 2 || check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
} else {
if(check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
}
}
checkAgain(toBeReplaced);
}
for(var i=0; i<toRemoveClass.length; i++){
$("#"+toRemoveClass[i]).removeClass("valid");
}
for(var i=0; i<toAddClass.length; i++){
$("#"+toAddClass[i]).addClass("valid");
}
toBeReplaced = toAddClass;
if(toAddClass.length == 0){
//exit
return;
} else {
setInterval(function(){
gol($.unique(toBeReplaced));
},1000);
}
selectedCells = [];
toAddClass =[];
toRemoveClass = [];
};
start = function(){
if(selectedCells.length == 0){
alert("select cell");
} else {
gol(selectedCells);
}
};
});
})();
body{
background: #BBDEFB ;
}
td {
width: 20px;
height: 20px;
background: #eee;
}
table {
cursor: default;
}
.valid {
background: #00BFA5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Conways Game of Life</title>
<link rel="stylesheet" type="text/css" href="gameOfLife.css">
</head>
<body>
<h1><code>Conway's game of life</code></h1>
<div id="container">
<h2><code>enter row * columns</code></h2>
<form>
<code>row ★ column : </code>
<input id="rowNo" type="text"/> ★
<input id="columnNo" type="text"/>
</form>
<button id="submit"> Submit </button>
<br><br>
</div>
<table class="table"></table>
<br><br>
<button onClick="start()"> start </button>
<br><br>
<h2><code> Rules </code></h2>
<code>1. Any live cell with fewer than two live neighbours dies,
as if caused by underpopulation.</code><br>
<code>2. Any live cell with more than three live neighbours dies,
as if by overcrowding.</code><br>
<code>3. Any live cell with two or three live neighbours lives
on to the next generation.</code><br>
<code>4. Any dead cell with exactly three live neighbours becomes
a live cell.</code>
<script type="text/javascript" src="gameOfLife.js"></script>
</body>
</html>
Without digging really deep into your code. You build the IDs by using col and row index, so you'll get something like 11, 12, 13, 14, 15, ... 110, 111, 112 etc. for the first row. Without a delimiter the ID of the eleventh row first element would be 111 too. As soon as you use a kind of delimiter like '_' your IDs are unique: 1_1, 1_2 again.
for(var row=1; row<=noOfRow; row++){
for(var col=1; col<=noOfColumn; col++){
column += "<td id =" + inc+"_"+col + "> </td>";
/* you also could add data attributes:
data-row=\""+row+"\" data-col=\""+col+"\"
*/
}
appendRow += "<tr>"+column+"</tr>";
column= "";
inc++;
}
Looking into your code, I think you will get other problems, because there is a lot of code related to "10". For example: if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){ - this won't work in case you'll have more than 9 rows. But fixing this would be a rewritten version of the complete game.

Allow to enter only 2 decimal points number

I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:
function isNumberKeyOnlyWithDecimalFormat(event,value,id){
var val = value;
if (event.shiftKey === true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 ||
event.keyCode == 9 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 46 ||
event.keyCode == 190) {
} else {
event.preventDefault();
}
if(val.indexOf('.') !== -1 && event.keyCode == 190){
event.preventDefault();
}
if ((pointPos = $('#'+id).val().indexOf('.')) >= 0){
$('#'+id).attr("maxLength", pointPos+3);
}
else
$('#'+id).removeAttr("maxLength");
}
It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?
Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.
Here is the fiddle: http://jsfiddle.net/sAp9D/
HTML:
<input type="text" id="the_id" />
JavaScript:
var input_field = document.getElementById('the_id');
input_field.addEventListener('change', function() {
var v = parseFloat(this.value);
if (isNaN(v)) {
this.value = '';
} else {
this.value = v.toFixed(2);
}
});
Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this
if( value.match(/\./g).length === 2 ) {
// Number has 2 decimals eg. 1.2.3
} else {
// Number is incorrect eg. 1.2.3.4
}
or if you want 1.2 then
if( value.match(/\./g).length === 1 ) {
// Code....
}
I use the following
// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Backspace
if (whichCode == 0) return true; // Null
if (whichCode == 9) return true; // Tab
key = String.fromCharCode(whichCode); // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false; // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
var exp = /\./;
var a = x.search(exp);
if ( a != -1 ) return false;
}
}
// samer code on change or on blur event
function allow2decimal(obj){
var v = parseFloat($(obj).val());
if (isNaN(v)) {
$(obj).value = '';
} else {
newVal = v.toFixed(2);
if(newVal >= 100){
$(obj).val( 100 );
}else{
$(obj).val(newVal);
}
}
}
//usage
<input
onkeypress="return numericFormat( this , event , '.');"
onchange="allow2decimal(this)"
value="0.1"
id="factory_silk" name="factory_silk" />
<html>
<head>
<script type="text/javascript">
function NumAndTwoDecimals(e, field) {
var val = field.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
}
else {
val = re1.exec(val);
if (val) {
field.value = val[0];
}
else {
field.value = "";
}
}
}
</script>
</head>
<body>
<input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">
</body>
</html>
$('.number').keypress(function(evt){
var str = $(this).val();
var index = str.indexOf('.');
if(index==-1){index=0;}else{index= index+1;}
var extrapoint = str.indexOf('.',index);
if(extrapoint>0){$(this).val(str.slice(0,-1));}
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = $(this).val();
if (validNumber.test($(this).val()))
{
lastValid = $(this).val();
}
else
{
$(this).val(lastValid);
}
});

Categories