Getting element ID's for if/else statements - javascript

Working on a project. I need the else statement to work but when I hit the submit button it just redirects to the "if"
<head>
<script>
var judgmentAmount = document.getElementById('judgmentAmount');
var amountCollected = document.getElementById('amountCollected');
function judgmentCalc() {
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}
</script>
</head>
<body>
<h1>Application</h1>
<p>I understand that this application neither obligates me to <b>Affirmative Judgment</b> nor does it obligate <b>Affirmative Judgment</b> to me.</p>
<h3>Judgment Information</h3>
<form>
<span>Do you have a case number?</span>
<input type="text" name="caseNumber" />
<span>Amount of Judgment</span>
<input type="text" name="judgmentAmount" id="judgmentAmount" />
<span>Amount collected to date</span>
<input type="text" name="amountCollected" id="amountCollected" />
<input type="submit" name="submitButton" onclick="judgmentCalc();" />
</form>

You need to access values of these input fields instead of directly working on dom elemens returned by document.getElementById(). You can get value of input using .value property.
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;

move your variables inside the function so they are properly filled at the time of function execution, and add .value properties of the DOM elements.
try this:
function judgmentCalc() {
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}

You are only comparing the objects, you need to compare their values
var judgmentAmount = Number(document.getElementById('judgmentAmount').value);
var amountCollected = Number(document.getElementById('amountCollected').value);
Also, convert them to Number before comparison.
function judgmentCalc() {
var judgmentAmount = Number(document.getElementById('judgmentAmount').value);
var amountCollected = Number(document.getElementById('amountCollected').value);
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}

You're getting the HTML DOM elements here:
var judgmentAmount = document.getElementById('judgmentAmount');
var amountCollected = document.getElementById('amountCollected');
So in your judgementCalc method you need to get the values of those elements:
function judgmentCalc() {
// notice that we're using VALUE here:
if( judgmentAmount.value - amountCollected.value < 10000 ) {
window.open( 'http://afjudgment.com' );
}else {
window.open( 'http://www.yahoo.com' );
}
}

You need to operate with values of your elements:
function judgmentCalc() {
var judgmentAmount = +document.getElementById('judgmentAmount').value;
var amountCollected = +document.getElementById('amountCollected').value;
if( judgmentAmount - amountCollected < 10000 ) {
window.open( 'http://afjudgment.com' );
}
else {
window.open( 'http://www.yahoo.com' );
}
}
var judgmentAmount = document.getElementById('judgmentAmount') returns only a reference to element with ID "judgmentAmount". If you want to use element's value, you need to do this:
var judgmentAmount = document.getElementById('judgmentAmount').value.
The next step is calculating some amount. You need to convert string to int (with + operator)
typeof judgmentAmount; // "string"
typeof +judgmentAmount; // "number"
Demo

Please run the script below, it'll work fine:
<head>
<script>
function judgmentCalc() {
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
var exp = parseFloat(judgmentAmount) - parseFloat(amountCollected);
if( exp < 10000 ) {
window.open( 'http://afjudgment.com' );
} else {
window.open( 'http://www.yahoo.com' );
}
}
</script>
</head>

You have to compare the value of the input element, Please try the following
function judgmentCalc() {
var judgmentAmount = document.getElementById('judgmentAmount').value;
var amountCollected = document.getElementById('amountCollected').value;
if( (judgmentAmount - amountCollected) < 10000 ) {
window.open( 'http://afjudgment.com' );
} else {
window.open( 'http://www.yahoo.com' );
}
}
It may help you.

Related

Javascript problem with loop for hiding/showing element depending on checkbox

