Change background on div with Javascript - php

This is my a management exam that I'm trying to make a modification. The exam shows questions one by one hiding the other
When I press on one of the answers if the answer is correct, right before going to the next question the background
of the pressed question goes green if it was the correct answer, red if it was the wrong answer.
What I want: When the user presses the wrong answer I want the system not only to show a red background for the pressed button but
also make the background of the correct answer green. Showing this way to the user what was the correct answer. If I missed code please let me know.
PHP
$orderbyrand = "SELECT * FROM management
ORDER BY rand(), `answer` ASC LIMIT 2";
$rend_result=mysql_query($orderbyrand);
$k=1;
while($row_rand=mysql_fetch_array($rend_result)){
$answerarry[$k]= $row_rand['answer'];
$k++;}
$answerarry['0'] = $answerarry_shuffle['0'];
$answerarry['1'];
$answerarry['2'];
shuffle($answerarry);
if($answerarry_shuffle['0']==$answerarry[0])
{ $correcr_answer[0]=1; } else { $correcr_answer[0]=0; }
if($answerarry_shuffle['0']==$answerarry[1])
{ $correcr_answer[1]=1; } else { $correcr_answer[1]=0; }
if($answerarry_shuffle['0']==$answerarry[2])
{ $correcr_answer[2]=1; } else { $correcr_answer[2]=0; }
Javascript
function change_question(quest_num,optionvalue,ans_div_num){
var hidediv = 'question_'+optionvalue;
var add_optionvalue = (Number(optionvalue)+Number(1));
var showdiv = 'question_'+add_optionvalue;
var noofques = document.getElementById('noofques').value;
var totalno = (Number(noofques)+Number(1));
var totalcount = document.getElementById('noofques').value=totalno;
if(quest_num==1){
var correct_answer = document.getElementById('optvalue').value;
var optinoresult_add = (Number(correct_answer)+Number(1));
var addoptvalue = document.getElementById('optvalue').value=optinoresult_add;
document.getElementById('answerdiv_'+ans_div_num+'_'+optionvalue).style.background='#bbd387';
} else {
var correct_answer = document.getElementById('optvalue').value;
var optinoresult_add = (Number(correct_answer)+Number(0));
var addoptvalue = document.getElementById('optvalue').value=optinoresult_add;
if(ans_div_num!=0){
document.getElementById('answerdiv_'+ans_div_num+'_'+optionvalue).style.background='#dd5f5b'; }
}
}
HTML
<div class="row-fluid answer">
<div id="answerdiv_1_<?php echo $i; ?>" onClick="return change_question('<?php echo $correcr_answer[0]; ?>','<?php echo $i; ?>','1');" class="span12 show_cursor"><p><?php echo substr($answerarry[0],0,300);?></p></div>
</div>
<div class="row-fluid answer">
<div id="answerdiv_2_<?php echo $i; ?>" onClick="return change_question('<?php echo $correcr_answer[1]; ?>','<?php echo $i; ?>','2');" class="span12 show_cursor"><p><?php echo substr($answerarry[1],0,300);?></p> </div>
</div>
<div class="row-fluid answer">
<div id="answerdiv_3_<?php echo $i; ?>" onClick="return change_question('<?php echo $correcr_answer[2]; ?>','<?php echo $i; ?>','3');" class="span12 show_cursor"><p><?php echo substr($answerarry[2],0,300);?></p> </div>
</div>

Related

Can't retrieve numeric input and assign it to a variable

