My onclick does not work right the way it should be - javascript

I have this function
<?php
for($i = 1; $i <=9; $i++){
print("<div id='cover'>");
for ( $j = 1; $j <= 9; $j++){
if($i % $j == 8 || $i < $j || $i == $j){
print("<div class='colors' onClick='hello($i, $j)'>");
} else {
print("<div class='pinks' onClick='hello($i, $j)'>");
}
print($i ."+". $j ." ");
print("</div>");
}
print("</div>");
}
?>
Which produces a bunch of div with numbers on it. I want to be able to click on it, and show the result of adding two numbers.
I have this JavaScript function for that
function hello(r, t)
{
$("div.colors, div.pinks").html(r+t);
}
but I do not know how to get only the one div i click on. How can I do that?

Assuming you only want to calculate the element on which the user has clicked, then the method should be more like this:
function calc(element, r, t)
{
element.innerHTML = r+t
}
while the method call ofc would be:
<div>3+2</div>
See this fiddle for example.
http://jsfiddle.net/m9wkr0vz/
To allow more complex calculations without providing methods for every combination, you could use javascripts ability to evaluate expressions given:
function calc(element)
{
element.innerHTML = eval(element.innerHTML);
}
with
<div>(7+1)/(2+2)</div>
see this fiddle: http://jsfiddle.net/u20bgx83/

Related

how to set value to field populated by php in Javascript

I'm using PHP to populate some anchor tags with data from the database. but after some time I want to change its value with Javascript. but the Javascript value don't change PHP value. any idea? how to achieve this with Javascript?
I don't want to make changes in the database. only change value of the field.
var distance = 0;
if (distance <= 0) {
document.getElementById("valueName").innerHTML = 'Changed by Javascript';
}
<?php
$invoice = find_by_id($_GET['job'], 'job_id', 'job_post_payments');
$address = $invoice['address'];
?>
<p id="valueName"><?php echo $address; ?></p>
// javascript code is below this ^^^
No Issue see fiddle -> http://main.xfiddle.com/bf1876ac/works.php
var distance = 0;
window.onload = function() {
if (distance <= 0) {
document.getElementById("valueName").innerHTML = 'Changed by Javascript';
}
if (distance > 0) {
document.getElementById("testValue").innerHTML = 'Changed by Javascript';
}
}
<div>
<p id="valueName">
<?php echo $address; ?>
</p>
</div>
<div>
<p id="testValue">
<?php echo $address; ?>
</p>
</div>
You need understand, php it's backend technology, and javascript it's frontend technology.
if you use javascript, you need wait while browser will render this HTML part. Browser must create a DOM tree. And only then you can manipulate with this DOM tree by javascript.
So this is example:
var distance = 0;
// wait while browser will create DOM tree
window.onload = function() {
if (distance <= 0) {
document.getElementById("valueName").innerHTML = 'Changed by Javascript';
}
}
<p id="valueName">Random Street</p>

Having javascript apply to multiple elements created by php foreach loop

