Change NaN to 0 - javascript

How could I change the NaN text to 0?
Im using a function to show a variable price calculator in a Woocommerce store.
Until some variable are selected Im getting a NaN result, once selected it works fine so I would like to just change the NaN text to zero.
This is the code:
// hook this on priority 31, display below add to cart button.
add_action( 'woocommerce_single_product_summary', 'woocommerce_total_product_variation_price', 31 );
function woocommerce_total_product_variation_price() {
global $woocommerce, $product;
// setup base html... We are going to rewrite this with the standard selected variation
echo sprintf('<div id="product_total_price" style="margin-bottom:20px; display: block;">%s %s</div>',__('Precio Total:','woocommerce'),'<span class="price">'.$product->get_price().'</span>');
?>
<script>
jQuery(function($){
var currency = currency = ' <?php echo get_woocommerce_currency_symbol(); ?>';
function priceformat() {
var product_total = parseFloat(jQuery('.woocommerce-variation-price .amount').text().replace(/ /g ,'').replace(/€/g ,'').replace(/,/g ,'.')) * parseFloat(jQuery('.qty').val());
var product_total2 = product_total.toFixed(2);
var product_total3 = product_total2.toString().replace(/\./g, ',');
jQuery('#product_total_price .price').html( currency + ' ' + product_total3);
}
jQuery('[name=quantity]').change(function(){
priceformat();
});
jQuery('body').on('change','.variations select',function(){
priceformat();
});
priceformat();
});
</script>
<?php }
Thanks in advance

Just check if the variable is NaN and if it is set it to zero.
if(isNaN(product_total)){
product_total = 0
}

A simpler way to do this is:
product_total = product_total || 0
Because product_total is NaN it will assign it to 0. Be careful though because 0 is also considered a falsey value in this scenario.

Related

How to check empty in my input text form with calculate?

