I'm modifying one script and learning JS and Web Sockets while changing it to my needs.
Script is a simple calculator between BTC and USD.
Code works fine, but I cant get proper number formatting since I'm not certain should I do it in JS or PHP.
HTML
<input type="text" class="form-control" id="amtUSD" value="<?php echo $data['price_usd']; ?>">
JS
var ember = [];
var usdInput = document.getElementById("amtUSD");
var btcInput = document.getElementById("amtBTC");
ember.btcPrice = <?php echo $data['price_usd']; ?>;
ember.socket = io.connect('https://socket.coincap.io');
ember.socket.on('trades', function(data) {
var amt = document.getElementById("amtUSD");
if (data.coin == "BTC") {
ember.amtUSD = usdInput.value;
ember.amtBTC = btcInput.value;
ember.usdCalc = ember.amtBTC * data.msg.price;
if(data.msg.price > amt.value) {
$(amt).addClass('increment');
} else {
$(amt).addClass('decrement');
}
$("#amtUSD").attr("value", ember.usdCalc);
setTimeout(function () {
$(amt).removeClass('increment decrement');
}, 700);
}
});
$("#amtBTC").bind("change paste keyup", function() {
ember.usdCalc = $(this).val() * ember.btcPrice;
$("#amtUSD").attr("value", ember.usdCalc);
});
I tried with PHP. It works for the first value, but as soon as it gets new value, it reverts to non formatted value.
<?php echo number_format($data['price_usd'], 2); ?>
So, I presume I need to format numbers in JS or Jquery - it doesnt matter for this case, whichever is simpler.
Thanks in advance
Related
I am trying to take the values from the array in PHP, and pass them onto the JavaScript function. The code below functions as intended. The values are taken from a MySQL database and entered into their respective arrays. [Disclaimer: New to coding]
echo "<div id='demo'></div>";
$sql = mysqli_query($conn, "SELECT DISTINCT Safepoint_name,Latitude,Longitude FROM safepoints");
while($row = mysqli_fetch_array($sql)) {
$latl[] = $row['Latitude'];
$long[] = $row['Longitude'];}
foreach($latl as $name) {
echo "$name";
}
foreach($long as $name) {
echo "$name";
}
The problem I am having is with code as shown below. It does not process and show the output as desired. I want the output to be shown one after the other after subtracting the two arrays. I would prefer if the output could be designed via HTML. What am I supposed to do?
[Note: The function is just a trial function just for checking whether it works]
<p id="demo"></p>
<button onclick = "myFunction()">Submit</button>
<script type="text/JavaScript">
let text = "";
function myFunction() {
var latitute = <?php echo json_encode($latl); ?>;
var loni = <?php echo json_encode($long); ?>;
for (let i = 0; i < latitute.length; i++)
{
var x[i] = latitute[i]-loni[i];
text += x[i]+"<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
I think your problem here is that you are defining variable x in a cycle (first warning something is fishy) and you are assigning a value into it's array index at the same time (which is technically possible, but not recommendable, in PHP, but definitely not in JS where is causes syntax error).
You can skip the variable completely and just generate the text.
for (let i = 0; i < latitute.length; i++) {
text += (latitute[i]-loni[i]) +"<br>";
}
Or if you need to keep the result array for later, you should define it as an array before the cycle:
var x = [];
for (let i = 0; i < latitute.length; i++) {
x[i] = latitute[i]-loni[i];
text += x[i]+"<br>";
}
Update:
<p id="demo"></p>
<button onclick = "myFunction()">Submit</button>
<script type="text/JavaScript">
console.log('Preparing JS...');
let text = "";
function myFunction() {
console.log('Calculating demo...');
var latitute = [9,8,7];
var loni = [1,2,3];
for (let i = 0; i < latitute.length; i++) {
text += (latitute[i] - loni[i]) + "<br>";
}
document.getElementById("demo").innerHTML = text;
alert('Demo OK');
}
</script>
JS runs OK after submit.
Right-Click your page and use "View page source file" to check what PHP generates into the JS - if it's really valid array as in the example above.
Then open Debugger (press F12 in browser) and see Console if there are any Syntax or other errors.
If you are in doubt if JS is running, you can add console.log() and/or alert() into your code (see the example).
Good Afternoon,
I need to check if the value insert by the user inside an inputbox on my PHP page it's included in specific range. So if the value insert isn't included in this range i need to color the text in the inputbox or show a message. The range is definited from two PHP variables.
For example if my range will be >10 and <20 any number from 11 to 19 will be 'ok' and any another number (out of this range) will be colored in red or something like this.
I tried to use something like this:
<script>
function checkFilled() {
var inputVal = document.getElementById("myinputbox");
var min = "<?php echo $someVar2; ?>";
var max = "<?php echo $someVar3; ?>";
if (inputVal.value < min) {
inputVal.style.backgroundColor = "yellow";
}
else if (inputVal.value > max) {
inputVal.style.backgroundColor = "yellow";
}
else {
inputVal.style.backgroundColor = "";
}
}
checkFilled();
</script>
PHP:
$someVar2 = 10;
$someVar3 = 20;
echo '<input type="text" id="myinputbox" onchange="checkFilled();">';
This way doesn't work and all number I insert in my inputbox will be change the color to yellow. If I try to set the min and the max variable with a number directly in Javascript (without reading the variable from PHP) the script work.
Could anyone please help me?
Thanks you very much for your help.
Regards
Good Afternoon
you can go this way
<input type="text" id="myinputbox" oninput="myFunction()">
<script>
function myFunction() {
var inputVal = document.getElementById("myinputbox").value;
var min = "<?php echo $someVar2; ?>";
var max = "<?php echo $someVar3; ?>";
if (inputVal.value < min) {
document.getElementById("myinputbox").style.backgroundColor = "yellow";
}
else if (inputVal.value > max) {
document.getElementById("myinputbox").style.backgroundColor = "red";
}
else {
document.getElementById("myinputbox").style.backgroundColor = "";
}
}
</script>
you have to use oninput event and try debugging you will get it
All the best
I have a js function that I have working to display a list of categories with the quiz results. However the quiz results are calculated in the javascript and the php table I created just calls the initial array without the result. That means I can order by anything in the array but I would like to order by the quiz %. Should I be doing this in the js or php?
setCategoryOverview: function() {
results.comp.cats = {};
$e.find('.wpProQuiz_catOverview li').each(function() {
var $this = $(this);
var catId = $this.data('category_id');
if(config.catPoints[catId] === undefined) {
$this.hide();
return true;
}
var r = Math.round(catResults[catId] / config.catPoints[catId] * 100 * 100) / 100;
results.comp.cats[catId] = r;
$this.find('.wpProQuiz_catPercent').text(r + '%');
$this.show();
});
},
Here is the php table which just is ordered by category_id
<div class="wpProQuiz_catOverview" <?php $this->isDisplayNone($this->quiz->isShowCategoryScore()); ?>>
<h4><?php _e('Categories', 'wp-pro-quiz'); ?></h4>
<div style="margin-top: 10px;">
<ol>
<?php foreach($this->category as $cat) {
if(!$cat->getCategoryId()) {
$cat->setCategoryName(__('Not categorized', 'wp-pro-quiz'));
}
?>
<li data-category_id="<?php echo $cat->getCategoryId();?>">
<span class="wpProQuiz_catName"><?php echo $cat->getCategoryName(); ?></span>
<span class="wpProQuiz_catPercent">0%</span>
</li>
<?php } ?>
</ol>
</div>
</div>
As JayBlanchard is proposing, the best option would be to generate the percentages and do the ordering beforehand (in the server side). However, it might be possible that that isn't an option. You could try this approach to do the ordenation in the client side (fiddle):
// Pre-calculate the percentages using js as you're doing.
var results = [];
$("ol li").each(function (index, item) {// Store the results in an array of objects.
results.push({
id: $(item).data("category_id"),
name: $(".wpProQuiz_catName", this).text(),
percentage: $(".wpProQuiz_catPercent",this).text()
});
});
results.sort(function(a,b){// Sort the array by percentage.
var numA = +(a.percentage.slice(0,-1)), numB = +(b.percentage.slice(0,-1));
return numB - numA;// Ascending order
});
$("ol li").each(function (index, item) {// Substitute li information acccording to the ordered array.
$(item).attr("data-category_id", results[index].id);
$(".wpProQuiz_catName", this).text(results[index].name);
$(".wpProQuiz_catPercent",this).text(results[index].percentage);
});
It can probably be done with less loops due to the fact that you're calculating the percentages somewhere else in your js (you could take advantage of that and create the array of results there).
Hope it helps.
Based on Adding a parameter to the URL with JavaScript i tried to make a script that adds parameters to the existing URL but kinda failed and i don't know why...
<script type="javascript">
function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
</script>
<label>
<select name="id" onchange="window.location='somepage.php?page=inserari-note&selected_value='+this.value">
<option>--Alege user--</option>
<?php
while($runrows = mysql_fetch_assoc($run))
{
$user = $runrows ['user_login'];
echo"<option value=\"$user\">$user</option>";
}
?>
</select>
</label>
<label>
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">
<option>--Alege Elev--</option>
<?php
while($runrows4 = mysql_fetch_assoc($run4))
{
$elev = $runrows4 ['Nume'];
echo"<option value=\"$elev\">$elev</option>";
}
?>
</select>
</label>
So the first select is populating the second select with students and also change the URL into somepage.php?page=inserari-note&selected_value='+this.value which works great but when i click on the options from the second select, nothing happens. In my opinion it should add at the existing URL which is the one i have mentioned before, the values &selected_valueelev="chosen-option" so that the URL should look like let's say somepage.php?page=inserari-note&selected_value=user&selected_valueelev=student. What am i doing wrong?
You should define script tag by the following:
<script type="text/javascript">
...
</script>
And also you have a syntax bug in the following:
// remove + before this.value
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">
I have a simple problem to solve, I know how to do it in PHP but have no ideia how to do it in javascript.
I gave a dinamic form, with N lines.
// HTML
<form>
$total = 0;
for($x...){
?><input type="text" name="field<?PHP echo $x; ?>" onChange="f5(this.form,<?PHP echo $total; ?>)" />
$total++;
}
</form>
//Js
function f5(formulario,total){
math = 0;
for(numero=0; numero<=total; numero++){
var foo+eval(numero) = formulario.quantidade+eval(numero).value
math = math + foo+eval(numero);
}
}
In Js I need to get all values of the form and do some maths and send it back to the html.
Anyone have an example of how do that? I am trying to use eval() funcion with no sucess.
Regards,
Thanks,
You can use the bracket operator to access a dynamic property
function f5(formulario,total) {
var math = 0;
for(var numero=0; numero < total; numero++){
math += Number(formulario["field" + numero].value);
}
return math;
}
Here's a live example http://jsfiddle.net/WFdZJ/