Divide the anchor string value? - javascript

I have an anchor which I inject in HTML in jqGrid formatter as below:
var number = rowObject.number;
var plateNumber = rowObject.plateNmber;
var markup = "<a href=%Href%;>%Text%</a>"
var replacements = {
"%Text%": plateNumber ,
"%Href%": "javascript:Search.openViewByPlateNumber(" + number + "," + plateNumber + ")"
};
markup = markup.replace(/%\w+%/g, function(all) {
return replacements[all];
});
Here is my OpenViewByPlateNumber function:
var OpenViewByPlateNumber = function(number, plateNumber) {
// Do something
};
In the UI there will be a number in the grid. When I click on the number the openViewByPlateNumber function will be called. Everything is working fine for me. The problem is the plate number is a string type. It is a number but it can be 1, 2, 3/4, 340/2 etc.
It's working fine when number is simple like 1, 5 or 9 but if number is 340/2, then the method receives a value of 170.5. It divides the number. So how I can pass it as string?

To pass the values to the function as a string wrap them in quotes:
"%Href%": 'javascript:Search.openViewByPlateNumber("' + number + '","' + plateNumber + '")'

Related

Sum of toFixed not working correctly

I have the following code that calculates and shows the sum of two values.
var oldprice_formated = parseFloat(oldprice).toFixed(2);
var extraPrice = parseFloat(3).toFixed(2);
if(initials != '') {
var new_price = oldprice_formated + extraPrice;
$('.product-detail .woocommerce-Price-amount.amount').html('<span>€</span>'+new_price);
} else {
$('.product-detail .woocommerce-Price amount.amount').html('<span>€</span>'+oldprice_formated);
}
For example:
oldprice_formated = parseFloat(49.99).toFixed(2);
extraPrice = parseFloat(3.00).toFixed(2)
The expected result: Sum is 52.99
Actual result: Sum is 49.003.00
What am I doing wrong? I assume it's with the number parsing, but not sure what I should change to make it work correctly. Thanks!
.toFixed() returns a string, not a number with only two decimal places.
oldprice_formated = parseFloat(49.99).toFixed(2); // "49.99"
extraPrice = parseFloat(3.00).toFixed(2); // "3.00"
When adding those two variables, instead of a number sum, you're concatenating two strings:
"49.99" + "3.00"; // "49.993.00"
I believe this is what you'll want to do:
var new_price = parseFloat(oldprice_formated) + parseFloat(extraPrice);
Or simply run .toFixed() after you sum those values which were already parsed to floats.
Because toFixed() returns a string, the + operator acts as a string concatenator. If you want it to operate as an addition operator, you must typecast your values as numbers:
let oldprice = 49.99;
let oldprice_formatted = parseFloat(oldprice).toFixed(2);
let extraPrice = parseFloat(3).toFixed(2);
console.log(`string concatenation: ${oldprice_formatted + extraPrice}`)
console.log(`type conversion: ${+oldprice_formatted + +extraPrice}`)

Use same random number in Javascript AND php

I want to generate a random number between 1 and 10, use it in Javascript to return a random item in that array, and use that SAME item in PHP. Thus, I create a random number:
var iRandom = Math.floor((Math.random() * 10) + 1);
I use that number in my Javascript function, and then I have my PHP like this:
$json_a['items'][$iRandomPHP]['title']
Simply said, the $iRandomPHP must have the same random number as in my javascript variable iRandom. I tried jquery .post like this:
$.post('custom_search.php', {iRandomPHP: iRandomPHP});
Trying to convert it in PHP like this:
$iRandomPHP = $_POST['iRandomPHP'];
It doesn't work. Any ideas?
Thanks!
EDIT
For some more complete code:
<script>
var iRandom = Math.floor((Math.random() * 10) + 1);
$.post('custom_search.php', {iRandomPHP: iRandom});
function hndlr(response) {
var item = response.items[iRandom];
document.getElementById("content").innerHTML += item.title + "<br>" + "<img src=" + item.link + ">";
}
</script>
PHP code:
$iRandomPHP = $_POST['iRandomPHP']."haha";
print_r($iRandomPHP);
$url_nocb = "https://www.googleapis.com/customsearch/v1?key=".$key."&cx=013263683795763287108:ne-fxf3oy-a&searchType=image&q=office";
$json_string = file_get_contents($url_nocb);
$json_a = json_decode($json_string, true);
print $json_a['items'][$iRandomPHP]['title']."<br>";
That's all
This line:
$.post('custom_search.php', {iRandomPHP: iRandomPHP});
should read
$.post('custom_search.php', {iRandomPHP: iRandom});
since you are passing the js var iRandom

Javascript - Incrementing specific numbers of a string