I have 2 Input Text in my form how to fix calculate
<?php
$txtA="";
$txtB="";
$textA=0;
$textB=0;
$Total=0;
$txtA = $_POST["TextA"];
$txtB = $_POST["TextB"];
if(empty($txtA)){
$textB=$txtB*0.4;
$Total=$textB;
if(empty($txtB)){
$textA=$txtA*0.4;
$Total=$textA;
if(!empty($txtA) AND !empty($txtB)){
$textA=$txtA*0.65;
$textB=$txtB*0.35;
$Total=$textA + $textB;
Always no data for this code i beginner in php and still learning
You need to know if the value is setted, so we use isset($_POST['yourVariable'])
And you don't need to declare variables when your are defining them with $_POST value, with this said your code ends like this:
<?PHP
$Total=0;
$txtA = $_POST["TextA"];
$txtB = $_POST["TextB"];
if(isset($txtB) && !isset($txtA)){
$textB=$txtB*0.4;
$Total=$textB;
}elseif(isset($txtA) && !isset($txtB)){
$textA=$txtA*0.4;
$Total=$textA;
}
//&& == AND
if(isset($txtA) && isset($txtB)){
$textA=$txtA*0.65;
$textB=$txtB*0.35;
$Total=$textA + $textB;
}
?>

jQuery division - find all price classes and divide

I have a page of items with various prices in GBP, each price is within a span with a class of price, what I would like to do is change the value of ALL the prices to that value divided by 1.2. so along the lines of
$('.price').html() / "1.2";
now i'm aware that this won't work as the format is £10,500 for example, I havent been able to find similar here but i'd like to take that £10,500 value divide it by 1.2 and have the value update to the result (£8,750). Anything I have tried thus far leaves me with NaN and i'm struggling to make progress.
Add a button for testing:
<button id="test-button">Test Currencies</button>
Add the following jQuery:
$('#test-button').on('click', function () {
// Get currency elements
var currencies = $('.price');
var newSymbol = '£';
var eRate = 0.8333;
$.each(currencies, function (index, value) {
// Change value to a number using regex
var number = Number($(this).html().replace(/[^0-9\.]+/g, ""));
// Assign new value and add number formatting
$(this).html(newSymbol + (number * eRate).toFixed(2).toLocaleString('en'));
});
});
Hope it helps.
Here you go :-)
Tested and working.
$("span").each(function()
{
var strNewString = $(this).html().replace(',','');
$(this).html(strNewString / 1.2);
});
function format_price(_input_str){
var input_str=_input_str+''; //if input integer convert to string
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if exist spaces
input_str=input_str.replace(new RegExp('£',"g"), ''); //if exist simbil £
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if wxist
var input_int = parseInt(input_str)||0;
if(input_int==0){ return _input_str;} //return original string
input_str=input_int+'';
var out_str='';
while(input_str.length > 3){
out_str=input_str.substr(-3)+' '+out_str;
input_str=input_str.substr(0,input_str.length-3);
}
if(input_str.length>0){out_str=input_str+' '+out_str;}
out_str='£ '+out_str;
return out_str;
}
$('.price').each(function(){
var this_price=$(this).html();
$(this).html(format_price(this_price));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price">12345</div>
<div class="price">76 09</div>
<div class="price">4576 09</div>
<div class="price">45</div>
<div class="price">£ 12 345 678 </div>

Javascript Variable in Ajax Updater

I am trying to send the javascript variable 'sortlist' to an Ajax function using the following code:
<div id = "output">Drag to sort</div>
<script type="text/javascript">
var session = <? echo $sesh; ?>;
var track = <? echo $trk; ?>;
var sortlist = "sortlist_" + session + "_" + track;
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
})
</script>
The variable appears to be passing successfully to Sortable.create (because I can sort the boxes on the webpage), but it does not appear to be passing into Sortable.serialize within Ajax.updater (because it no longer writes the sort order values to the database).
This code works when I use the literal value in Sortable.serialize, like
parameters:Sortable.serialize('sortlist_1_1'),
I have tried using sortlist as a variable with and without single and double quotes inside Sortable.serialize to no avail. What is the format required to successfully pass this variable information?
For reference,
My AJAX/javascript experience is about a 1 (scale 1-10); my PHP/MySQL experience is about a 7 (scale 1-10).
Try this:
Sortable.create(sortlist,{
onUpdate:function(sortlist){return function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
};}(sortlist);
})
Let's go one step further then:
function(sortlist){
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
});
}(sortlist);

Why is the javascript variable undefined? (2nd time around...)

I am reposting this question with revised code that use more of jQuery.
Here is the HTML code that defines the objects:
<LEGEND><b>Select Study Sample</b></LEGEND>
<p>
<P CLASS=select_header>Study - Box - Well - Lab ID<br>
<SELECT multiple size=20 NAME="stylabid" ID="stylabid" onchange=show_stylabid() onclick=clear_fetch() STYLE="width: 115px">
<?php
$i=0;
while ($i < $numstylabids) {
$styarr = pg_fetch_row($stylabidresult);
echo "<option value=$styarr[0]>$styarr[1]\n";
$i++;
}
?>
</select>
and
<LEGEND><b>Select Project Sample</b></LEGEND>
<p>
<P CLASS=select_header>Project - Box - Well - Lab ID<br>
<SELECT multiple size=20 NAME="pjtlabid" ID="pjtlabid" onchange=show_pjtlabid() onclick=clear_fetch() STYLE="width: 115px">
<?php
$j=0;
while ($j < $numpjtlabids) {
$pjtarr = pg_fetch_row($pjtlabidresult);
echo "<option value=$pjtarr[0]>$pjtarr[1]\n";
$j++;
}
?>
</select>
Now, here is the javascript; I am simply trying to get the values of the selected object, which can be either a Study or a Project. I use this later to retrieve data from the database:
function fetchgenotype() {
var ms, mndx, ss, sndex = 0;
ms = $("#marker")[0].selectedIndex;
if (Study_selected) {
ss = $("#stylabid")[0].selectedIndex;
sndx = $("#stylabid").val(ss);
} else
ss = $("#pjtlabid")[0].selectedIndex;
sndx = $("#pjtlabid").val(ss);
}
// for debugging...
alert('ss='+ss+', sndx='+sndx);
This code dies on the line sndx = ... Would really appreciate any help!
TIA
Currently i don't know what $("#marker") an Study_selected are.
Assuming there is anything OK so far, change the function into:
if (Study_selected) {
sndx = $("#stylabid").val();
} else
sndx = $("#pjtlabid").val();
}
val() returns the value of a form-element when used without an argument, otherwise it will set the value and return an jQuery-object.
There is no need to retrieve the selectedIndex, you may access the value of the select-element directly(it will be the value of the currently selected option)
I think you have a syntax error
sndx should be sndex .. or the other way around
var ms, mndx, ss, sndex = 0; // <--
$("#pjtlabid").val(ss) // <-- setter method
.val(value) is also a setter method so sndx is undefined because it never was defined with any value
It's a typo:
var ms, mndx, ss, sndex = 0;
should be
var ms, mndx, ss, sndx = 0;

