Appending conditions in a numerical loop (JavaScript) - javascript

I have four IF statements, is it possible to rewrite this into a neater loop, where the [i] may be '4' or higher.
if (typed.length == 1 && c.charAt(0) == typed[0]) {
//something ;
return false;
}
if (typed.length == 2 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1]) {
//something ;
return false;
}
if (typed.length == 3 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1] && c.charAt(2) == typed[2]) {
//something ;
return false;
}
if (typed.length == 4 && c.charAt(0) == typed[0]
&& c.charAt(1) == typed[1] && c.charAt(2) == typed[2]
&& c.charAt(3) == typed[3]) {
//something ;
return false;
}

Looks to me like something like this should to it:
if (c.substr(0, typed.length) == typed)
Possibly typed.join() if typed is an array.

Try this
for(var x=0; x<typed.length; x++)
{
if(c.chatAt(x)!=typed[x]) { return false; }
}
return true;

for (var i=1; i<=4; ++i){
if (typed.length!=i) continue;
var OK = true;
for (var j=0;j<i;++j){
OK = OK && (c.charAt(0)==typed[j]);
}
if (OK){
// something
return false;
}
}

Forget about two nested loops, or assuming c and typed are "ordered", just look for the char in c
for (var i=0; i<typed.length; i++) {
if (c.indexOf(typed.charAt(i)) >= 0) { // or c.indexOf(typed.charAt(i)) == i
return false;
}
}
return true;

Related

I don't want to allow a 9 digit number in my textbox which is in format:123-12-1234 or 123456789

I am trying like this:
function k(){
var x = $('#textArea').val();
for (i = 0; i < x.length; i++)
{
if(x[i].match(/^[0-9]/))
{
if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/))
{
if(x[i+11].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/))
{
if(x[i+9].match(/^[0-9]/))
{
return 'true';
}
else
{
return false;
}
}
else
{
continue;
}
}
else
{
continue;
}
}
return 'true';
}
Or simply
var x = $('#textArea').val();
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
Or if you only want to allow - and digits
var x = $('#textArea').val();
var matches = x.match( /[0-9-]/g ).length;
if ( !matches || matches.length != x.length )
{
return false;
}
x = x.replace(/\D+/g,""); //first remove all non-digits from x
if (x.length <= 8 )
{
return true;
}
return false;
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
or using pure regexp
to match the 123-45-678 and 12345678 formats:
var x = $('#textArea').val();
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) {
return true;
} else return false;
to match any number less then 9 digits:
var x = $('#textArea').val();
if (x.match(/^(?:\d-?){1,8}$/) {
return true;
} else return false;

Datatables multiple select afnFiltering

I have multiple select menus which are used to filter a table using jquery datatables.
The following code i use works brilliant, but for this example I am only using 3 select menus.
I now have a table which will be using upwards of 10.
Is there a better way of writing this so I don't have to write every variation of matches.
//UPDATE
If I put the select vars and the tabledata column vars in array can I iterate through them.
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
if ( oSettings.nTable == document.getElementById( 'logtable' ))
{
var nature_of_complaint = document.getElementById('nature_of_complaint_select').value;
var division = document.getElementById('division_select').value;
var resolved = document.getElementById('resolved_select').value;
var tabledata_nature_of_complaint = aData[22];
var tabledata_division = aData[12];
var tabledata_resolved = aData[26];
if (nature_of_complaint == "" && division == "" && resolved == "")
{ return true; }
else if (tabledata_division == division && nature_of_complaint == "" && resolved == "")
{ return true; }
else if (tabledata_nature_of_complaint == nature_of_complaint && division == "" && resolved == "")
{ return true; }
else if (tabledata_resolved == resolved && division == "" && nature_of_complaint == "")
{ return true; }
else if (tabledata_nature_of_complaint == nature_of_complaint && tabledata_division == division && resolved == "")
{ return true; }
else if (tabledata_division == division && tabledata_resolved == resolved && nature_of_complaint == "")
{ return true; }
else if (tabledata_resolved == resolved && tabledata_nature_of_complaint == nature_of_complaint && division == "")
{ return true; }
else if (tabledata_nature_of_complaint == nature_of_complaint && tabledata_division == division && tabledata_resolved == resolved)
{ return true; }
return false;
} else
return true;
}
);
Figured it out using this tutorial.
http://www.flynsarmy.com/2011/12/save-custom-filter-state-jquery-data-tables/
Just add class of 'dtable_filter' to each select.
Here is the reduced code:
$.fn.dataTableExt.afnFiltering = new Array();
var oControls = $('#adv_search_filters').find(':input[name]');
oControls.each(function() {
var oControl = $(this);
//Add custom filters
$.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
if ( !oControl.val() || !oControl.hasClass('dtable_filter') ) return true;
for ( i=0; i<aData.length; i++ )
if ( aData[i].indexOf(oControl.val()) != -1 )
return true;
return false;
});
});

