Validate Null value in Ext JS javascript - javascript

I need to allow for the value 's1pdtCalc' to be null and allow for the record to be saved.
Right now I get the error message "s1pdtCalc is null or not an object". Thanks for the help and here is the code.
function validateForm(values) {
var pass = true;
// check percent days turnaround
var ck = values.s1pdtCalc.toString ();
if (ck > "") {
var t1 = values.s1pdtNTTd.toString (); //NEMIS Turn around
var t2 = values.s1pdtTAd.toString (); //NEMIS Turn adjustment
var t3 = values.actDays.toString (); //NEMIS Turn adjustment
t1 = (t1!=null?t1.trim ():0);
if (ck == "MINUS") {
if ((t1-t2) > t3) {
errorMsgs += '<br /> s1pdtATT - Percent days turnaround < 4.0.0. exceeds the number of activation days';
}
}
else {
if ((t1+t2) > t3) {
errorMsgs += '<br /> s1pdtATT - Percent days turnaround < 4.0.0. exceeds the number of activation days';
}
}
}
if (errorMsgs > "") {
pass = false
}
return pass;
}

You can't invoke methods on objects that don't exist. You'd need to default the s1pdtCalc to something if it doesn't exist before attempting to invoke methods:
function validateForm(values) {
...
// set ck to an empty string if values.s1pdtCalc doesn't exist
var ck = values.s1pdtCalc ? values.s1pdtCalc.toString() : '';
...

Related

How to force loop to wait until user press submit button?

I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.

.each function () for cloned inputs

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

jQuery password generator

I have the following JS code that checks a password strength and also creates a random password as well. What I want to do is edit the code so that instead of putting the generated password inside the password field it will put it inside a span tag with say an id of randompassword. In addition that I would like it so that by default there will be a random password inside the span tag and then when the user clicks the button it will generate another one. And also move the link to be next to span tag rather than the password box.
Thanks.
Here is the code:
$.fn.passwordStrength = function( options ){
return this.each(function(){
var that = this;that.opts = {};
that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);
that.div = $(that.opts.targetDiv);
that.defaultClass = that.div.attr('class');
that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;
v = $(this)
.keyup(function(){
if( typeof el == "undefined" )
this.el = $(this);
var s = getPasswordStrength (this.value);
var p = this.percents;
var t = Math.floor( s / p );
if( 100 <= s )
t = this.opts.classes.length - 1;
this.div
.removeAttr('class')
.addClass( this.defaultClass )
.addClass( this.opts.classes[ t ] );
})
.after('Generate Password')
.next()
.click(function(){
$(this).prev().val( randomPassword() ).trigger('keyup');
return false;
});
});
function getPasswordStrength(H){
var D=(H.length);
if(D>5){
D=5
}
var F=H.replace(/[0-9]/g,"");
var G=(H.length-F.length);
if(G>3){G=3}
var A=H.replace(/\W/g,"");
var C=(H.length-A.length);
if(C>3){C=3}
var B=H.replace(/[A-Z]/g,"");
var I=(H.length-B.length);
if(I>3){I=3}
var E=((D*10)-20)+(G*10)+(C*15)+(I*10);
if(E<0){E=0}
if(E>100){E=100}
return E
}
function randomPassword() {
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$_+?%^&)";
var size = 10;
var i = 1;
var ret = ""
while ( i <= size ) {
$max = chars.length-1;
$num = Math.floor(Math.random()*$max);
$temp = chars.substr($num, 1);
ret += $temp;
i++;
}
return ret;
}
};
$(document)
.ready(function(){
$('#password1').passwordStrength({targetDiv: '#iSM',classes : Array('weak','medium','strong')});
});
// you can use another improved version to generate password as follows
//Define
function wpiGenerateRandomNumber(length) {
var i = 0;
var numkey = "";
var randomNumber;
while( i < length) {
randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
if ((randomNumber >=58) && (randomNumber <=90)) { continue; }
if ((randomNumber >=91) && (randomNumber <=122)) { continue; }
if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
i++;
numkey += String.fromCharCode(randomNumber);
}
return numkey;
}
// Call
var myKey=wpiGenerateRandomNumber(10); // 10=length
alert(myKey);
// Output
2606923083
This line:
$(this).prev().val( randomPassword() ).trigger('keyup');
is inserting the value after a click. So you can change that value to stick the password wherever you want it. For example you could change it to:
$('span#randompassword').html(randomPassword());
You could also run this when the page loads to stick something in that span right away:
$(document).ready(function(){
$('span#randompassword').html(randomPassword());
});
//Very simple method to generate random number; can be use to generate random password key as well
jq(document).ready( function() {
jq("#genCodeLnk").click( function() {
d = new Date();
t = d.getTime();
jq("#cstm_invitecode").val(t);
});
});