I'm trying to hide/show an element depending on if the corresponding checkbox is checked or not.
There are two checkbox each one corresponding to an element. The name of thos checkboxes and elements depends on a variable stored in vendorIds array.
The problem is that the code only works for ths second variable stocked in the array.
I suppose that the problem comes from the "for" loop but I'am beginner and I don't see what's wrong.
Here is the code :
<script>
jQuery(function($){
console.log(vendorIds);
for (var i=0; i<vendorIds.length; i++) {
var vendorId = vendorIds[i];
console.log(vendorId);
var vendorId = vendorIds[i];
console.log(vendorId);
var ism = 'input[name^="shipping_method['+vendorId+']"]', ismc = ism+':checked',
csa = 'input#ship-to-different-address-checkbox',
rq = '-required', vr = 'validate'+rq, w = 'woocommerce', wv = w+'-validated',
iv = '-invalid', fi = '-field', wir = w+iv+' '+w+iv+rq+fi,
b = '#wcfmd_delvery_time_'+vendorId,
livraison = 'Livraison:1';
console.log(b);
}
(function(i){
// Utility function to shows or hide checkout fields
function showHide( action='show', selector='' ){
if( action == 'show' )
$(selector).show(function(){
$(this).addClass(vr);
$(this).removeClass(wv);
$(this).removeClass(wir);
if( $(selector+' > label > abbr').html() == undefined )
$(selector+' label').append('<?php echo $required_html; ?>');
});
else
$(selector).hide(function(){
$(this).removeClass(vr);
$(this).removeClass(wv);
$(this).removeClass(wir);
if( $(selector+' > label > abbr').html() != undefined )
$(selector+' label > .required').remove();
});
}
// Initializing at start after checkout init (Based on the chosen shipping method)
setTimeout(function(){
if( $(ismc).val() == livraison ) // Choosen "livraison" (Hidding "Take away")
{
showHide('show',b);
}
else
{
showHide('hide',b);
}
}, 100);
// When shipping method is changed (Live event)
$( 'form.checkout' ).on( 'change', ism, function() {
if( $(ismc).val() == livraison )
{
showHide('show',b);
}
else
{
showHide('hide',b);
}
});
})(i);
});
</script>
Thanks in advance.
Have an nice day.
Fred
Here is the answer if one day someone need it
<script>
jQuery(document).ready(function($){
for (var i=0; i<vendorIds.length; i++) {
var vendorId = vendorIds[i];
var ism = 'input[name^="shipping_method['+vendorId+']"]', ismc = ism+':checked',
b = '#livraison_'+vendorId,
livraison = 'Livraison:1';
// When shipping method is changed (Live event)
$( 'form.checkout' ).on( 'change', ism, function(e) {
var name = e.currentTarget.name;
var dataValue = $('input[name ="'+name+'"]').attr('data-index');
var b = '#livraison_'+dataValue;
var ismc = 'input[name^="shipping_method['+dataValue+']"]:checked';
var livraison = 'Livraison:1';
if( $(ismc).val() == livraison )
{
$(b).show();
}
else
{
$(b).hide();
}
});
// Initializing at start after checkout init (Based on the chosen shipping method)
setTimeout(function(){
$( "input.shipping_method" ).each(function() {
var name = $(this).attr("name");
var type = $(this).attr("type");
var dataValue = $(this).attr('data-index');
var b = '#livraison_'+dataValue;
var ismc = 'input[name^="shipping_method['+dataValue+']"]:checked';
var livraison = 'Livraison:1';
if( ($(this).attr("type") == 'hidden') ) {
if( $(this).val() == 'Livraison:1' ) // Choosen "retrait sur place" (Hidding "Take away")
{
$(b).show();
} else
{
$(b).hide();
}
} else {
if($(this).is(':checked'))
{
if( $(this).val() == 'Livraison:1' ) // Choosen "retrait sur place" (Hidding "Take away")
{
$(b).show();
} else
{
$(b).hide();
}
}
}
});
}, 100);
}
});
</script>

Is there any way of adapting this name-generating loop to run for a minimum number of seconds?