Internet Explorer may run slowly: change of logic to be done

TableHandler.prototype.IsAlreadySelected = function(dataToCheck)
{
var _this = this;
if (_this.NewTemplateUsageSelected.length > 0)
{
var len = _this.NewTemplateUsageSelected.length;
for (var i = 0; i < len; i++)
{
var an = _this.NewTemplateUsageSelected[i];
var isTemplateUsageDataDuplicate=false;
var isNonApplicableCGDataDuplicate=false;
if ((an.CustomerName == dataToCheck.CustomerName) &&
(an.ProgramName == dataToCheck.ProgramName) &&
(an.WorkpackageName == dataToCheck.WorkpackageName) &&
(an.ActivityName == dataToCheck.ActivityName) &&
(an.SelectedWorkFlowType == dataToCheck.SelectedWorkFlowType) &&
(an.SelectedWorkFlowCategory == dataToCheck.SelectedWorkFlowCategory) &&
(an.ReWorkflow== dataToCheck.ReWorkflow) &&
(an.AllowCheckGroupSelection == dataToCheck.AllowCheckGroupSelection) &&
(an.InitiatorGroupSelection == dataToCheck.InitiatorGroupSelection) &&
(an.R1GroupSelection == dataToCheck.R1GroupSelection) &&
(an.R2GroupSelection == dataToCheck.R2GroupSelection) &&
(an.R3GroupSelection == dataToCheck.R3GroupSelection) &&
(an.R4GroupSelection == dataToCheck.R4GroupSelection) &&
(an.InitiatorMinReworkEffort == dataToCheck.InitiatorMinReworkEffort) &&
(an.R1MinReworkEffort == dataToCheck.R1MinReworkEffort) &&
(an.R2MinReworkEffort == dataToCheck.R2MinReworkEffort) &&
(an.R3MinReworkEffort == dataToCheck.R3MinReworkEffort) &&
(an.R4MinReworkEffort == dataToCheck.R4MinReworkEffort) &&
(an.AllowFileAttachment == dataToCheck.AllowFileAttachment) &&
(an.QualityReviewer== dataToCheck.QualityReviewer) &&
(an.AllowLiabiltySelection == dataToCheck.AllowLiabiltySelection)&&
(an.SetToInactive == dataToCheck.SetToInactive)&&
(an.NonApplicabilityCheckGroupAllowed == dataToCheck.NonApplicabilityCheckGroupAllowed))
{
istemplateusagedataduplicate=true;
}
var checkgroupslendataToCheck=dataToCheck.NonApplicableCheckGroupList.length;
var nalen=an.NonApplicableCheckGroupList.length;
if(checkgroupslendataToCheck == nalen )
{
for (var i = 0 ;i < checkgroupslendataToCheck ; i++)
{
var naDatatocheck= dataToCheck.NonApplicableCheckGroupList[i];
var naData=an.NonApplicableCheckGroupList[i];
if(
( naDatatocheck.INonApplicability == naData.INonApplicability )&&
( naDatatocheck.R1NonApplicability == naData.R1NonApplicability )&&
( naDatatocheck.R2NonApplicability == naData.R2NonApplicability) &&
( naDatatocheck.R3NonApplicability == naData.R3NonApplicability )&&
( naDatatocheck.R4NonApplicability == naData.R4NonApplicability))
isNonApplicableCGDataDuplicate=true;
else
{
isNonApplicableCGDataDuplicate=false;
break;
}
}
if(isNonApplicableCGDataDuplicate==true && istemplateusagedataduplicate==true)
return true;
}
}
}
};
The above code is causing error Internet may run slowly. When i seached for a solution i got solutions like change of registry and IE version, Move the code to cdebehind,usage of plugin etc.. Which are not feasible in our project. So I have to change the above logic.Any inbuilt function in javascript or jquery which i can use to campare a two nested list.
The inner loop needs to use a different variable as its counter or it will make the outer loop go on infinitely. Currently you are using i for both loops.

Javascript code to convert serial numbers converted from PHP

