Display label character by character using javascript - php

I am creating Hang a Man using PHP, MySQL & Javascript. Every thing is going perfect, I get a word randomly from DB show it as a label apply it a class where display = none. Now when I click on a Character that character become disable fine which i actually want but the label-character does not show.
My code is:
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
<?php
include( 'config.php' );
$question = questions(); // Get question.
$alpha = alphabats(); // Get alphabets.
?>
<script language="javascript">
function clickMe( name ){
var question = '<?php echo $question; ?>';
var questionLen = <?php echo strlen($question); ?>;
for ( var i = 0; i < questionLen; i++ ){
if ( question[i] == name ){
var link = document.getElementById( name );
link.style.display = 'none';
var label = document.getElementById( 'questionLabel' + i );
label.style.display = 'block';
}
}
}
</script>
<div>
<table align="center" style="border:solid 1px">
<tr>
<?php
for ( $i = 0; $i < 26; $i++ ) {
echo "<td><a href='#' id=$alpha[$i] name=$alpha[$i] onclick=clickMe('$alpha[$i]');>". $alpha[$i] ."</a> </td>";
}
?>
</tr>
</table>
<br/>
<table align="center" style="border:solid 1px">
<tr>
<?php
for ( $i = 0; $i < strlen($question); $i++ ) {
echo "<td class='question'><label id=questionLabel$i >". $question[$i] ."</label></td>";
}
?>
</tr>
</table>
</div>

First of all, why would it show, when you're setting its display to none?
Second, you probably want to take the hiding of the letter outside the if - if you don't, you'll be hiding the letter several times over if it appears couple of times in the question (think "banana" - if you pick "a", it will hide "a" three times) - which is not an issue, and won't hide the letter if it does not appear in the question - which probably is.
Third - Why are you using labels? You can, it's not illegal or anything, but they have a clear purpose - to mark text belonging to checkboxes and other selectable elements that don't have text of their own. It is best to use elements according to their intended meaning. As there is no HTML element dedicated to single letters in a hangman game, you're best off with span or div.
UPDATE:
Try this; I'm not sure, but reasonably convinced that this is what you want:
for ( var i = 0; i < questionLen; i++ ){
var link = document.getElementById( name );
link.style.display = 'none';
if ( question[i] == name ){
var label = document.getElementById( 'questionLabel' + i );
label.style.display = 'inline';
}
}

Have you tried label.style.display = ''; instead of 'block'?

$question seems to have been mis used...
on this lines:
for ( $i = 0; $i < strlen($question); $i++ ) {
echo "<td class='question'><label id=questionLabel$i >". $question[$i] ."</label></td>";
}
you say strlen which is the number of characters in a string. or aka string length.
and then you say "....$question[$i]...." which is a non array ...
so....
replace "strlen" with "count" and then use str_split on $questions.
so you end up with ...
$question = str_split($question);
for ( $i = 0; $i < count($question); $i++ ) {
echo "<td class='question'><label id=questionLabel$i >". $question[$i] ."</label></td>";
}
this would split each character which is what i think you are trying to do.

The problem (as Amadan pointed out) is that you're setting the display to none for the label (looks like you might have copy-pasted):
var link = document.getElementById( name );
link.style.display = 'none';
var label = document.getElementById( 'questionLabel' + i );
label.style.display = 'inline';
Also, you might consider refactoring to use a regular expression instead of looping through the string:
function clickMe(name) {
// Get the question string
var question = '<?php echo $question; ?>',
// Create a RegExp based on the name
re = new RegExp(name, "gi"),
// Get a handle to the link
link = document.getElementById(name),
// Set up our `match` variable
match;
// Set the link display to "none" outside of the loop
link.style.display = "none";
// For each match found in the question, show that label.
while(match = re.exec(question))
document.getElementById("questionLabel"+match.index)
.style.display = "inline";
}
Your function compresses down to only 7 lines of code this way, making it easier to read and a little smarter than looping through each character of the question.

Related

