i want to match two float number but unable check below:
https://jsfiddle.net/mcsab3aa/2/
js code:
$('#checkButton').click(function() {
var getusertarget = parseFloat(jQuery("#targetval").val());
var currentval = $("#demo").find( "h1" ).html();
currentval = parseFloat(currentval.replace('$',''));
console.log(currentval);
console.log(getusertarget);
var dividerval = (currentval/targetval); // it should be 1
console.log(dividerval);
if (dividerval==1) {
$('.coins_drags').hide();
//$("#demo").find( "h1" ).html('$' + sum.toFixed(2) + '<br />Great job');
console.log('great');
}
else {
//$("#demo").find( "h1" ).html('$' + sum.toFixed(2) + '<br />Try again');
//sum = 0;
console.log('try');
}
});
var dividerval = (currentval/targetval);
targetval is undefined. You might want to do:
var dividerval = (currentval/getusertarget);
Try like this
var dividerval = (currentval/getusertarget);
instead of
var dividerval = (currentval/targetval);
https://jsfiddle.net/mcsab3aa/4/
var h1 = $("#demo").find( "h1" ),
targetVal = f2num(h1.text()),
current = $("#targetval"),
msg = $('.msg');
msg.text('click after typing your guess');
$('#checkButton').click(function () {
if (current.val() == targetVal) {
msg.text('Great job');
h1.html('$' + targetVal).show();
} else {
h1.hide();
msg.text('try again!');
}
});
function f2num(n) {
return parseFloat((n+"").replace(/[^0-9\.]+/g, ''));
}
The problem was that you were trying to parse number with $ in it. And had handlers reversed.
Related
I'm trying to cut down this list of class change functions to one neat loop using an array for the class names used in the change event.
I need to put the four example $ ('.[class]').change functions into a loop. The D7codes array doesn't read in as a dynamic class changer (where I've put [class] in this comment). Also, do I need an overall change function so the loop executes each time?
Currently it works in long hand how I want it to, but I'm going to need to use this autosum throughout a project that other people will need to refer to, and it's going to get really messy.
This code looks for change (check box) in a class - I haven't included the python and html elements because it works correctly currently. There are four functions that need to be in a loop.
Apart from the class names in the D7codes array the only other two things that change within the functions are the numbers, ascending, after the 'question' and 'click' variables (0-4)
var question0 = 15.99;
var question1 = 20.99;
var question2 = 5.99;
var question3 = 2.99;
var total = 0
var click0 = false;
var click1 = false;
var click2 = false;
var click3 = false;
var click99 = false;
//this array is for the class names (currently the array isn't being used as I've elongated the code back out
var D7codes = [d7-r6,d7-r7,d7-r8,d7-r9]
//the four functions that should be in a loop
$ ('.d7-r6').change( function() {
click0 = !click0;
if (!click99) {
total += click0 ? question0 : -question0
} else {
totalOrig += click0 ? question0 : -question0
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
$ ('.d7-r7').change( function() {
click1 = !click1;
if (!click99) {
total += click1 ? question1 : -question1
} else {
totalOrig += click1 ? question1 : -question1
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
$ ('.d7-r8').change( function() {
click2 = !click2;
if (!click99) {
total += click2 ? question2 : -question2
} else {
totalOrig += click2 ? question2 : -question2
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
$ ('.d7-r9').change( function() {
click3 = !click3;
if (!click99) {
total += click3 ? question3 : -question3
} else {
totalOrig += click3 ? question3 : -question3
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
//This next function doesn't need to be in the loop but is referred to so I've //left it in for clarity
$ ('.d7-r99').change( function() {
click99 = !click99;
if (click99) {
totalOrig = total;
total = 0;
} else {
total = totalOrig;
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
Got there in the end:
var total = 0
var click99 = false;
var question = [15.99, 20.99, 5.99, 2.99];
var click = [false, false, false, false];
//classnames
var D7codes = ['.d7-r6','.d7-r7','.d7-r8','.d7-r9']
D7codes.forEach( function( value, index ) {
$ (value).change( function() {
click[index] = !click[index];
if (!click99) {
total += click[index] ? question[index] : -question[index]
} else {
totalOrig += click[index] ? question[index] : -question[index]
}
var totalFloat = parseFloat(total).toFixed(2)
$ ('.asum-total').text(totalFloat);
});
});
$ ('.d7-r99').change( function() {
click99 = !click99;
if (click99) {
totalOrig = total;
total = 0;
} else {
total = totalOrig;
};
var totalFloat = parseFloat(total).toFixed(2);
$ ('.asum-total').text(totalFloat);
});
Chris G gave a great answer in the comments also (I couldn't use it with the software I'm using but it would work outside of my particular project)
This should be simple but I am not sure why it isn't working:
function kebabToSnake (str){
var string = "";
var chart = "";
for(i=0; i < str.lenght; i++){
if (str.charAt(i) == "-") {
chart = "_";
string = string + chart;
}
else {
chart = str.charAt(i);
string = string + chart;
}
}
return string
}
I know I could do it with str.replace(/-/g,"_") but I cannot see what's wrong with the above, besides being too long. Any help would be great.
You spelled "length" wrong. ( on line 4 )
It works after the spelling correction.
function kebabToSnake (str){
var string = "";
var chart = "";
for(i=0; i < str.length; i++){ //fixed spelling from 'str.lenght'
if (str.charAt(i) == "-") {
chart = "_";
string = string + chart;
}
else {
chart = str.charAt(i);
string = string + chart;
}
}
return string
}
var body = document.querySelector( 'body' ),
output = kebabToSnake( '-' ); //First test with '-' in conditional statement
body.innerHTML = output; //display to body
output = kebabToSnake( 'Another String' ); //Second test with random text triggering ELSE statement
body.innerHTML += '<br>' + output; //display to body
You can achieve this goal by using RegExp more concisely:
function kebabToSnake (str) {
return str.replace(/-/g, '_');
}
When I click on save on my bootstrap modal button it tries to find next available number.
How ever if returns null throws error.
TypeError: matches is null
Question When click on save in bootstrap modal if no numbers found in textarea then will create a number. Currently if no findAvailableNumber function returns null unable to create a number
Codepen Example
$('#myLink').on('shown.bs.modal', function() {
var text = getSelectedText();
$('#title').val(text.trim());
$('#url').val('http://');
});
function getSelectedText() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
return sel;
}
function findAvailableNumber(textarea){
//Find lines with links
var matches = textarea.value.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
return number;
}
$('#save-link').on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace = '[' + $('input#title').val() + ']' + '[' + counter + ']';
var id = '\n [' + counter + ']: ' + $('input#url').val();
if ($('#title').val().length > 0) {
textarea.value = textarea.value.substring(0,start) + replace +
textarea.value.substring(end,len) + id;
} else {
return false;
}
});
How links look in textarea when created.
[exmple-1][1] and [example-2][2]
[1]: http://www.example.com
[2]: http://www.example.com
You need to check to see if the <textarea> actually has a value within findAvailableNumber(). If not, return 1 to kick it off.
function findAvailableNumber(textarea){
var number = 1;
if(textarea.value){
//Find lines with links
var matches = textarea.value.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
}
return number;
}
Here's an updated pen.
I paste all of my code because it might have a connection with the function I am asking for. I had help to make one of my functions run. Look at the parseJSON() function. Why I have to use 2 functions (parseJSON() and nested makeNav(navigation)), but not only one parseJSON(navigation) (and ofc to change the inner elements from makeNav to parseJSON). Can someone explain why it works only that way for me. Because I want to understand it, not just to do my exercise and go on.
var new_json;
$.get('navigation.json', function (json){
new_json = json;
parseJSON();
var reload_page;
var this_hash = window.location.hash;
if( this_hash.length == 0 ){
reload_page = "home";
}else{
reload_page = this_hash.replace('#', '');
};
loading(reload_page + '.html');
});
var cache = {};
function loading(url){
if( typeof(cache[url]) == 'undefined' ) {
console.log( 'cache A does not exists' );
container.load(url + ' .container>*', function(){
cache[url] = container.html();
});
}else {
console.log( 'cache A exists' );
container.html(cache[url]);
};
};
$('#navigation li a, #logo a').live('click',function(){
var url = $(this).attr('href');
window.location.hash = url.replace('.html', '');
loading(url);
return false;
});
function parseJSON() {
function makeNav(navigation) {
var nav_html = '';
console.log( navigation.length );
for (var i = 0; i < navigation.length; i++) {
var name = navigation[i]['name'];
var href = navigation[i]['href'];
var submenu = navigation[i]['navigation'];
nav_html += '<li>' + name + '<span class="ddArrow"></span>';
if( typeof(submenu) != 'undefined' ){
nav_html += '<ul>';
nav_html += makeNav(submenu);
nav_html += '</ul>';
}
nav_html += '</li>';
}
return nav_html;
}
$('#navigation ul').html(makeNav( new_json['navigation'] ));
}
Probable reason is that your parseJSON does extra things: $('#navigation ul').html(makeNav( new_json['navigation'])); and when you make recursive call to makeNav you don't need to set this html content. Reason for the nested definition of makeNav inside parseJSON could be that you don't want makeNav to be visible outside of the scope of parseJSON because you simply don't use it out of this scope and you don't want to pollute the "environment".
Anyway, I really don't think that's the best way to implement it...but that should be discussed at https://codereview.stackexchange.com/.
To use a single function, without the nested makeNav you can do something like:
var new_json;
$.get('navigation.json', function (json){
new_json = json;
parseJSON();
var reload_page;
var this_hash = window.location.hash;
if( this_hash.length == 0 ){
reload_page = "home";
}else{
reload_page = this_hash.replace('#', '');
};
loading(reload_page + '.html');
});
var cache = {};
function loading(url){
if( typeof(cache[url]) == 'undefined' ) {
console.log( 'cache A does not exists' );
container.load(url + ' .container>*', function(){
cache[url] = container.html();
});
}else {
console.log( 'cache A exists' );
container.html(cache[url]);
};
};
$('#navigation li a, #logo a').live('click',function(){
var url = $(this).attr('href');
window.location.hash = url.replace('.html', '');
loading(url);
return false;
});
function makeNav(navigation) {
var nav_html = '';
console.log( navigation.length );
for (var i = 0; i < navigation.length; i++) {
var name = navigation[i]['name'];
var href = navigation[i]['href'];
var submenu = navigation[i]['navigation'];
nav_html += '<li>' + name + '<span class="ddArrow"></span>';
if( typeof(submenu) != 'undefined' ){
nav_html += '<ul>';
nav_html += makeNav(submenu);
nav_html += '</ul>';
}
nav_html += '</li>';
}
return nav_html;
}
I have a script that is setting conversion rates depending on input boxes (works fine), however I now want to get an average of these rates.
My Code is
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
The id conversion1,2 etc have a number from 0-100 (the conversion rate). However whenever I run this script I get all sorts of crazy numbers for the average (sumavg or id conversion7). I do not know why! I should also note that this bit of code is inside of the function doing the conversion for each day which works fine.
See below for entire snippet:
// Conversion Rate
$.fn.sumConv = function(customers) {
var sum = 0;
var val = 0
this.each(function() {
if ( $(this).is(':input') ) {
val = $(this).val();
} else {
val = $(this).text();
}
customersval = $(customers).val();
sum = (customersval/val) * 100;
//sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
sum = Math.round(sum*Math.pow(10,2))/Math.pow(10,2);
if(sum=="Infinity" || sum=="NaN") sum=0;
});
// do average
var avg1 = $('#conversion1').text();
var avg2 = $('#conversion2').text();
var avg3 = $('#conversion3').text();
var avg4 = $('#conversion4').text();
var avg5 = $('#conversion5').text();
var avg6 = $('#conversion6').text();
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg = Math.round(sumavg*Math.pow(10,2))/Math.pow(10,2);
$('#conversion7').html(sumavg);
return sum;
};
$('input#foot1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#customers1').bind('keyup', function() {
$('#conversion1').html( $('input#foot1').sumConv('input#customers1') );
});
$('input#foot2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#customers2').bind('keyup', function() {
$('#conversion2').html( $('input#foot2').sumConv('input#customers2') );
});
$('input#foot3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#customers3').bind('keyup', function() {
$('#conversion3').html( $('input#foot3').sumConv('input#customers3') );
});
$('input#foot4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#customers4').bind('keyup', function() {
$('#conversion4').html( $('input#foot4').sumConv('input#customers4') );
});
$('input#foot5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#customers5').bind('keyup', function() {
$('#conversion5').html( $('input#foot5').sumConv('input#customers5') );
});
$('input#foot6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
$('input#customers6').bind('keyup', function() {
$('#conversion6').html( $('input#foot6').sumConv('input#customers6') );
});
I suppose you have to apply parseFloat to your data. text method returns string, not number. Take a look at the simple example:
var avg1 = "1";
var avg2 = "1";
var avg3 = "1";
var avg4 = "1";
var avg5 = "1";
var avg6 = "1";
var sumavg = (avg1 + avg2 + avg3 + avg4 + avg5 + avg6) / 6;
sumavg will be 18518.5 and not 1.
Wrap all avg data with parseFloat:
var avgN = parseFloat($('#conversionN').text());
You're repeating a lot of code, so I advise employing a DRY technique to minimise that -- e.g. make a bindKeyUp function...
Anyway, you need numbers. .text() returns strings. E.g. "99" + "77" === "9977". This is where your crazy numbers might be coming from. Try this:
var avg1 = ~~$('#conversion1').text();
var avg2 = ~~$('#conversion2').text();
// repeat
~~ just converts its operand to a number (and floors it towards 0). More info.
Or, to make it clearer, use parseFloat:
var avg1 = parseFloat($('#conversion1').text());
var avg2 = parseFloat($('#conversion2').text());
// repeat