These two Javascript functions are supposed to convert serial numbers (2-9999) for example into a number , but the functions below are not working for some reason .. they were originally written in PHP ... Works in PHP but not for Javascript.
<html>
<head>
<script type="text/javascript">
function my_isnum(str, negative=false, decimal=false)
{
var has_decimal = false;
var len = strlen(str);
if (len > 0) {
var valid = true;
for (var i=0; valid && i < len; i++) {
if (!(str[i] >= "0" && str[i] <= "9")) {
if (str[i] == "-") {
if (!negative || i != 0) {
valid = false;
}
} else if (str[i] == ".") {
if (!decimal || has_decimal) {
valid = false;
}
} else {
valid = false;
}
}
}
} else {
valid = false;
}
return valid;
}
function esn_to_num(esn) {
var tmp = [];
if ((tmp = esn.split("-")) {
if (tmp.length == 2
&& my_isnum(tmp[0])
&& my_isnum(tmp[1])
) {
esn = ((tmp[0] << 23) | tmp[1]);
} else {
esn = -1;
}
} else {
esn = -1;
}
return esn;
}
alert(2-9999);
</script> </head>
</html>
Original PHP functions
<?php
function my_isnum($str, $negative=false, $decimal=false)
{
$has_decimal = false;
$len = strlen($str);
if ($len > 0) {
$valid = true;
for ($i=0; $valid && $i<$len; $i++) {
if (!($str[$i] >= '0' && $str[$i] <= '9')) {
if ($str[$i] == '-') {
if (!$negative || $i != 0) {
$valid = false;
}
} else if ($str[$i] == '.') {
if (!$decimal || $has_decimal) {
$valid = false;
}
} else {
$valid = false;
}
}
}
} else {
$valid = false;
}
return $valid;
}
function esn_to_num($esn)
{
if (($tmp = explode('-', $esn))) {
if (sizeof($tmp) == 2
&& my_isnum($tmp[0])
&& my_isnum($tmp[1])
) {
$esn = (($tmp[0] << 23) | $tmp[1]);
} else {
$esn = -1;
}
} else {
$esn = -1;
}
return $esn;
}
?>
There is no such thing as strlen in Javascript. Use str.length instead.
Also, as Jason Sperske suggested below, change this:
function my_isnum(str, negative=false, decimal=false)
To this:
function my_isnum(str, negative, decimal)
{
if (typeof negative == "undefined") negative = false;
if (typeof decimal == "undefined") decimal = false;
....
}
These two javascript functions are supposed to convert serial numbers (2-9999) for example into a number.
Why not just get rid of the - and parse as a decimal number?
function padToFourDigits(_, digits) {
return "0000".substring(digits.length) + digits;
}
function serialToNum(serialNumStr) {
return +(serialNumStr.replace(/-(\d{1,4})/g, padToFourDigits));
}
Then
serialToNum('2-9999') === 29999
serialToNum('2-999') === 20999

Looping through javascript function

I'm trying to loop my if statements inside a while loop through my function. But it will only hit the first if statement and stop looping.
Sample:
while(No.length == 0 || Name.length == 0 || Tel.length == 0
|| Date.length == 0 || Email.length == 0) {
alert("Don't leave blank!");
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
return false;
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
return false;
}
//continues same if statement for rest of the elements variables.
}
It will only go to the first if statement and will not loop through it.
You are returning from inside the loop; that breaks the loop. If you want to continue on to the next round of the loop, use continue instead. If you want to break out of the loop, but not return from the entire function, use break.
Now if you are using a jQuery loop, because it's really just a function, you do use return:
$.each([1,2,3,4], function(index, x) {
if (x < 4) return true; // equivalent to continue
if (x == 4) return false; // equivalent to break
});
but that's only for jQuery loops, not Javascript standard ones.
The first error I can see is you should escape your alert with '\' for example :
alert('Don\'t leave blank!');
And the loop with just continue if you write this :
while(No.length == 0 || Name.length == 0 || Tel.length == 0 || Date.length == 0 || Email.length == 0) {
if (No.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
}
if(Name.length == 0) {
document.getElementById('Name').style.visibility = 'visible';
}
return true;
}
Could also try:
while(No.length == 0 && Name.length == 0 && Tel.length == 0 && Date.length == 0 && Email.length == 0) {
document.getElementById('Nos').style.visibility = 'visible';
document.getElementById('Name').style.visibility = 'visible';
continue;
}
Maybe this?
function test_all_fields() {
var No = document.getElementById('No');
var Nos = document.getElementById('Nos');
var Name = document.getElementById('Name');
// ...
Nos.style.visibility = (No.value.length==0) ? 'visible':'hidden';
Names.style.visibility = (Name.value.length==0) ? 'visible':'hidden';
//...
//continues same if statement for rest of the elements variables.
if (No.value.length >0 && Name.value.length >0 && Tel.value.length>0 && Date.value.length >0 && Email.value.length>0) {
return true;
}
else {
alert("Don\'t leave blank!");
return false;
}
}

Categories