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

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.

Related

Javascript to calculate and display odds as their simplest fraction

I'm writing a bit of script for the WooCommerce product page that takes the quantity entered in the qty input field and displays some text based on that qty:
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return [numerator/gcd,denominator/gcd];
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>
The current output:
Max odds of 1 ticket winning is 1,200
How can I make the odds display in their simplest fraction form? For example if there are 200 tickets available and '1' is entered, it should show '1/200' but if someone enters '20' it should show '1/10'. The 'total' figure will eventually be picked up from the page rather than a fixed value too.
I can use the gcd as posted here but how can I get the two numbers from the array and display them as a fraction (with the /) in the required div?
You can return the desired string instead of array. Check the snippet below.
I've changed return [numerator/gcd,denominator/gcd]; to return numerator/gcd+'/'+denominator/gcd;
function reduce(numerator,denominator){
var gcd = function gcd(a,b){
return b ? gcd(b, a%b) : a;
};
gcd = gcd(numerator,denominator);
return numerator/gcd+'/'+denominator/gcd;
}
jQuery('.qty').on('change', function() {
showOdds();
});
function showOdds() {
var qty = 1; // hard coded for testing
var min = 200; // hard coded for testing
var sofar = 40; // hard coded for testing
var plural = '';
var total = 0;
var odds = '';
if (qty > 1){
plural = 'tickets';
}
else{
plural = 'ticket';
}
if (qty > 0){
if ((qty + sofar) > min){
total = qty + sofar;
odds = reduce(qty, total);
}
else {
odds = reduce(qty, min);
}
var text = document.createElement('p');
text.className = 'product-odds';
text.innerHTML = 'Max odds of ' + qty + ' ' + plural + ' winning is ' + odds + '.';
var theDiv = document.getElementById('odds');
theDiv.appendChild(text);
}
}
jQuery(document).ready(function loadPage() {
showOdds();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='odds'></div>

Validate Null value in Ext JS 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() : '';
...

show and hide several random divs using jquery

i am developing a jquery application. I have 10 divs with quotes. I am trying to create a function that takes a number and randomly displays that number of quotes from the 10 divs for 10 seconds and hide the divs. Then repeat the process again. I have not been able to do it please help me out. here is my code:
$(document).ready(function(){
var div_number = 4;
var used_numbers = new Array();
var todo = setInterval(showQuotes(),3000);
function showQuotes(){
used_numbers.splice(0,used_numbers.length);
$('.quotes').hide();
for(var inc = 0; inc<div_number; inc++) {
var random = get_random_number();
$('.quotes:eq('+random+')').show();
}
$('.quotes').fadeOut(3000);
}
function get_random_number(){
var number = randomFromTo(0,9);
if($.inArray(number, used_numbers) != -1) {
get_random_number();
}
else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
});
Changes I made:
hide the .quotes on launch via a stylesheet
run showQuotes() once before setInterval(showQuotes,10000), and
add a .delay() before fading the quotes out
Py's 'return' added to get_random_number
http://jsfiddle.net/cMQdj/1/
the changed JavaScript:
$(document).ready(function () {
var div_number = 4;
var used_numbers = new Array();
showQuotes();
var todo = setInterval(showQuotes, 10000);
function showQuotes() {
used_numbers.splice(0, used_numbers.length);
$('.quotes').hide();
for (var inc = 0; inc < div_number; inc++) {
var random = get_random_number();
$('.quotes:eq(' + random + ')').show();
}
$('.quotes').delay(6000).fadeOut(3000);
}
function get_random_number() {
var number = randomFromTo(0, 9);
if ($.inArray(number, used_numbers) != -1) {
return get_random_number();
} else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
});
and add to your stylesheet:
.quotes {display:none}
I didn't test everything, but i already see one point that might block you, the get_random_number does not always return a number. To do so, it should be
function get_random_number(){
var number = randomFromTo(0,9);
if($.inArray(number, used_numbers) != -1)
{
return get_random_number();
}
else
{
used_numbers.push(number);
return number;
}
}
Hope that helps.

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

Truncate width function not working when passing integer

I'm trying to create a universal function that I can call from multiple places to truncate long text recursively to fit a predefined pixel width - using jquery.
Here is the code...
function constrain(text, original, ideal_width){
var ideal = parseInt(ideal_width);
$('span.temp_item').remove();
var temp_item = ('<span class="temp_item" style="display:none">'+ text +'</span>');
var item_length = text.length;
$(temp_item).appendTo('body');
var item_width = $('span.temp_item').width();
if (item_width > ideal) {
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original);
} else if (item_length != original) {
return (text + '…');
} else if (item_length == original) {
return text;
}
}
If I run the function like this:
$('.service_link span:odd').each(function(){
var item_text = $(this).text();
var original_length = item_text.length;
var constrained = constrain(item_text, original_length,'175');
$(this).html(constrained);
});
The text doesn't truncate. I also tried the 175 without the quotes.
If I define var ideal = 175; inside the function, then it works. Why is passing 175 to the function not working? I did a parseInt on it in case it was a string.
Also - this truncate code run a bit slow on older machines - any tips for speeding it up?
Thanks!
Great stuff here. I used the function by Phil Carter. I just wanted the new string with the &hellip to be truncated at the same width as the rest.
I just quickly added another temp-width lookup and recursive call. Could use some cleanup but it works.
here's the new while:
while(item_width > ideal) {
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original, ideal_width, counter);
}
if (item_length != original) {
new_text=text+'…';
$('span.temp_item').remove();
var temp_item = ('<span class="temp_item" style="display:none">'+ new_text +'</span>');
$(temp_item).appendTo('body');
var item_width_new = $('span.temp_item').width();
if(item_width_new>ideal){
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original, ideal_width, counter);
}
else {
return new_text;
}
} else if (item_length == original) {
return text;
}
}
What happens when the visitor to your site presses "ctl +" ? It's my (probably out of date) belief that you're supposed to use "em" sizes for font containers, so they scale.
Ah... found the bug - forgot to pass the recursive part the ideal width:
return constrain(smaller_text, original, ideal);
TOTAL WE WRITE
So I decided that your iteration over the lorum ipsum text in 5 spans, taking 16 secs was far too long, so thought how to speed this up. and I have it down to 0.4 seconds.
function constrain(text, original, ideal_width, counter){
var ideal = parseInt(ideal_width);
$('span.temp_item').remove();
var temp_item = ('<span class="temp_item" style="display:none">'+ text +'</span>');
var item_length = text.length;
$(temp_item).appendTo('body');
var item_width = $('span.temp_item').width();
if(counter == 0) {
//work out some ranges
var temp_item = ('<span class="temp_item_i" style="display:none">i</span>');
$(temp_item).appendTo('body');
var i_width = $('span.temp_item_i').width();
var max_i = Math.round((ideal_width / i_width) + 1);
var temp_item = ('<span class="temp_item_m" style="display:none">M</span>');
$(temp_item).appendTo('body');
var m_width = $('span.temp_item_m').width();
var max_m = Math.round((ideal_width / m_width) + 1);
text = text.substr(0, (max_i - max_m));
var item_length = text.length;
}
counter++;
while(item_width > ideal) {
var smaller_text = text.substr(0, (item_length-1));
return constrain(smaller_text, original, ideal_width, counter);
}
if (item_length != original) {
return (text + '…');
} else if (item_length == original) {
return text;
}
}
$(document).ready(function() {
var d = new Date();
var s = d.getTime();
$('.service_link').each(function(){
var item_text = $(this).text();
var original_length = item_text.length;
var constrained = constrain(item_text, original_length, 175, 0);
$(this).html(constrained);
});
var e = d.getTime()
alert('Time Taken: ' + ((e - s)/1000));
});
Basically on the first run, it works out how many lowercase i's and how many uppercase Ms fit in the space, and then restricts the text length to that, this reduces the number of iterations massively.
Hope this helps.

Categories