JS: Counter decrease, at hide()

If I have a normal
<?php echo "Today (".mysql_num_rows($query)."); ?>
That turns out as Today (10) if there's 10 rows.
Now under this counter I have an while() that outputs all the rows inside a <tr>.
In a <td> inside the tr i have this delete button, which hides closest 'tr'.
How can I when you hide the 'tr' the Today(10) will decrease to Today(9) ?
--
I dont think its possible with the current counter (mysql_num_rows), but maybe if you count how many 'tr' there is, in the Today(), you could make something that decreases, but I do not know how to do this. Although this is just an thought..
Alter your PHP accordingly:
<?php echo 'Today (<span class="counter">' . mysql_num_rows($query) . '</span>)'; ?>
And have something like this for your delete button:
$('#theTable').delegate('button.delete', 'click', function (event) {
$(this).closest('tr').slideUp();
$('span.counter').text(function (index, val) {
return (parseInt(val, 10) - 1);
});
event.preventDefault();
});
Note the use of delegate: It's much more efficient than it would be to bind an event handler to each delete button.
You'll have to alter the selector for your table and your delete button accordingly.
you can do something like this :
$('.deleteButton').click(function() {
var curn = parseInt($('.counter').text(), 10);
if(curn - 1 >= 0)
$('.counter').text(curn - 1);
});
and change your echo to
<?php echo "Today (<span class='counter'>".mysql_num_rows($query)."</span>)"; ?>
Wrap the number so you can select is easily:
<?php echo 'Today (<span id="number">'.mysql_num_rows($query).'</span>)'; ?>
Then when a delete button is clicked:
// Get the number element once
var num = $('#number');
// Set an onclick event on your button
$('.delete').click(function(){
// Find the closest table row and remove it
$(this).closest( 'tr' ).remove();
// num.text() will get the text inside the number element
// parseInt is used to convert it from string to int
// subtract 1 to update the number
var newNumber = parseInt( num.text(), 10 ) - 1;
// And set the new number text
num.text( newNumber );
// Stop the default browser action - might cause the page to reload or to scroll
return false;
});
try it at: http://jsfiddle.net/xMZgv/7/
Today(<span id="counter">3</span>)
<table>
<tr><td>hello</td><td>delete</td></tr>
<tr><td>world</td><td>delete</td></tr>
<tr><td>hi</td><td>delete</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js"></script>
<script>
$(function() {
$('table tr').find('td:last').click(function() {
$(this).parent().remove();
$('#counter').html($('#counter').html() - 1)
})
})
</script>
Output your counter to a JavaScript var and use it in your loop and Today() function call. I'm assuming you're trying to output a client side function call from the server?
 <?php echo "var count=".mysql_num_rows($query).";Today(count);" ?>
In your delete handler decrement count and call Today(count) again.

Categories