(PHP) How do I properly concatenate a list of arrays into a string for file_put_contents?

I've been playing around with a php input function that will build a html page for a game, something like a wiki. All is going fine and dandy but when trying to build an array into a string it's passing back some funny errors.
It's happening to every one that involves an array and I've snipped some code out that works independently to save me time, but just can't figure it out. I'm using the Linux Terminal to run the script and when I set it to echo inside the foreach loop it does it just fine, it just won't when I try building it into a HTML file.
Here is the input script:
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
$facInputRankString = "";
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
foreach ($facInputRanks as $facInputRankList) {
$facInputRankString .= $facInputRankList.PHP_EOL;
}
Then I'll build it into a multi-line echo (rather than appending every single block of code):
$facBuildPage = <<<EOT
<?php
\$facRankLimit = '$facInputRankLimit';
\$facRanks = '$facInputRankString';
include('faction2.html');
?>
EOT;
The variables with the backslashes will then be built into "$facFileName.php" and will be a set of variables inputted through this script (input2.php), which will each also include the same html page.
To top it off I'm getting really weird results... if I create 5 ranks, each as "1 2 3 4 5", I actually get "1 2 3" with two vertical linebreaks in between.
Edit: Snipped some of it, I didn't want to risk not adding enough info but it turns out I added a bit much.
For instance, the input I'm giving is:
$facInputRankLimit = 5;
$facInputRanks[1] = 1; -> $facInputRanks[5] = 5;
But it prints:
1<br><br>2<br><br>3
#Deepkak - The relative code in faction2.html is:
<div class="fpDivisions fpBox">
<span class="header">Ranks</span><br>
<?php
$facRankCount = 0;
while ($facRankCount < $facRankLimit) {
echo $facRanks[$facRankCount].'<br>';
$facRankCount++;
}
?>
</div>
I Hope this will solve the issue
<?php
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
$array = [];
foreach ($facInputRanks as $facInputRankList) {
$array[] = "'".$facInputRankList."'";
}
$facInputRankString = "[".implode(",",$array)."]";
$facBuildPage = <<<EOT
<?php
\$facRankLimit = '$facInputRankLimit';
\$facRanks = $facInputRankString;
include('faction2.html');
?>
EOT;
echo $facBuildPage;
I've created a workaround for this, incase anyone needs any help in the future. It was as simple as echoing it from the HTML page, rather than creating a loop that runs through both the PHP script and the HTML code.
PHP input code:
echo "\nHow many ranks were there (number)?:\n";
$facInputRankLimit = readline();
echo "Please read carefully and supply the ranks in descending order (HIGHEST > LOWEST):\n";
$facInputRankCount = 0;
while ($facInputRankCount < $facInputRankLimit) {
echo "Enter a rank:\n";
$facInputRanks[$facInputRankCount] = readline();
$facInputRankCount++;
}
$facInputList = implode("<br>", $facInputRanks);
PHP output code:
$facBuildPage = <<<EOT
<?php
\$facRanks = '$facInputList';
include('faction2.html');
?>
EOT;
file_put_contents("test/$facFileName.php", $facBuildPage);
HTML output code:
<div class="fpDivisions fpBox">
<span class="header">Ranks</span><br>
<?php echo $facRanks; ?>
</div>

GetElementByID Dynamic php ID to js function call