I have this php foreach loop, which read the videos saved in a folder and load them into my page.
Under the videos I have created a like and dislike button, which i would like to work with javascript.
The problem is that I cant figure out, how to point js to buttons, when i create unique ID's for the buttons, with a counter in my foreach loop.
My php.
$i=1;
foreach($allfiles as $file) {
if($file != '.' && $file != '..' && $file != video/ini) // sikre den ikke
producere . og .. files
{
echo "<div>
<div>
<video width=\"$videoW\" height=\"$videoH\"
controls>
<source src=\"". $dir . $file ."\" type=\"video/mp4\">
<source src=\"". $dir . $file ."\" type=\"video/ogg\">
</video>
</div>
<div><strong> Recorded:</strong> $file </div> </div>";
echo '<img src="/img/like-icon.png" id="like'.$i.'"
style="width:40px;height:40px;">';
echo '<img src="/img/dislike-icon.png" id="dislike'.$i.'"
style="width:40px;height:40px;">';
echo '<p style=display:none; id="text'.$i.'">Submitted!</p>';
$i++;
My javascript
<script type='text/javascript'>
for (var i = 0; i < 100; i++) {
var button = document.getElementById(like[i]);
var button2 = document.getElementById(dislike[i]);
button.onclick = function() {
var text = document.getElementById(text[i]);
var like = document.getElementById(like[i]);
var dislike = document.getElementById(dislike[i]);
if (text.style.display !== 'none') {
text.style.display = 'none';
}
else {
text.style.display = 'block';
like.style.display = 'none';
dislike.style.display = 'none';
}
};
button2.onclick = function() {
var text = document.getElementById(text[i]);
var dislike = document.getElementById(dislike[i]);
var like = document.getElementById(like[i]);
if (text.style.display !== 'none') {
text.style.display = 'none';
}
else {
text.style.display = 'block';
like.style.display = 'none';
dislike.style.display = 'none';
}
};
};
Your code is very weird... Why are you looping a hundred time to select one element ?
You should look at querySelector and querySelectorAll with which you can select anything using a css selector. For example :
document.querySelectorAll('.like');
Will return a node list (which you can loop over) containing every element with class="like"
In this case you might want to add an event listener over each element. You can imagine something like this :
var likes = document.querySelectorAll('.like');
for (var i = 0, length = likes.length; i < length; i++) {
likes[i].addEventListener('event', myFunction);
}
If you don't like querySelectors, you still have some other ways to select multiple elements such as :
getElementsByClassName
getElementsByTagName
Also, you shouldn't overwrite style attribute. It's more comfortable to work on project where it is easy to find initial state and changed state. Maybe you should think of a class hidden (for example) which would be like this :
.hidden {
display: none;
}
So if you want to hide them all, you'd juste have to run :
var likes = document.querySelectorAll('.like');
for (var i = 0, length = likes.length; i < length; i++) {
likes[i].classList.add('hidden');
}
In case this is resulting of an action :
var likes = document.querySelectorAll('.like');
for (var i = 0, length = likes.length; i < length; i++) {
likes[i].addEventListener('event', myFunction);
}
function myFunction() {
this.classList.toggle('hidden');
}
If I am not wrong,you want like/dislike for perticular video,then try
onclick event on like/dislike image icon .
onclick="user_responce(responce,id)"
where,
responce:- 1:like,2:dislike
id:- unique video id
In user_responce function do what you want according to responce.
Hope this work for you.

Jquery looped array selectors with custom element ID's

Going through the other posts i must either have something wrong with my code or my logic is fundamentally flawed.
So what happens is i have a series of array elements that get called/written, these array elements need to have sub elements modified by java script.
Everything was workign before i needed to add an array i.e i was using a single element selector ID for the functions below and got the correct results. However after adding unique ID's in a loop it doesn't want to change.
So here's what happens, I have a separate div that is hidden. This prints out how many elements are in the array as its a PHP session variable. $Carray is a count function and works correctly.
<div class="Carray"><?php echo $Carray;?></div>
Then as the items are looped they add an array ID
<?php
$arrayID = -1;
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
<div id="subP_<?php echo $arrayID;?>" class="booking_action">-</div>
<div id="booking_people_<?php echo $arrayID;?>" class="booking_people_number">
<?php echo $list["i_quantity"] ?>
</div>
<div id="addP_<?php echo $arrayID;?>" class="booking_action">+</div>
<?php }} ?>
Then in Javascript i call a loop function that counts through however many $Carray elements there are and then corresponds the correct function actions to the correct div ID's
//get the counted array variable and force as an int
var js_var = parseInt($('.Carray').html(),10);
// loop for however many array elements there are
for (i = 0; i < js_var; i++){
// get the amount of people from a field
var ppl_P = parseInt($('#booking_people_'+i).html(),10);
// subtract 1 person and then change the output to match the new people count
$("#subP_"+i).click(function() {
if(ppl_P >= 2){
ppl_P -= 1;
$('#booking_people_'+i]).html(ppl_P);
}
});
// Add 1 person and then change the output to match the new people count
$("#addP_"+i).click(function() {
ppl_P += 1;
$('#booking_people_'+i).html(ppl_P);
});
}
****************************** EDIT **********************
So based on Jimmi Elofsson answer which works beautifully, i want to expand this to effect elements that are not inside the parent/child selectors. The selector is '.booking_price_inner' which is another div stored elsewhere. I am assuming the line that needs the correct syntax is the marked line.
The '.booking_base_price' is within the parent/child element.
$(".subPerson").click(function() {
// Subtract Person
var subPeopleCount = getCurrentCountByPeopleItem($(this).parent()) - 1;
$(this).parent().children('.booking_people_number').html(subPeopleCount>1 ? subPeopleCount : 1);
//Change price
var totalPriceS = subPeopleCount * getBasePrice($(this).parent());
$(this).parent().children('.booking_price_inner').html(totalPriceS); <-------
});
$(".addPerson").click(function() {
//Add person
var addPeopeCount = getCurrentCountByPeopleItem($(this).parent()) + 1;
$(this).parent().children('.booking_people_number').html(addPeopeCount);
//Change price
var totalPriceA = addPeopleCount * getBasePrice($(this).parent());
$(this).parent().children('.booking_price_inner').html(totalPriceA); <------
});
// get the number of people in the specific array
function getCurrentCountByPeopleItem(peopleItem) {
return parseInt(peopleItem.children('.booking_people_number').html());
}
//get the base price
function getBasePrice(peoplePrice){
return parseInt(peoplePrice.children('.booking_base_price').html());
}
Markup
<div id="<?php echo $arrayID;?>" class="booking_people">
<div class="booking_date_header">People:</div>
<div class="subPerson booking_action">-</div>
<div class="booking_people_number"><?php echo $list["i_quantity"] ?></div>
<div class="addPerson booking_action">+</div>
<div class="booking_base_price"><?php echo $list["i_base_price"] ?></div>
</div>
<div class=spacer></div>
<div class=cost>
<div class=booking_price_inner></div>
</div>
If you don't mind, I did some changes in your code.
you could make your add/substract element use the same click function with the help of some DOM traversing. That way you wouldnt need the CArray to keep track of the buttons.
Javascript:
// subtract 1 person and then change the output to match the new people count
$(".subPerson").click(function() {
var subPeopleCount = getCurrentCountByPeopleItem($(this).parent()) - 1;// Substract by one.
$(this).parent().children('.booking_people_number').html(subPeopleCount>1 ? subPeopleCount : 1);
});
// Add 1 person and then change the output to match the new people count
$(".addPerson").click(function() {
var addPeopeCount = getCurrentCountByPeopleItem($(this).parent()) + 1; // Increase by one.
$(this).parent().children('.booking_people_number').html(addPeopeCount);
});
function getCurrentCountByPeopleItem(peopleItem) {
return parseInt(peopleItem.children('.booking_people_number').html());
}
PHP:
<?php
$arrayID = -1;
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
<div class="booking_people_item" id="<?php echo $arrayID;?>">
<div class="subPerson booking_action">-</div>
<div class="booking_people_number">
<?php echo $list["i_quantity"] ?>
</div>
<div class="addPerson booking_action">+</div>
</div>
<?php }} ?>
I added a div wrapper around your elements called booking_people_item.
from what I see - you're definig click functions in a loop. Those click functions have a reference to a ppl_P variable. When you define the click, it seems OK. But when the click is triggered, the ppl_P variable is already set to the value from loops last iteration. So, whenever you call that click function, it always has the same result, doesn't it?
The proper way to do it would be to pass this ppl_P variable as a parameter, so you don't have a reference to a variable that was already changed in the other scope. Something like:
function addClickFunction(i, ppl_P){
$("#subP_"+i).click(function() {
if(ppl_P >= 2){
ppl_P -= 1;
$('#booking_people_'+i]).html(ppl_P);
}
});
// Add 1 person and then change the output to match the new people count
$("#addP_"+i).click(function() {
ppl_P += 1;
$('#booking_people_'+i).html(ppl_P);
});
}
And then use this function inside the loop:
var ppl;
for (i = 0; i < js_var; i++){
ppl = parseInt($('#booking_people_'+i).html(),10);
addClickFunction(i, ppl);
}
This hasn't been tested, but I'm pretty sure you'll get the point :)

