I found this question to be exactly the same problem I'm facing, but the answers suggested using objects for dynamic access. This might be well and good, but I'm looking for the exact simple answer on how to include a variable in a function's name.
I'm using ClockPick and dare not mess up the code, so I can't use objects or anything else. The problem is that with [ $("#clockpick"+x).clockpick ] the result isn't [ $("#clockpick0").clockpick ] but instead [ $("#clockpick"+x).clockpick ].
This all happens inside a PHP loop and it looks something like this:
var x = 0; (declared previously outside of the loop)
<script>
function doit()
{
$("#clockpick"+x).clockpick
({
starthour: 7,
endhour: 20
...
});
}
x++;
timepicker.php
<script>var times = 0;</script>
<?php
$goo = $_POST['goo'];
for ($foo = 0; $foo < $goo; $foo++)
{
?>
<script>
function clocker()
{
$("#clockpick"+times).clockpick
({
starthour: 7,
endhour: 20
});
} times++;
</script>
<?php
print "<input type='text' id='clockpick$foo' onclick='clocker()' />
?>
As mentioned, this works ok if I manually set "times" to a number, but as you can see, I don't know what number $goo has. In all, this is still a simplified demo from the actual page of 153 rows.
You are using a javascript variable to be incremented in a php loop.
The problem is that php will just write your javascript code as is, printing $("#clockpick"+times) at each iteration of the php loop.
To achieve what you want to do, you should use $foo instead of the useless javascript variable times like this
<?php
$goo = $_POST['goo'];
for ($foo = 0; $foo < $goo; $foo++)
{
?>
<script>
function clocker()
{
<?php
print "$('#clockpick$foo').clockpick"
?>
({
starthour: 7,
endhour: 20
});
}
</script>
<?php
print "<input type='text' id='clockpick$foo' onclick='clocker()' />"
}
?>
Related
I am creating a reacting quiz that changes based on the answer you have selected using PHP and Javascript.
This is the working example of the radio button script that changes the innerHTML based on what answer you have selected. Using PHP to write the value as 'AQN20'
$(function () {
$("input[name=AQN2]:radio").click(function () {
if ($('input[value=AQN20]:checked').val()) {
document.getElementById("MCA2").innerHTML = "this is right";
}
else {
document.getElementById("MCA2").innerHTML = "this is wrong";
}
});
});
I am trying to replicate the same behaviour for checkboxes but consider multiple answers.
So, I have a PHP array where you type your answers.
$multipleCheckboxOptions = array(
'Option A',
'Option B',
'Option C',
'Option D'
);
I then create each answer as a checkbox option and assign the arrays Key to the Value. So in the example directly below, this would be the first option in the array (outputted HTML example).
<input type="checkbox" name="AQN1" class="checkbox Q1" value="0" id="0mcq">
I then have another array where you can select what the correct answers are.
$correctAnswerNumber = array(0,2)
In this instance, answer 1 and 3 would be the correct answers.
Below is where I am currently stuck for the checkbox on behaviour using PHP,
$(function () {
$("input[name=<?php echo $uniqueIDAnswer ?>]:checkbox").click(function () {
if ($('input[value=<?php echo $correctAnswerNumber?>]:checked').val()) {
document.getElementById("CA<?php echo $mcanumber?>").innerHTML = "<?php echo $correctAnswerDescriptionAnswer ?>";
}
else {
document.getElementById("CA<?php echo $mcanumber?>").innerHTML = "<?php echo $incorrectAnswerDescriptionAnswer ?>";
}
});
});
I need the [value=] tag ($correctAnswerNumber) to output 0 && 3
'input[value=<?php echo $correctAnswerNumber?>]:checked'
I hope I have explained this clearly enough! Sorry if it is confusing.
It should be RadioButtonGroup instead of CheckBoxGroups and also create one more variable which is call as Answer and where the true answer is placed set that radio button as Answer and make a logic answer is selected it will be ur right answer
I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.
I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps
Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.
You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});
<input type="button" onclick="restartBattle('Battle=Trainer&BattleID=294','nFOgYlQGjn')" value="Restart Battle" style="width:160px;">
That is the coding of the button. Unless the restart code is entered as well (it's dynamic, changes every refresh), I can't click the button with the methods of Javascript or jQuery that I've tried.
'nFOgYlQGjn' is the restartCode. I've tried this coding to click the button, but it won't work.
var btn = document.querySelector('input[value="Restart Battle"]');
if (btn) {
var x = Math.round((Math.random() * 90) + 663);
var y = Math.round((Math.random() * 15) + 589);
function restartBattle(url, restartCode) {
$('#battleContent').html('Loading...<br /><br />');
$('#battle').load('http://tpkrpg.net/core/battles/battle.php?'+url+'&RestartCode='+restartCode);
}
//btn.click();
}
This should work, since I took the function restartBattle part out of the source code, but it still won't work. Any ideas?
Pass the data as an object to the script. You could use on('click', method here) or click(method here) on the id of the input tag. Make sure jquery is included too.
button:
<input type="button" value="Restart Battle" id="restart" />
css:
#restart
{
width:160px;
}
jQuery:
/* sample how to get the values as variables
method one, static hard coded
var battleType = "Training";
var battleId = 294;
var restartCode = "nFOgYlQGjn";
method 2, php set via echo, requires page to be created by php, example uses theoretical data returned from a database stored as an associative array but could be changed for variables
var battleType = <?php echo $battle['training']; ?>;
var battleId = <?php echo $battle['id']; ?>;
var restartCode = <?php echo $battle['restart_code']; ?>;
*/
function restartBattle( varz )
{
$("#battleContent").html("Loading...<br /><br />");
$("#battle").load("http://tpkrpg.net/core/battles/battle.php", {Battle : varz.data.type, BattleId : varz.data.id, RestartCode : varz.data.code});
}
// handle the click of the button and execute functon with passed data.
$("#restart").on("click", { type : "Training", id : 294, code : "nFOgYlQGjn" }, restartBattle);
Your php code needs to check for this data being passed to it so it can return the data either some json, html, or plain text using echo.
battle.php:
$restartCode = ( ( isset( $_REQUEST['RestartCode'] ) ) ? $_REQUEST['RestartCode'] : false );
if( !$restartCode ) echo "Error : No restart code!";
That is a start, but you need to create variables that hold the data being sent to the php script or else it's hard coded to those values.
See method API
<header>
<script type="text/javascript">
function hideit()
{
var x1 = document.getElementsByTagName("ol").item(0);
var x = document.getElementsByTagName("ol");
for (var i = 0; i < x.length; i++)
x[i].style.display="none";
}
function showit()
{
var x1 = document.getElementsByTagName("ol").item(0);
var x=document.getElementsByTagName("ol");
for (var i = 0; i < x.length; i++)
x[i].style.display="";
}
</script><header>
<body>
foreach $key (keys %{$stats_data{$out}}) {
print $indexfd ("<input onclick=\"showit()\" type=\"button\" id=\"<?perl echo $key; ?>\" value=\"showit\"><br><input onclick=\"hideit()\" type=\"button\" id=\"<?perl echo $key; ?>\" value=\"hideit\"><br><b><ol id=$key>$stats_data{$out}{$key}<ol id=$key> </b><br>");
}</body>
I am creating an html document with perl. I wrote an event mouseover and mouseout to happen for every perl variable (over a loop). But looks like the event controls all the variables at the same time. How do I write the event only once but enable it to individually be applied for each item: this is what I have currently
but this html when displayed, does not let me control the event separately for each $key.
Even though the buttons do get created for each $key, clicking on one, controls the $stats_data{$out}{$key} of all.
I even tried passing the id to the show/hide script, but no luck.
Your code looks like you are trying to mix Perl with HTML in a way you would use PHP. This does not work in Perl.
I tried fixing your Perl code first. This will print to your filehandle (which I omitted), but will not not give you the working JavaScript code. I did not change that since I did not understand what you want to do. More on that later.
use strict;
use warnings;
# open of $indexfd filehandle goes here..
# print head of HTML page
print $indexfd <<HTML
<html>
<header>
<script type="text/javascript">
function hideit() {
var x1 = document.getElementsByTagName("ol").item(0);
var x = document.getElementsByTagName("ol");
for (var i = 0; i < x.length; i++)
x[i].style.display="none";
}
function showit() {
var x1 = document.getElementsByTagName("ol").item(0);
var x=document.getElementsByTagName("ol");
for (var i = 0; i < x.length; i++)
x[i].style.display="";
}
</script>
</header>
<body>
HTML
;
# If I see this correctly, %stats_data looks like this:
my %stats_data = (
'out1' => {
'key1' => 'val1',
'key2' => 'val2',
},
'out2' => {
'key1' => 'val1',
'key2' => 'val2',
},
);
my $out = 'out1'; # you need the $out from somewhere
# print buttons for each data thingy - you'll want to sort them probably
foreach my $key (sort keys %{$stats_data{$out}}) {
print $indexfd
qq~<input onclick="showit()" type="button" id="$key" value="showit"><br />~,
qq~<input onclick="hideit()" type="button" id="$key" value="hideit"><br/>~,
# Because $stats_data{$out} is a hash ref you need the -> operator here
qq~<ol id="$key"><li><b>$stats_data{$out}->{$key}</b></li></ol><br/>~;
}
print $indexfd qq~<p>more html...</p></body></html>~;
So there are a few things worth mentioning.
print $indexfd ("<input onclick=\"showit()\" type=\"button\" id=\"<?perl echo $key; ?>\" value=\"showit\"><br><input onclick=\"hideit()\" type=\"button\" id=\"<?perl echo $key; ?>\" value=\"hideit\"><br><b><ol id=$key>$stats_data{$out}{$key}<ol id=$key> </b><br>");
In this rather long line of code you used <?perl echo $key; ?> which looks like php and doesn't work. You also used <ol id=$key> which works because you used double-quotes "...". Perl substitutes the variables inside the "-delimited string for their values. You don't need that php-like stuff. In order to save yourself the effort of escaping all the double quotes in the HTML code you can use the qq-Operator. See perlop for more infos.
I explained about the %stats_data data structure in my comments.
For printing the large chunk of HTML, I used HERE docs.
Let's talk about your JavaScript now.
Even though the buttons do get created for each $key, clicking on one, controls the $stats_data{$out}{$key} of all.
This is because of the way you designed your hideit() and showit() functions. I'm not really ceratin what you want to achieve. If you look at my %stats_data you'll see that there are several keys in 'out1'. That lets the foreach-loop print a set of buttons for each of those keys. The buttons both have the same key as their id, as does the ol. That is not correct. An id-attribute has to be unique.
Furthermore, there were some basic issues in your html which I took the liberty to fix as well. If you open an <ol id="foo"> container, you need to close it like </ol>. Since <ol> is a block-level element, you shouldn't put the inline element <b> outside it, but rather inside the ol's <li> elements (which I omitted). It would be better yet to just assign css ``style="font-weight: bold" to the li items or better yet give them classes.
I'll take one last guess at what you were trying to do with the JavaScript. If you have several paragraphs of text and you want to hide them with buttons, you could do that like my untested code here.
Javascript:
function toggle(id) {
if (document.getElementById(id).style.display == 'block' ) {
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
HTML:
<div>
<input type="button" name="toggle1" id="toggle1" onclick="toggle('p1')" />
<p id="p1">Lorem ipsum dolor set ... foo a lot of text 1.</p>
<input type="button" name="toggle2" id="toggle2" onclick="toggle('p2')" />
<p id="p2">Lorem ipsum dolor set ... foo a lot of text 2.</p>
</div>
In this case, the function checks whether the paragraph is shown or not. The display-value needs to be set to 'none' or 'block', because the p-element is a block-level element.
Please try to post more specific information about the data you use with your script if you need any more help.
EDIT:
In the following code I changed the JS functions to both take an id (the key) as a parameter. They only show or hide the lists associated with this key. I changed the button's ids so they're not the same. I also added a div around each pair of buttons and list to make it clearer what belongs where.
use strict;
use warnings;
# open of $indexfd filehandle goes here..
my $indexfd;
# print head of HTML page
print $indexfd <<HTML
<html>
<header>
<script type="text/javascript">
function hideit(key) {
document.getElementById(key).style.display = "none";
}
function showit(key) {
document.getElementById(key).style.display = "";
}
</script>
</header>
<body>
HTML
;
# If I see this correctly, %stats_data looks like this:
my %stats_data = (
'out1' => {
'key1' => 'val1',
'key2' => 'val2',
},
'out2' => {
'key1' => 'val1',
'key2' => 'val2',
},
);
my $out = 'out1'; # you need the $out from somewhere
foreach my $key (sort keys %{$stats_data{$out}}) {
print $indexfd
qq~<div id="div_$key">\n~, # Add a div around the $key-elements
qq~<input onclick="showit('$key')" type="button" id="btn_show_$key" value="showit">\n~,
qq~<input onclick="hideit('$key')" type="button" id="btn_show_$key" value="hideit"><br/>\n~,
qq~<ol id="$key"><li><b>$stats_data{$out}->{$key}</b></li></ol>\n~,
qq~</div>\n~;
}
print $indexfd qq~<p>more html...</p></body></html>~;
It looks like you want one of Perl's templating modules, such as Template Toolkit. It allows you to embed Perl snippets inside larger documents then process them such that the Perl parts fill in whatever you need.
Here's an example from one of my websites. It uses wrapper files to include the top and bottom portions, and reads an XML file to get the data to fill in the middle:
[%
title = "The Perl Review"
xml = "raw/xml/tpr_issues.xml"
sidebar = 1
%]
[% PROCESS top %]
<table class="content-table">
<tr>
<td colspan class="2">
<h2>Next issue: April 15</h2>
[% PERL %]
use XML::Twig;
my $twig = XML::Twig->new;
$twig->parsefile( $stash->get( 'xml' ) );
my $root = $twig->root;
my $latest_issue = $root->first_child( 'release' );
my( $volume, $issue, $year, $season ) =
map { eval {$latest_issue->first_child( $_ )->text } }
qw( volume issue year season );
my $articles = $latest_issue->first_child( 'articles' );
print <<"TEMPLATE";
<A class="cover-link" href="/Subscribers/ThePerlReview-v${volume}i${issue}.pdf"><img
class="cover-image-medium" height="396" width="306"
src="/Images/covers/v${volume}i${issue}-cover-medium.png" /></a>
</td>
<td class="article-cell">
<h2 id="issue-header">Issue $volume.$issue, $season $year</h2>
TEMPLATE
foreach my $article ( $articles->children( ) )
{
my #children = map { $_->tag } $article->children;
my %hash =
map {
$article->first_child( $_ )->tag,
$article->first_child( $_ )->text
}
map { $_->tag } $article->children;
print qq|\t<p class="article-title"><span class="article-title">$hash{title}</span>|;
print qq| (sample)| if $hash{sample_page};
print "<br />\n";
print qq|\t\t<span class="article-author">$hash{author}</span></p>\n|;
}
[% END %]
[% PROCESS issue_note %]
</td>
</tr>
</table>
[% PROCESS footer %]
This function get a parameter and pass it to this this
$.arte({'ajax_url':'getRealTimeUpdates.php?activity_id='+id, 'on_success':updateLiveUpdates}).start();
[where this line of code feches the upadtes from server each a
specific time period as a jaxed loop]
when I call the function showLiveUpdates(id) with some parameter for example id=5, this line remember id=5 for all this function calls even different parameters !
I want each time I call the function with different id this line of code get the new id
{{ where arte is JQuery plug-in : Ajax Real Time Extension, this is its website click here}}
js code :
function showLiveUpdates(id)
{
//$.arte().stop();
$("#liveUpdates").fadeIn("slow");
$("#liveUpdates").html("");
$("#liveUpdates").append("<div><textarea rows='2' cols='49' id='txtLiveUpdates'></textarea></div>");
$("#liveUpdates").append("<div><input type='button' id='btnliveUpdatesShare' value='share' onClick='addComment("+id+","+getCookie("userId")+")'></div>");
last="";
$.arte({'ajax_url':'getRealTimeUpdates.php?activity_id='+id, 'on_success':updateLiveUpdates}).start();
}
I call it like this:
<input type='button' onClick='showLiveUpdates(<? echo $_GET["id"];?>)' />
edit
function updateLiveUpdates(data)
{
if(data!=last)
{
$("#liveUpdates").append("<div id='updates"+ii+"' style='display:none' >"+data+"</div>");
$("#updates"+ii).fadeIn();
last=data;
}
ii++;
}
getRealTimeUpdates.php
<?php
require("database.php");
$activity_id=$_GET["activity_id"];
$query = "SELECT id,comment from comments where activity_id=$activity_id order by id desc limit 0,1";
echo $query;
$result = mysql_query($query);
$row = #mysql_fetch_assoc($result);
echo $row["id"]."-".$row["comment"];
?>
How about this? Creating a function scope for the id variable:
function createData(id) {
return function () {
return {
'ajax_url':'getRealTimeUpdates.php?activity_id='+id,
'on_success':updateLiveUpdates
}
}
}
for (var id = 0; id < 5; i++) {
$.arte(createData(id)()).start();
}
EDIT 1 Just looked at the code at http://code.google.com/p/arte/source/browse/trunk/jquery-plugin-arte.js.
There is a shared _config property that gets overwritten, and the URL used is always _config['ajax_url'].
EDIT 2 I've posted a demo of this here to demonstrate your issue. So it looks like you cannot call this function multiple times, because the internal state is shared.
EDIT 3 I've updated a jsfiddle with a rough attempt at making this code work as you desire. The demo is here. The new code keeps no state and (seems to) successfully run 5 update loops before terminating them after 3 seconds.