I'm tring to retrieve the numeric input and store it in the variabe q but I can't seem to access it using the method post this way.
<?php
$sql = "SELECT * FROM produit";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
?>
<div class="prod<?php echo $row['ID_produit']?>">
<img src="images/<?php echo $row['image']?>" alt="image">
<h3><?php echo $row['nom_produit']?></h3>
<h3>Prix:<?php echo $row['prix']?>€</h6>
<form action="" method="post">
<label name="qte">QTE:</label>
<input type="number" name="qte"><br><br>
<a href="panier.php?action=ajout&
l=<?php echo $row['nom_produit']?>&
q=<?php $_POST['qte']?>&
p=<?php echo $row['prix']?>"
onclick="window.open(this.href, '', 'toolbar=no, location=no, directories=no, status=yes,
scrollbars=yes, resizable=yes, copyhistory=no, width=600, height=350'); return false;">
GOGOGO </a>
</form>
</div>
<?php
}
?>
</div>
I also tried with
<?php
if (isset($_POST['submit'])) {
$example = $_POST['qte'];
echo $example;
}
?>
There's a couple issues with this code. You were trying to reference qte in each loop through a $_POST variable, when what you really wanted was to just grab the input from the user. In an effort to clean up the code a little and make things more readable, I changed that big <a href... tag to trigger a function that will grab the qte value, form the URL and open the window. Note that I pass into the function the productID and prix values. I put them in quotes just in case they're blank. I also added an ID to your qte input element so we can get the value. Take a look and let me know if you need clarification
<?php
$sql = "SELECT * FROM produit";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
?>
<div class="prod<?php echo $row['ID_produit']?>">
<img src="images/<?php echo $row['image']?>" alt="image">
<h3><?php echo $row['nom_produit']?></h3>
<h3>Prix:<?php echo $row['prix']?>€</h6>
<form action="" method="post" onsubmit="return false;">
<label for="qte">QTE:</label>
<input type="number" name="qte" id="qte_<?php echo $row['ID_produit']?>"><br><br>
<a href='javascript:void(0)'
onclick='gogoLink("<?php echo $row['ID_produit']?>", "<?php echo $row['prix']?>")'>
GOGOGO </a>
</form>
</div>
<?php
}
?>
// then outside the loop is the function
<script>
function gogoLink(id, prix) {
let url ="panier.php?action=ajout"
url += "&l=" + id
url += "&q=" + document.getElementById("qte_"+id).value;
url += "&p=" + prix;
window.open(url, '', 'toolbar=no, location=no, directories=no, status=yes,
scrollbars=yes, resizable=yes, copyhistory=no, width=600, height=350');
}
</script>

assign value to php variable using jquery [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
i am working on website with buttons each button fire up a bootstrap modal contain data from mysql database i pass a variable from the jquery that fire up the model into a mysql query inside the modal the problam is the php variable cannot get the data send it from the jquery any hints please ?!
i am passing data through jquery post to ajax.php file
the modal code
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<span id="codeElem"></span>
<?php
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode ");// WHERE Code IN ('".$codeArrayStr."')
?>
<?php
$i=0;
$row3 = mysqli_fetch_array($resultHead);
?>
<h4 class="modal-title"><?=$row3['CoopName'];?></h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php
$result = mysqli_query($con,"SELECT DISTINCT * FROM reports WHERE host = $getCode GROUP BY host DESC");
?>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<div class="card card-figure has-hoverable">
<figure class="figure">
<img class="img-fluid" src="http://www.iroof.tv/screenshots/<?=$row['screenshot'];?>" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"><?=$row['host'];?></h6>
<p class="text-muted mb-0"> <?=$row['timestamp'];?> </p>
<?php
// Assign JSON encoded string to a PHP variable
$statusJson = $row['status'];
// Decode JSON data into PHP associative array format
$arr = json_decode($statusJson, true);
// Call the function and print all the values
// $result2 = printValues($arr);
echo "<hr>";
echo "<h3> Player </h3>";
// Print a single value
echo "Status: ".$arr["player"]["status"] . "<br>";
echo $arr["player"]["filename"] . "<br>";
echo "<hr>";
echo "<h3> Graphics </h3>";
echo "Display: ".$arr["video"]["display"] . "<br>";
echo "Resolution: ".$arr["video"]["resolution"] . "<br>";
echo "Colors: ".$arr["video"]["colors"] . "<br>";
echo "<hr>";
echo "<h3> System </h3>";
echo "CPU: ".$arr["cpu"] . "<br>";
echo "Ram: ".$arr["ram"] . "<br>";
//echo "Temprature: ".$arr["temperature"] . "<br>";
echo "Fan: ".$arr["fan"] . "<br>";
?>
</figcaption>
</figure>
</div>
<?php $i++;
}
?>
</div>
<!-- Modal footer
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>-->
</div>
the jquery script
<script>
$(document).ready(
function() {
setInterval(function() {
$('.card');
}, 5000); //Delay here = 5 seconds
var gen;
$(".btn").click(function(){
gen = $(this).attr("data-code");
//$.post("ajax.php", {"code": gen},function(data){console.log(data);});
});
$('#myModal').on('shown.bs.modal', function () {
$.post("ajax.php", {"code": gen},function(data){console.log(data);});
//var phpCode = "<? $getCode = $_POST["code"]; ?>";
//$('#codeElem').html(phpCode);
})
});
</script>
ajax.php file
<?php
if(isset($_POST['code']) && isset($_POST['code'])){
//$_SESSION["code"] = $_POST["code"];
$_SESSION['header'] = $_POST['code'];
$getCode = $_POST["code"];
echo $_SESSION['header'];
}
?>
i expect the variable $getCode to get the code from jquery to complete the mysql query inside the modal :
$resultHead = mysqli_query($con2,"SELECT * FROM coops WHERE Code = $getCode");
I dont think its possible to post variables to a modal, I didnt see example like that when I was searching for popup modal login.
guess you need an action page to forvard infos to modal.
This is the solution to post variables:
Change variables to your needs..
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var post_id =$("#mail-id").val();
var name =$("#mail-name").val();
var email =$("#mail-email").val();
var message =$("#mail-message").val();
var type =$("#mail-type").val();
var captcha_code =$("#captcha_code").val();
var submit =$("#mail-submit").val();
$(".form-message").load("heads/comment.php",{
post_id: post_id,
name: name,
email: email,
message: message,
type: type,
captcha_code: captcha_code,
submit: submit
});
});
});
you probably need some thing like this to show variables in popup
<p class="form-message"></p>
Or you can check Bootstrap modal table :
Here