Use existing javascript to trigger if else in php

I have the following script within a page on my site which adds + - buttons to a qty entry field:
<script language="javascript">
jQuery.noConflict();
jQuery(document).ready(function() {
var $cartAdd = jQuery('#cartAdd')
, $quantity = $cartAdd.find('input');
$cartAdd.append('<div class="inc button">+</div><div class="dec button">-</div>');
jQuery(".back").change(function(){
$quantity.val(1).change();
});
$cartAdd.click(function(evt) {
var $incrementor = jQuery(evt.target)
, quantity = parseInt($quantity.val(), 10);
if($incrementor.hasClass('inc')) {
quantity += 1;
} else if($incrementor.hasClass('dec')) {
quantity += -1;
}
if(quantity > 0) {
$quantity.val(quantity);
xhr.getPrice();
}
jQuery(".back").change(function(){
xhr.getPrice();
});
});
});
</script>
I want to be able to hide/unhide a div when var $cartAdd goes above 1
I tried using something like
var $cartAdd = jQuery('#cartAdd')
, $quantity = $cartAdd.find('input');
<?php $trigger = "<script>document.write(quantity)</script>"?>
followed by
<?php echo $trigger;?>
and i expected that to echo the value in the entry box but it didn't.
Is it achievable?
You must understand that all php scripts are executed BEFORE the javascript.
What's wrong with simply grabbing the quantity and hiding if needed?
if( $('#cartAdd').find('input').val() > 1 )
{ $('#div_we_want_to_hide').hide() }
just put that inside a document.ready and it should work fine

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;

Categories