I have a string that looks like this
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
Is there an easier way to increment the numbers at the end of "question1" and "answer0" inside of the string? I have tried to separate the contents of the string using the following method:
id = 'CourseContent1_activityContent34169_question1_answer0_ac';
idArray = id.split('_');
originalArray = idArray.slice();
if (idArray) {
idArray.pop();
for (i = 0; i < 2; i++) {
idArray.shift();
}
}
The above results in:
idArray = ["question1","answer0"];
but the final result needs to be a string, I know I'll probably need to concatenate it later, so I can pass it into another argument. I just need to isolate those two numbers and increment only those two. I was searching for an easier way to finish that task but I haven't come across anything like that. Also jQuery isn't an option for me since I'm trying to accomplish this using just javascript and the console. Thank you for your help in advance.
You can try this :
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
var incrementQuestion = function (id) {
return id.replace(/question([0-9]+)/, function (val1, val2) {
return "question" + (parseInt(val2) + 1)
}) }
var incrementAnswer = function (id) {
return id.replace(/answer([0-9]+)/, function (val1, val2) {
return "answer" + (parseInt(val2) + 1)
}) }
then increment using:
id = incrementAnswer(id);
and
id = incrementQuestion(id);
You can use regular expressions to find the string "question1" and replace it with "question2" - or more accurately "question{any number here}" and replace with "question{any other number}"
var id = 'CourseContent1_activityContent34169_question1_answer0_ac'
var re = /question\d+/
var id2 = id.replace(re,"question2")
You can do the same for answer\d+
You should use replace function of RegExp:
Please run the example below:
var id = 'CourseContent1_activityContent34169_question1_answer0_ac';
alert('before:\r' + id)
id = id.replace(/question([0-9]+).*answer([0-9]+)/, function(a, b, c) {
return 'question' + (parseInt(b) + 1) + '_answer' + (parseInt(c) + 1)
// Using parseInt to convert string to number
})
alert('after:\r' + id)
function updateQA(question, answer) {
return 'CourseContent1_activityContent34169_question1_answer0_ac'.replace(/^(.*question)(\d*)(_answer)(\d*)(.*)/gi, '$1' + question + '$3' + answer + '$5');
}
Here's a bit of a less verbose way of doing it:
var increment = function(_, prefix, n) { return prefix + (+n + 1) };
id.replace(/(question)(\d+)/, increment).replace(/(answer)(\d+)/, increment);
The parenthesized matches (i.e. the capturing groups) are passed as separate args to the replacement functions, and there you can just increment them and return with the corresponding prefix.

Convert a string with function calls to an array

I need to convert this function call to a simple array[] but it's not working for some reason.
Here's the fiddle
var LongCombinedReady = $('#GeoImageLat').val(exifObject.GPSLatitude + "," + "'" + exifObject.GPSLatitudeRef + "'")
var LatCombinedReady = exifObject.GPSLongitude + "," + "'" + exifObject.GPSLongitudeRef + "'"
//an attemp to take the values and convert them to an array but it doesn't work.
var LongCombined = [LongCombinedReady];
var LatCombined = [LatCombinedReady];
I've commented it all out in the fiddle also here's an image with GeoCoords if you don't have one for testing.
Test Geotag image
Basically I read the images Geotag and then convert the tag from DMS to DD so it can be used for something like Google maps.
There are three problems:
you are missing an apply in line 49
you are applying array with one item being a string while function you are applying to expects four parameters
at line 43 LongCombinedReady is an jQuery object

Javascript comparison not working properly

I'm working with the billing part of my system and I put an event in my TextBox using javascript and I have two textboxes. First is the cashonhand and change textboxes. But what I'm wondering is why the comparison between two textboxes is not giving me the right answer. Here is my code:
$(document).ready(function () {
$(document).on('click', '.btn-pay-bill', function () {
var cash = parseFloat(Number($('.cashonhand').val())).toFixed(2);
var amtdue = parseFloat(Number($('.amtdue').text())).toFixed(2);
if (cash <= amtdue) {
alert(cash + ' ' + amtdue + ' ' +"Insufficient Cash!!!");
return false;
}
if (cash >= amtdue) {
return true;
}
return false;
});
SO what am I missing here? Here is the output when I compare 100,000 to 78,200.00:
You're comparing alphabetically instead of numerically.
Note that .toFixed() returns a string:
Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.
You'll want to do this comparison before you call .toFixed()
var cash = parseFloat(Number($('.cashonhand').val()));
var amtdue = parseFloat(Number($('.amtdue').text()));
if (cash <= amtdue) {
alert(cash.toFixed(2) + ' ' + amtdue.toFixed(2) + ' ' +"Insufficient Cash!!!");
return false;
}
You can just call .toFixed() wherever you display the number in the UI, or create a separate string version of the value, such as sCash and sAmtDue or something.

Categories

Resources