Could anybody help me with this little issue. Im trying to change the class of a page number if clicked. but im trying through a js function call using a dynamic php ID . The code below should show you what i mean, Basically the function would change the class of the selected number.
echo"
<div class='pagebuttonsdiv'>";
for ( $x =0 ; $x < $pagesnum ; $x++ ) {
$pagex=$x+1;
if ($pagex<1) {$pagex==1;}
if ($pagex>$pagesnum) {$pagex==$pagesnum;};
if ($x > $pagesnum) {$x==$pagesnum;}
echo "
<div id='{$x}' class='pagebuttons' onclick='pageclick({$x},
{$display}, {$maxresults} , {$startfrom});'>
{$pagex}</div>";
if ($x==$ifclicked) {?>
<script type="text/javascript">
document.getElementById({$x}).className =
'pagebuttonsclicked';}
</script>
<?php
};
};
echo"
</div>
";
Anybody have any idea how i should go about this, Many thanks in advance.
<div id="id[<?php echo $x; ?>]" class="pagebuttons" onclick="pageclick(<?php echo$x; ?>)">
{$pagex}</div>
Not sure why are you sending all those variables in function. you just need the id to change that.
Simple Answer -
echo"
";
for ( $x =0 ; $x < $pagesnum ; $x++ ) {
$pagex=$x+1;
if ($pagex<1) {$pagex==1;}
if ($pagex>$pagesnum) {$pagex==$pagesnum;};
if ($x > $pagesnum) {$x==$pagesnum;}
echo "
<div id='{$x}' class='pagebuttons' onclick='pageclick({$x},{$display}, {$maxresults} , {$startfrom});'>
{$pagex}</div>";
if ($x==$ifclicked) { echo " <script> document.getElementById({$x}).className='pagebuttonsclicked' </script> ";};
};
echo"
</div>
<br>
";
call the function from php to change class. = onlclicking the number, it changes its class to change whatever you wish it to change according to the new css class... I changed the border surround color...

Generating Javascript variables using php

I was trying to generate a Javascript varialbe using php. I am getting the desired result on the source page but it looks like that result is not being processed into the array. Is there any way of doing it using javascript? Here, I'm generating URLs for images that need to be displayed on my website carousel and though a for loop would save me the time of entering every url. The images are also number serially. Since I'm not well versed in javascript can you suggest me a javascript alternative?
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
You can do it using javascript only. No reason for using PHP here.
var leftrightslide = new Array()
var finalslide = ''; // this line is not really relevant to the question
for (var i = 0; i < 34; i++){
var j = i + 1;
leftrightslide[i] = '<img src="../images/'+ j +'.jpg" border="0">';
}
echo "leftrightslide[".$i."]='<img src=\"../images/".$j.".jpg\" border=0>';";
Here's a snippet of code that I use to move data from PHP To JS
if (isset($javascriptData)) {
echo "<script>";
foreach(array_keys($javascriptData) as $jsData) {
echo "var " . $jsData . " = " . json_encode($javascriptData[$jsData]) . ";\n";
}
echo "</script>";
}
I pass in $javascriptData to my view which is an array with the structure array('JS_VAR_NAME' => 'JS_VALUE')
You can then use those variables in any scripts you've added below that
Since your example code contains no script tags, or other HTML elements for that matter, one might assume that this PHP snippet is intended to generate some JavaScript source "file" external to the page in which it is being used.
If that is the case, consider that the following additional line may just fix it:
<?php header( 'Content-Type: text/javascript' ); ?>
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>

Get dynamically given div id's from document

I'm not a developer but I've been dabbling around with this for a while. Hope you can help
I have several div's with ID:s that are given to them dynamically through php. I have a function that is called through a checkbox which hides and shows the divs. What I want to do now is to get the div ids from the document and put them into the function.
I've kind of copied codes from different forums and it works if I'm hard coding the div names. Not sure what I'm doing now though, any help would be appreciated.
Here's what I have
Assigns id's to the divs:
$a .= "<div id='$go[media_caption]" . $i . "'>";
The function:
var editorial = [id^='editorial']);
function visiblox(arrDiv, hs) {
var disp = (hs) ? 'none' : 'block';
for(var x = 0; x < arrDiv.length; x++) {
document.getElementById(arrDiv[x]).style.display = disp;
}
}
function chk(what, item) {
if(item) {
visiblox(what, false);
} else {
visiblox(what, true);
}
}
Calls the function:
<input type='checkbox' onclick='chk(editorial, this.checked);' checked> Editorial</p>
Can you have your PHP output an array for your Javascript to use? As PHP outputs the IDs, it would also add them to a string that is in the syntax of a Javascript array. Something like this:
$a .= "<div id='$go[media_caption]" . $i . "'>";
$jsIDs .= "'$go[media_caption]',";
Then at the end of the file, just before you the PHP file closes the </body> and </html> tags, output the array as a script:
$jsIDs = substr($jsIDs, 0, strlen($jdIDs)-1); // strip off the last comma
$jsIDs = "<script type='text/javascript'>var idArr = [" . $jsIDs . "];</script>";
echo($jsIDs);
Then inside the javascript, you don't need to look up the IDs in the DOM. You can just use the array (in my example, I called it idArr).
UPDATE: Martin says the IDs output by PHP sometimes start with "editorial", some start with something else. To collect only the ones that start with "editorial", change the line above that starts with $jsIDs .= to these two lines:
if ( substr($go[media_caption], 9) == "editorial" )
$jsIDs .= "'$go[media_caption]',";
That should do the trick.