Change input value when i press <a> Attribute

Ok guys already search for it but no results at all, and cant figured it out how to do this, so my problem is:
I have this form:
<form method="POST" action="search.php" name="form" id="form">
<input type="text" name="search" id="search" placeholder="Introduza a sua Localização">
<input type="submit" name="Submit" value="Pesquisar">
</form>
And what i would like to is when i press this:
<a onClick="">City</a>
The input value change to what i want in this case "City" and then automatically submit the form.
I already made a research about this and theres nothing i could take, any help would be appreciated.
Cumps.
Guys thanks to your help now its working but someone tell me please what the problem in this code:
<?php if (mysql_num_rows($tournaments) !=0){
do { ?>
<div id="mainContainer">
<div id="leftContainer"><img src="images/tournaments/<?php echo $row_tournaments['logo']; ?>.png"></div>
<div id="rightContainer">
<div id="rightContent">
<p><?php echo $row_tournaments['description']; ?></p>
<div id="galleryButton"><p>Entrar no torneio</p></div>
</div>
<div id="rightDetails">
<i class="fa fa-gamepad"></i> <?php echo $row_tournaments['game']; ?><br>
<i class="fa fa-calendar-o"></i> <?php echo $row_tournaments['date']; ?><br>
<i class="fa fa-pencil-square-o"></i> Sem comentários<br>
<script type="text/javascript">
function giveThatInputAValue(){
var elem = document.getElementById("search");
elem.value = "<?php echo $row_tournaments['city']; ?>";
/*document.forms["form"].submit();
*/}
</script>
<i class="fa fa-map-marker"></i> <a onClick="giveThatInputAValue()"><?php echo $row_tournaments['city']; ?></a><br>
<img src="images/<?php echo $row_tournaments['online']; ?>.png"> <?php echo $row_tournaments['online']; ?>
</div>
</div>
</div>
<?php } while ($row_tournaments = mysql_fetch_assoc($tournaments));
} else {
?>
<div id="noresults"><p>Sem torneios</p></div>
<?php
}
?>
Everything is looped fine but that part:
<script type="text/javascript">
function giveThatInputAValue(){
var elem = document.getElementById("search");
elem.value = "<?php echo $row_tournaments['city']; ?>";
/*document.forms["form"].submit();
*/}
</script>
Its not looping it only shows the first record why is it?
Any help would be appreciated.
in your js file you can check if the value of the textbox is equal to the cityname you want. if it is then submit the form. Attach the function to your a tag
function SubmitRightCity(){
if(document.getElementById('search').value == "citynamehere"){
document.forms["form"].submit();
}
}
in html
<a onClick="submitRightCity()">City</a>
In the case where you want your a tag to give the input a value, you attach a function to your tag, once the link is clicked, then the function will give your input a value.
<a onClick="giveThatInputAValue()"> City</a>
in javascript file you will have
<script>
function giveThatInputAValue(){
var elem = document.getElementById("search");
elem.value = "My city value";
//if you want to submit the form right after, you add the line below
document.forms["form"].submit();
}
</script>

