Problems to get a dynamic var in javascript - eval() - javascript

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/

Related

How to input array from php into javascript function and display the output using HTML?

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).

Javascript, dynamic color HTML inputbox if value insert is included in range

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

JS switch value onclick

I've an array thats downloaded from php to JS with paths to images, i want to switch the value on clicking the arrow image, -1 for left and +1 for right, my code doesn't seem to work tho.
<script>
var urls = <?php echo json_encode($urls); ?>;
var i = 4;
function goleft(){
if (i > 1) {
i = i - 1;
return i;
}
}
document.write('<div id=showcase><a id=leftslide><img onclick=goleft() src=images/left.png></a><img id=bigpic src='+urls[i]+'></div>');
</script>
img src=images/left.png is the left arrow.
urls[i] is what i want to change onclick an make it interactive
Thanks every one for guiding me to solution, it works with jquery now.
var urls = <?php echo json_encode($urls); ?>;
var i = 4;
function goleft(){
if (i > 1) {
i = i - 1;
$("#bigpic").attr("src",urls[i]);
}
}
</script>
<div id=showcase><a id=leftslide><img onclick=goleft() src=images/left.png></a><img id=bigpic src=></div>

Javascript or Jquery / PHP / Web Socket number formatting issue

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

Declare and use variables via input fields and php array + for loop

I build a questionnaire, actually a kind of a online survey. I came across major issue about the code below. No matter how hard I try, my array obviously doesn't return anything. I provide a full code below, and it will be really helpful if anyone can locate errors. The result returns empty page.
HTML FORM
<form action="process.php" method="post">
Title: <br/><input type="text" name="title"><br/><br/>
Question 1: <br/><textarea name="ask[1]"></textarea><br/>
Question 2: <br/><textarea name="ask[2]"></textarea><br/>
Question 3: <br/><textarea name="ask[3]"></textarea><br/><br/>
<input type="submit" name="submit" value="PROCEED">
</form>
PHP FILE PROCESS.PHP
<?php
$blah = "";
$title = $_POST['title'];
$ask = array();
for($j=1; $j<4; $j++) {
$ask[$j] = $_POST['ask$j'];
if($ask[$j] != "") {
$area = '<textarea name="ans11"></textarea>';
$addmore = '<button type="button" name="addmore" onClick="addmore('.$j.');">Add more</button>';
$blah .= $j.'): '.$ask[$j].'<br/>'.$area.'<br/><div id="inner$j"></div>'.$addmore.'<br/><br/>';
}}
echo $blah;
?>
JAVASCRIPT FILE
var am = [];
for(var i=1; i<101; i++){
am[i] = 1;
}
function addmore(index) {
am[index]++;
var textarea = document.createElement("textarea");
textarea.name = "ans" + index + am[index];
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
I believe your problem is how you're capturing the array in PHP. These lines:
for($j=1; $j<4; $j++) {
$ask[$j] = $_POST['ask$j'];
Should be:
for($j=1; $j<4; $j++) {
$ask[$j] = $_POST['ask'][$j];
Or more simply:
$ask = $_POST['ask'];
PHP will convert form elements that specifies an array.
ask[...] will be converted to an array:
$_POST = array(
'ask' => array(...)
)
You can observe the behavior by var_dumping the $_POST array: var_dump($_POST);
See HTML Element Array, name="something[]" or name="something"?

Categories

Resources