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>
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 am using js and php to build an app. I've used a foreach loop in php to create buttons for each row fetched from mysql table. Each button has a unique value (row id).
If someone clicks on of the buttons (each with unique id), there will be a total likes count that holds how many times a button is clicked.
If we have three buttons, and button 1 is clicked, then total likes will be increase by 1. if the same button is clicked again, then the value would decrease by 1.
However, if two buttons of different values are clicked, the total likes add.
When using js, I cant get each button id to pass to the js function loaded from the foreach loop. only the last button value loads to the js function.
Here is what i've tried. the js works but it doesnt apply to each button of the foreach loop.
My Code
<?php foreach($values as $value){
$value['button_id'];
<!-- button --->
<button id="button"
class="button-<?= $value['button_id']; ?>"
value="<?= $value['button_id']; ?>"
onclick="showUser(this.value)" >LIKE
</button>
<!-- button --->
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
Here is an illustration explaining what I mean
Thanks in advance
<script>
var likes = new Array();
function calc(value) {
if(likes[value] == 0 || !likes[value]) {
likes[value]=1;
} else {
likes[value]=0;
}
var sum=0;
for(i=0; i<likes.length; i++) {
if(likes[i]==1){ sum ++ }
}
document.getElementById("total").innerHTML = sum;
}
</script>
<div id=total>0 </div>
<?php
$values = [1,2,3]; //here you can generate values
foreach($values as $value){
?>
<button id="button"
class="button-<?php echo $value; ?>"
value="<?php echo $value; ?>"
onclick="calc(<?php echo $value; ?>)" >LIKE
</button>
<?php
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
Im quite new at javascript so dont expect me to know much else than whats written :)
So i have a javascript file with a lot of javascript codes that almost looks the same except a number is changing with each element.
Most of my code are inside a function just not written since it's a cut out.
The relevant part of my code looks something like:
//Upgrade 1
if (CREDITS >= UpgradePrice1 && Upgrade1 === 0){
document.getElementById("Upgrade1").style.display = "block";}
else{document.getElementById("Upgrade1").style.display = "none";}
//Upgrade 2
if (CREDITS >= UpgradePrice2 && Upgrade2 === 0){
document.getElementById("Upgrade2").style.display = "block";}
else{document.getElementById("Upgrade2").style.display = "none";}
//Upgrade 3
if (CREDITS >= UpgradePrice3 && Upgrade3 === 0){
document.getElementById("Upgrade3").style.display = "block";}
else{document.getElementById("Upgrade3").style.display = "none";
And so on...
The values are assigned in a file named StandardValues.js:
var UpgradeName1 = "Craftmanship Lvl 1";
var UpgradePrice1 = 100;
var UpgradeContent1 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade1 = 0;
var UpgradeName2 = "Craftmanship Lvl 2";
var UpgradePrice2 = 200;
var UpgradeContent2 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade2 = 0;
And so on...
If it were a html code i tried to generate i would use a php while function and make it echo the same code with the changed number a specefic amount of times.
But since this is inside a javascript file i really dont think thats an option?
The javascript code from before is in a .js file.
I think a potential fix could be:
Inside a .php file:
<?php
$Upgrades = 10;
$CurrentUpgrade = 1;
while ($Upgrades >= $CurrentUpgrade){
echo "
<script>
function Upgrade1(){
//Upgrade ".$CurrentUpgrade."
if (CREDITS >= UpgradePrice".$CurrentUpgrade." && Upgrade".$CurrentUpgrade." === 0){
document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'block';}
else{document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'none';}
}
</script>
";
$CurrentUpgrade ++;
}
?>
*Sry for any typo in this part, made it quite quick.
But i would quite like to keep the javascript code inside my .js file instead of having it in my .php file.
So to sum it up i would like to (If possible):
Keep all code inside the .js file
Generate javascript code with javascript code
Repeat the same javascript element with only a number changing with each element
Try to shorten the amount of code by doing this.
Still be able to use any of the assigned variables alone somewhere like in a buy function.
I hope i gave all relevant information :)
Thanks in advance.
You can create a method (in index you are passing the number in the end of your variables):
function myFunction(newUpgradePrice, newUpgrade, index) {
if (CREDITS >= newUpgradePrice && newUpgrade === 0){
document.getElementById("Upgrade" + index).style.display = "block";}
else{document.getElementById("Upgrade" + index).style.display = "none";
}
Is This what you are looking for? Anything needing to be changed to meet your needs?
just try to run this code in two ways:
1) run this code below;
2) enable for loop then run it
<html>
<head>
<script>
function toggle(){
//console.log('hi');
var samplediv = document.getElementById('samplediv');
samplediv.innerHTML = '';
var i = 1;
//for(var i = 0; i < 3; ++i){
samplediv.innerHTML +=
"<div id=\'jh"+ i + "\'>Hi This is "+i+"</div>" +
"<div id=\'edit" + i + "\' style=\'display:none\'>Edit "+i+"</div>" ;
document.getElementById('jh'+i).addEventListener("click", function(){document.getElementById('edit'+i).style.display="block";});
/*
(function(i){
//console.clear();
var key = i;
i += "";
document.getElementById('jh0').addEventListener("click", function(){document.getElementById('edit0').style.display="block";});
//document.getElementById('jh'+key).addEventListener("click", function(){document.getElementById('edit'+key).style.display="none";}, true);
//console.log(i, key);
}(i));
*/
//}
}
</script>
</head>
<body>
<div id="samplediv" >over here</div>
<script>toggle();</script>
</body>
</html>
I'm trying to add addEventLister on every divs using for. I'm sure this is kind of call by reference error. I know there are ways to add events such as on attribute method. Also adding a number of similar listeners is inefficient but I have to make them as you can see.
I've made a IIFE to make key be a value but failed. Do you have any idea to solve this problem?(No jQuery please)
JSFiddle
You will change method which You use to adding new elements.
I replaced innerHTML += to document.createElement for each new item.
var jh = document.createElement('div');
jh.id = 'jh'+i;
jh.innerText = 'Hi This is '+i;
var edit = document.createElement('div');
edit.id = 'edit'+i;
edit.style.display = 'none';
edit.innerText = 'Edit '+i;
samplediv.appendChild(jh).appendChild(edit);
Variable i on click event is visible with last value, so You must get index from other source (from id for example).
document.getElementById('jh'+i).addEventListener("click", function(){
var jhIndex = this.id.split('jh')[1];
document.getElementById('edit'+jhIndex).style.display= 'block';
});