Fancybox only works after second click

So I have a table where each cell is a name of a game and when you click it it needs to show in a fancybox the results of the user which clicked the cell (I use table Indexes to get the GameID and the Session variable to get userID) which will be used to load the results from a second PHP page.
If I click on a cell for the first time the fancybox will not display anything and after I close fancybox and click on any cell again it works fine. Am I doing something wrong?
This is the whole javascript:
$(".jogos").fancybox({
'hideOnContentClick': true,
'onComplete':function(element)
{
var gameIdx = $(element).index();
var cateIdx = $(element).parent().parent().index();
var gameIdxPHP;
var catIdxPHP;
var gameID;
var userId = '<?php echo $_SESSION['userID']; ?>'
<?php
for ($i=1; $i<= count($categoryArray);$i++)
{
for ($j=1; $j<=count($categoryArray[$i-1]->gamelist);$j++)
{
?>
catIdxPHP = '<?php echo $i ?>' -1;
gameIdxPHP = '<?php echo $j ?>' -1;
if (catIdxPHP == cateIdx && gameIdxPHP == gameIdx)
{
gameID = '<?php echo $categoryArray[$i-1]->gamelist[$j-1]->GameID; ?>';
$("#graphic").load("backoffice/resUserNivel2short.php", {userId:userId,gameID:gameID}, function(){ });
}
<?php
}
}
?>
}
});
HTML
<div style="display:none">
<div id="data">
<div id="graphic">
</div>
</div>
</div>
Sample code of the link
<a href="#data" class="jogos" id="cat<?php echo $i; ?>jogo<?php echo $j; ?>" >
You have display:none on the parent of your fancybox therefor the grafic isnt displayed.
The Grafic element isn't inside the dom yet if you use display:none initially. Try to use clip: rect instead as a class and add/remove that class using the fancybox callbacks.
Try this code:
$('.jogos').fancybox({
'onStart': function() {
$("#data").removeClass('hidden');
},
'onClosed': function() {
$("#data").addClass('hidden');
}
});
CSS:
.hidden {
clip: rect(1px 1px 1px 1px);
position: absolute;
)}
HTML:
<div>
<div id="data" class="hidden">
<div id="graphic">
</div>
</div>
</div>

showing or hiding div with id generated using php and javascript

I am trying to hide or show the div based on the div id from the php function. I am not able to make it work, please help me.
Javascript:
<script>
showOrHide(id) {
var elem=getElementById(id);
if(elem.style.visibility="hidden")
elem.style.visibility="visible";
else
elem.style.visibility="hidden";
}
</script>
PHP Script:
<?php
function display_link($link_id,$upvote_array,$downvote_array,$divid) {
?>
More links
<div id="<?php echo $divid ?>" style="visibility:hidden;">
</div>
<?php } ?>
Here's a cleaned-up version of your function.
function showOrHide(id) {
var elem = document.getElementById(id);
elem.style.visibility = (elem.style.visibility === 'hidden')? 'visible' : 'hidden';
}
<script>
function showOrHide(id){
var elem = getElementById(id);
if(elem.style.visibility=="hidden"){
elem.style.visibility="visible";
} else {
elem.style.visibility="hidden";
}
}
</script>
<?php
function display_link($link_id,$upvote_array,$downvote_array,$divid)
{
?>
More links
<div id="<?php echo $divid ?>" style="visibility:hidden;">
</div>
1 - visibility == 'hidden'
2 - missing ; after visibility="visible" and ="hidden"
3 - href="javascript:showOrHide('')" - missing '' inside your javascript function
Try this
<script>
function showOrHide(id){
var elem = document.getElementById(id);
elem.style.visibility = (elem.style.visibility === 'hidden')? 'visible' : 'hidden';
}
</script>
<?php
function display_link($link_id,$upvote_array,$downvote_array,$divid)
{
?>
More links
<div id="<?php echo $divid ?>" style="display:hidden;">
</div>
<?php
}
?>

Categories