need to loop through a PHP array in JavaScript

For example I have a PHP array, such as this one
<?php $s= array('a','b','c','d','e','f') ; ?>
And I need to loop through it in JavaScript, any ideas how do I do that?
for ( i=0 ; i < <?php echo sizeof($s) ?> ; i++) {
document.write('<?php echo $s [somehow need to get the 'i' value into here] ?>');
}
Any suggestions? Thanks!
Before your ehco/print or else your php array we make sure it's in JavaScript syntax.
<?php
$s=array('a','b','c','d','e','f');
$s_to_json=json_encode((array)$s);
?>
<script type="text/javascript">
var fromPHP=<? echo $s_to_json ?>;
for (i=0; i<fromPHP.length; i++) {
yourValue=fromPHP[i];
}
</script>
<?php
$s= array('a','b','c','d','e','f') ;
?>
<?php foreach($s as $a){ ?>
document.write('<?=$a?>');
<?php } ?>
Not tested but thats one way.
Javascript and PHP cannot be combined. They are two completely different programs that communicate only vaguely. The PHP runs on the server computer and generates the HTML. The javascript runs on the client computer in the webbrowser and acts on that HTML. If you need to move information from PHP into Javscript somehow, then you have to store it in the HTML and have the Javascript access it through that HTML. If you need to do the reverse, move information from Javascript to PHP, have the Javascript call a PHP page with a query string.
One way to place the information in your array somewhere where Javascript can get to it, would be to echo it into a hidden div. Either in a series of ided spans or just a comma separated list. Then you can pull it out of the DOM.
For example:
<div style="display: none;" id="myArray">
<?php
echo '<span id="myArray.count">'.sizeof($s).'</span>';
for ($i = 0; $i < sizeof($s); $i++) {
echo '<span id="myArray.'.$i.'">'.$s[$i].'</span>';
}
?>
</div>
Then in the Javascript you can access the array in the DOM:
var myArray = new Array();
for(i = 0; i < document.getElementById('myArray.count').innerHTML; i++) {
document.write(document.getElementById('myArray.'+i).innerHTML);
}
Disclaimer: untested code, and I don't have the time to perfect it right now. If someone else wants to comment or edit to fix any errors feel free :)
Yes.... echo out your PHP array as a JavaScript array first, and then loop over that. Don't try looping over your PHP array; you can't.
<?php $product = array('1'=>'acids','2'=>'chemical','3'=>'microbilogy'); ?>
<script>
<select name="product_id" class="form-control">
<?php foreach ($product as $key => $value)
{ echo" <option value=$value[product_id]> $value['product_name']
</option>"; } ?>
</select>
</script>
if this is helpfull please give a thumbs up
Actually you can do it, if you reverse the priority from JavaScript being the base, to PHP being the loop base.
<?php
$s= array('a','b','c','d','e','f') ;
for ( $i=0 ; $i < sizeof($s); i++)
{
?>
<script type="text/javascript">
document.write('<?php echo $s[$i]?>');
</script>
<?php
}

Categories