I'm using the following code (which has some Frog VLE API code in it; hopefully that's not too relevant) to pick a random student from a list.
This works well, but sometimes - given its random nature - it only runs for a very brief period of time. Would it be possible to loop this a number of times first, to ensure that it runs for X period of time as a minimum?
var Count = 0;
/* construct the array of people */
for (var i in data.users) {
for (var n = 0; n < data.users[i].Quantity; n++) {
var TempObj = { 'Count' : Count, 'Student_ID' : i, 'Student_Name' : data.users[i].Student_Name };
RewardPurchases.PurchasesArray[Count] = TempObj;
Count++;
}
}
... more code here, nothing relevant to the way the script works ...
$('button#random').click( function() {
/* first things first, play a drum-roll when the button is clicked! */
$('embed').remove();
$('body').append('<embed src="/user/74/177499.wav" autostart="true" hidden="true" loop="true">');
/* take the RewardPurchases.PurchasesArray and sort it so that there's no particular order */
RewardPurchases.PurchasesArray.sort(function() {return 0.5 - Math.random()})
/* remove the winner class for consecutive re-rolls */
$display.removeClass( "winner" );
$display.addClass( "spinner" );
/* determine the number of people in the array and calculate a random winner */
var total = RewardPurchases.PurchasesArray.length,
selected = Math.floor( Math.random() * total ),
i = 0;
/* work out how long each name should appear for, dependent upon how many people are in the array */
var timeout = ( 15000 / total );
/* run through the array of people ... */
for (i=0; i<total; i++) {
setTimeout((function(i){
return function(){
console.log( "timeout", i );
/* ... if the person in the array is a valid person! then display their name */
if (typeof RewardPurchases.PurchasesArray[i] === 'object' && typeof RewardPurchases.PurchasesArray[i] !== null) {
$display.text( "[" + RewardPurchases.PurchasesArray[i].Count + "] " + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() );
/* if we encounter the winner, play a cheering wav and change the class of the display so that they appear in big, bold, red text */
if( i === selected ) {
$('embed').remove();
$('body').append('<embed src="/user/74/177086.wav" autostart="true" hidden="true" loop="false">');
$display.addClass( "winner" );
}
}
};
}(i)), i*timeout);
/* if the winner has been found, break the loop */
if( i === selected ) {
break;
}
}
} );
Thanks in advance,
You could do something like this :
function doforsec(msec, func) {
var curDate = new Date().getTime();
while ((new Date().getTime() - curDate) < msec) {
func();
}
}
doforsec(200, function() {
console.log(new Date().getSeconds())
});​
This executes the function given to doforsec again and again until the timeperiod specified (in milliseconds) is over. (first i had seconds, but i think milliseconds will be better)
JSfiddle
Because my deadline for this is.. well, around 8 hours from posting this.. I've decided to re-write the script and use a jQuery plugin:
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
$(document).ready(function(){
var staff = [ 'hardcoded', 'list', 'of', 'staff', 'members' ];
$('button#start').click( function() {
var $display = $('#display'),
$results = $('#results table');
$display.removeClass( "winner" );
$display.addClass( "spinner" );
var counter = 0,
rand = 0,
run_time = 10,
delay = ( run_time * 100 ) / staff.length,
loop_number = 5,
max_count = staff.length * loop_number;
$display.doTimeout( 'loop', delay, function() {
counter++;
var newRand = Math.floor( Math.random() * staff.length );
if ( rand === newRand ) {
rand = Math.floor( Math.random() * staff.length );
} else {
rand = newRand;
}
$(this).text( staff[rand] );
if ( counter < max_count ) { return true; }
else {
$('#results tr:last').after('<tr><td class="number">' + staff.length + '</td><td>' + staff[rand] + '</td></tr>');
staff.remove( rand );
}
});
$display.doTimeout( 'class', max_count * delay, function() {
$display.removeClass( "spinner" );
$display.addClass( "winner" );
});
});
});
After var timeout = ( 15000 / total ); insert the following, and remove the line for (i=0; i
var totalTime = 2000;
var timeOut= Math.Ceiling(totalTime/timeout);
var timesToDisplay = totalTime / timeOut;
var currentDisplay = 0;
for (currentDisplay = 0; currentDisplay < timesToDisplay; currentDisplay++) {
i = currentDisplay % total;

Selection row disable/reenable text selection

I have this code which selects multiple row when shift key is pressed. But whenever selection starts, the table text always gets selected, hence I tried to add disableSelection( ); to the table and re-enable it once mouseup. However, it is not working, the text still get selected. Any help is greatly appreciated.
$(".tableGrid tr").live("click", function(event) {
if( event.shiftKey ) {
$(".tableGrid").disableSelection( );
}
var tableRow = $(this).closest("tr").prevAll("tr").length + 1;
if ($(this).hasClass("rowSelected")) {
event.shiftKey ? $(this).removeClass("rowSelected") : $(".tableGrid tr").removeClass("rowSelected");
}
else {
if( !event.shiftKey ) {
$(".tableGrid tr").removeClass("rowSelected");
}
$(this).addClass("rowSelected");
}
if( event.shiftKey ) {
var start = Math.min(tableRow, lastSelected);
var end = Math.max(tableRow, lastSelected);
for( var i=start; i<end; i++ ) { $(".tableGrid").find("tr").eq(i).addClass("rowSelected"); }
}
else {
lastSelected = $(this).closest("tr").prevAll("tr").length + 1;
}
}).mouseup(function( ) {
$(".tableGrid").enableSelection( );
});
To disable text selection of a specific DOM element, you could try this:
var element = document.getElementById('content');
element.onselectstart = function () { return false; } // ie
element.onmousedown = function () { return false; } // mozilla

Using Javascript to move a div wont work

I have some javascript that should move my div element every 400 milliseconds. From debugging I have found that all my code works except when I go to move the div element. Ie, this code:
block.style.left = xPos[index] + "px";
I am unsure why this code doesn't move my div? Should I use a different method (other than object.style.top etc.) to move my div?
My java script:
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
var block = null;
var clockStep = null;
var index = 0;
var maxIndex = 6;
var x = 0;
var y = 0;
var timerInterval = 400; // milliseconds
var xPos = null;
var yPos = null;
function moveBlock()
{
//alert( index ); // if you use this you will see my setInterval works fine
if ( index < 0 || index >= maxIndex || block === null || clockStep === null )
{
clearInterval( clockStep );
clockStep = null;
return;
}
block.innerHTML = "yellow"; // this works (just a debug test) so I know block points to the correct HTML element
block.style.left = xPos[index] + "px"; // this doesn't work
block.style.top = yPos[index] + "px";
index++;
}
function onBlockClick( blockID )
{
if ( clockStep !== null )
{
return;
}
block = document.getElementById( blockID );
index = 0;
x = parseInt( block.style.left, 10 );
y = parseInt( block.style.top, 10 );
xPos = new Array( x+10, x+20, x+30, x+40, x+50, x+60 );
yPos = new Array( y-10, y-20, y-30, y-40, y-50, y-60 );
clockStep = setInterval( "moveBlock()", timerInterval );
}
-->
</script>
The value of block.style.left and block.style.top is not set unless you use an absolutely-positioned div with preset values for both left and top (in fact, your array is filled with NaN when I tested). For instance, the code works fine with a div defined like this:
<div id="div1" style="position:absolute;left:100px;top:100px;
width:150px;height:150px;background-color:yellow;"
onclick="onBlockClick(this.id);">
HI
</div>

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);
});
});

Categories