js not working on IE but working on FF.....giving inner.html error..so want to convert in jquery format

Why this javascript working fine in Firefox but not in IE 6 and 7 ( haven't checked on IE8)?
giving inner.html error. Can any jquery expert convert this whole code into jquery? as i'm already using jquery on same site for other things.
function twoDecPlaces(theValue) {
var nm = new Number( Math.round( theValue * 100 ) ) /100 ;
var parts = nm.toString().split( '.' );
var ord = new Number( parts[ 0 ] );
var dec = ( parts[ 1 ] ) ? parts[ 1 ] : '';
if( dec ){
dec = dec.toString().substring( 0, 2 );
ord += '.' + dec;
}
return( ord );
}
function fourDecPlaces(theValue) {
num = theValue;
result = num.toFixed(4);
return( result );
}
function isNumber(val)
{
if (isNaN(val))
{
return false;
}
if (val==0)
{
return false;
}
else
{
return true;
}
}
function doCalc()
{
if (isNumber(document.getElementById("num_shares").value))
{
var dividend_rate = document.getElementById('dividend_rate');
var currency = document.getElementById('currency').value;
var dividendValue = dividend_rate.options[dividend_rate.selectedIndex].value;
var num_shares = document.getElementById('num_shares');
num_shares = parseInt(num_shares.value);
var totalDividend = dividendValue * num_shares;
var valuePaid = document.getElementById('valuePaid');
var divpershare = document.getElementById('divpershare');
divpersharevalue = fourDecPlaces(dividendValue/1000);
divpersharevalue = divpersharevalue + " " + currency;
totalDividend = twoDecPlaces(totalDividend/100);
totalDividend = totalDividend + " " + currency;
valuePaid.style.display="";
divpershare.style.display="";
valuePaid.innerHTML = "<td>The total dividend paid was:</td><td align='right'>"+totalDividend+"</td>";
divpershare.innerHTML = "<td>The dividend per share was:</td><td align='right'>"+divpersharevalue+"</td>";
}
else
{
alert("Invalid entry in dividend box");
document.getElementById("num_shares").value="";
document.getElementById('valuePaid').innerHTML="";
}
}
Can any jquery expert convert this whole code into jquery?
Here are some things I noticed:
I'm not sure why you are using two different methods, one fortwoDecPlaces and another for the fourDecPlaces function.
You shouldn't need to insert table cells with data to display results. I would just have the text in place in the table (but hidden), so then you only need to update the value.
This is how I would modify the result table (CSS included):
<style type="text/css">
.text, .val { display: none; }
</style>
<table>
<tr id="valuePaid"><td class="text">The total dividend paid was:</td><td class="val"></td></tr>
<tr id="divpershare"><td class="text">The dividend per share was:</td><td class="val"></td></tr>
</table>
And this would be your script made to work with the above HTMl. It's been cleaned up and jQuerified :)
function twoDecPlaces(theValue) {
return theValue.toFixed(2);
}
function fourDecPlaces(theValue) {
return theValue.toFixed(4);
}
function isNumber(val) {
if (isNaN(val) || val == 0) { return false; }
return true;
}
function doCalc(){
if (isNumber($('#num_shares').val())) {
var currency = $('#currency').val();
var dividendValue = $('#dividend_rate').val();
var num_shares = parseInt($('#num_shares').val(),10);
var divpersharevalue = fourDecPlaces(dividendValue/1000) + " " + currency;
var totalDividend = twoDecPlaces((dividendValue * num_shares)/100) + " " + currency;
$('#valuePaid').find('.val').html(totalDividend);
$('#divpershare').find('.val').html(divpersharevalue);
$('.text, .val').show();
} else {
alert("Invalid entry in dividend box");
$('#num_shares').val('');
$('.text').hide();
$('.val').empty();
}
}
If you want to limit the input box to only allow numbers to be typed inside of it, there are several jQuery plugins available. Here is one called Numeric.
Internet Explorer is very bad at editing the innerHTML of table, thead, tbody, and tr elements.
Either use standard DOM, replace the entire table, or replace the contents of indivdual cells.

Categories