I have 2 sets of checkboxes in my webpage, and I have a small script that is checking the boxes and not the others when I click one, which is what I want.
Unfortunately, it only checks one set of boxes, and leaves the other set unchecked.
Although on reloading my page both sets are checked, this is due to my post variable. I will show you the code.
Can anybody see where I could update it to check both boxes when clicking one box?
<div id='checkbox-container'>
<input type="checkbox" id="small" name="displaytypethumbs" value="minlist" <?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="small" class="smalllistings">Thumbs</label>
</input>
<input type="checkbox" id="large" name="displaytypegallery" value="maxlist" <?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="large" class="largelistings" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings" name="displaytypefull" value="fulllist" <?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?>onclick="chbx(this)">
<label for="fulllistings" class="fulllistings" >Full Listing</label>
</input>
</div>
<div id='checkbox-container2'>
<input type="checkbox" id="small2" name="displaytypethumbs" value="minlist" class="smalllistingsbox"
<?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="small2" class="smalllistingsmain" >Thumbs</label>
</input>
<input type="checkbox" id="large2" name="displaytypegallery" value="maxlist" class="largelistingsbox"
<?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="large2" class="largelistingsmain" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings2" name="displaytypefull" value="fulllist"
<?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this)">
<label for="fulllistings2" class="fulllistingsmain" >Full Listings</label>
</input>
</div>
</form>
<script>
function chbx(obj) {
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('small').checked = false;
document.getElementById('large').checked = false;
document.getElementById('fulllistings').checked = false;
document.getElementById('small2').checked = false;
document.getElementById('large2').checked = false;
document.getElementById('fulllistings2').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
Thanks guys, i should of thought about it before posting really, i chose the simple method . Very wet, But still did the job... Thanks for your help guys.
<div id='checkbox-container'>
<input type="checkbox" id="small" name="displaytypethumbs" value="minlist" <?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check1();">
<label for="small" class="smalllistings">Thumbs</label>
</input>
<input type="checkbox" id="large" name="displaytypegallery" value="maxlist" <?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check2();">
<label for="large" class="largelistings" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings" name="displaytypefull" value="fulllist" <?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?>onclick="chbx(this); check3();">
<label for="fulllistings" class="fulllistings" >Full Listing</label>
</input>
</div>
<div id='checkbox-container'>
<input type="checkbox" id="small2" name="displaytypethumbs" value="minlist" class="smalllistingsbox"
<?php if (!empty($_POST['displaytypethumbs'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check4();">
<label for="small2" class="smalllistingsmain" >Thumbs</label>
</input>
<input type="checkbox" id="large2" name="displaytypegallery" value="maxlist" class="largelistingsbox"
<?php if (!empty($_POST['displaytypegallery'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check5();">
<label for="large2" class="largelistingsmain" >Gallery</label>
</input>
<input type="checkbox" id="fulllistings2" name="displaytypefull" value="fulllist"
<?php if (!empty($_POST['displaytypefull'])): ?> checked="checked"<?php endif; ?> onclick="chbx(this); check6();">
<label for="fulllistings2" class="fulllistingsmain" >Full Listings</label>
</input>
</div>
</form>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('small').checked = false;
document.getElementById('large').checked = false;
document.getElementById('fulllistings').checked = false;
document.getElementById('small2').checked = false;
document.getElementById('large2').checked = false;
document.getElementById('fulllistings2').checked = false;
document.getElementById(that.id).checked = true;
}
}
function check1(){document.getElementById('small2').checked = true; }
function check2(){document.getElementById('large2').checked = true; }
function check3(){document.getElementById('fulllistings2').checked = true; }
function check4(){document.getElementById('small').checked = true; }
function check5(){document.getElementById('large').checked = true; }
function check6(){document.getElementById('fulllistings').checked = true; }
</script>
/
Related
I wanted to create a selection pages (by using checkboxes) where at the end it will show the result from the selection of all the checkboxes. There are about 5 different categories of checkboxes in my first page (only contains HTML) which is for emotions, time, movements, tools & personalization.
First page: index.php
<div>
<form action="process.php" method="post">
<label>Select your emotions :</label>
<input type="checkbox" name="emotions[]" value="Sadness"> Sadness
<input type="checkbox" name="emotions[]" value="Anxiety"> Anxiety
<input type="checkbox" name="emotions[]" value="Anger"> Anger
<input type="checkbox" name="emotions[]" value="Disgust"> Disgust
<input type="checkbox" name="emotions[]" value="Fear"> Fear
<input type="checkbox" name="emotions[]" value="Surprised"> Surprised
<br>
<label>Select your time to commit :</label>
<input type="checkbox" name="time[]" value="1"> Less than 1 minute
<input type="checkbox" name="time[]" value="1-3"> 1-3 minutes
<input type="checkbox" name="time[]" value="3-5"> 3-5 minutes
<input type="checkbox" name="time[]" value="5-10"> 5-10 minutes
<input type="checkbox" name="time[]" value="10-15"> 10-15 minutes
<input type="checkbox" name="time[]" value="15-30"> 15-30 minutes
<br>
<label>Select how you want to move :</label>
<input type="checkbox" name="movement[]" value="Lying Down"> Lying Down
<input type="checkbox" name="movement[]" value="Sitting"> Sitting
<input type="checkbox" name="movement[]" value="Standing"> Standing
<input type="checkbox" name="movement[]" value="Stretching"> Stretching
<input type="checkbox" name="movement[]" value="Walking"> Walking
<input type="checkbox" name="movement[]" value="Work-out"> Work-out
<br>
<label>Tools around me :</label>
<input type="checkbox" name="tools[]" value="Me"> Me
<input type="checkbox" name="tools[]" value="Pen & Paper"> Pen & Paper
<input type="checkbox" name="tools[]" value="Bottle"> Bottle
<input type="checkbox" name="tools[]" value="Color Pencils"> Color Pencils
<input type="checkbox" name="tools[]" value="Drinks"> Drinks
<input type="checkbox" name="tools[]" value="Snacks"> Snacks
<label>Personalization :</label>
<input type="checkbox" name="personalization[]" value="Favorites"> Favorites
<input type="checkbox" name="personalization[]" value="New"> New
<input type="checkbox" name="personalization[]" value="Completed"> Completed
<input type="checkbox" name="personalization[]" value="Islamic"> Islamic
</div>
<div>
<button type="submit">Submit</button>
</div>
2nd page: process.php
<?php
$emotions = (isset($_POST['emotions'])) ? $_POST['emotions'] : array(); ?>
<p><strong>Emotions :</strong>
<?php
if (count($emotions) > 0) {
foreach ($emotions as $emotions) {
echo $emotions . ' ';
}
} else {
echo "No emotions has been selected";
}
?>
</p>
<?
$time = (isset($_POST['time'])) ? $_POST['time'] : array(); ?>
<p><strong>Time :</strong>
<?php
if (count($time) > 0) {
foreach ($time as $time) {
echo $time . ' ';
}
} else {
echo "No time has been selected";
}
?>
</p>
<?
$movement = (isset($_POST['movement'])) ? $_POST['movement'] : array(); ?>
<p><strong>Movement :</strong>
<?php
if (count($movement) > 0) {
foreach ($movement as $movement) {
echo $movement . ' ';
}
} else {
echo "No movements has been selected";
}
?>
</p>
<?
$tools = (isset($_POST['tools'])) ? $_POST['tools'] : array(); ?>
<p><strong>Tools :</strong>
<?php
if (count($tools) > 0) {
foreach ($tools as $tools) {
echo $tools . ' ';
}
} else {
echo "No tools has been selected";
}
?>
</p>
<?
$personalization = (isset($_POST['personalization'])) ? $_POST['personalization'] : array(); ?>
<p><strong>Personalization :</strong>
<?php
if (count($personalization) > 0) {
foreach ($personalization as $personalization) {
echo $personalization . ' ';
}
} else {
echo "No personalization has been selected";
}
?>
</p>
Check if you have entered proper path in action attribute of form tag to reach the "process.php" file
Review your foreach.
What you do is :
$array = [1, 2, 3];
foreach($array as $array){
// $array is no more an array, but have the first value of the init array : 1
}
it's like if you do : $array = $array[0]
you have to do something like :
$array = [1, 2, 3];
foreach($array as $ar){
...
// code for $ar
...
}
I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.
Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>
hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>
add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>
I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced
i used the code below to create a quiz and it works well and nextbutton works perfect if the Que_id is for instance (1,2,3,4) but this will not work properlly (1,3,4) . as you can see, question id 2 has been deleted and this will result in many nextbutton instead of just normal One nextbutton.
But my problem is this, if i delete a row from the json file for example
"que_id":"1","que_desc":"The Best Coders Network","ans1":"Stackoverflow","ans2":"none","ans3":"none"}
or
{"que_id":"3","que_desc":"Stackoverflow was founded in what year","ans1":"2008","ans2":"none","ans3":"none"}
, the quiz will no longer be showing the quiz questions one by one via next button rather it will display all the nextbutton at once. If i then try to click any of the scattered next button, it will post the result.
on php end, It seems the quiz is submitted based on the que_id which is then passed to javascript incremented functions.
Can someone help me with this. I want the nextbutton to works perfect and display the quiz question one by one no matter which rows was deleted in json file.
below is the code
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<script src="jquery.min.js"></script>
</head>
<body>
<?php
$data = '[{"que_id":"1","que_desc":"The Best Coders Network","ans1":"Stackoverflow","ans2":"none","ans3":"none"},
{"que_id":"2","que_desc":"Who Founded Stackoverflow","ans1":"Jeff Atwood and Joel Spolsky.","ans2":"none","ans3":"none"},
{"que_id":"3","que_desc":"Stackoverflow was founded in what year","ans1":"2008","ans2":"none","ans3":"none"},
{"que_id":"4","que_desc":"Stack Overflow is a privately held by a website","ans1":"Stack Exchange Network","ans2":"none","ans3":"none"}]';
$characters = json_decode($data);
//echo $characters->que_desc;
//echo print_r($characters);
//var_dump($characters);
?>
<form method='post' id='quiz_form'>
<?php
foreach ($characters as $value) {
$result['que_id']= $value->que_id ;
$result['que_desc']= $value->que_desc ;
$result['ans1']= $value->ans1 ;
$result['ans2']= $value->ans2 ;
$result['ans3']= $value->ans3 ;
?>
<div id="question_<?php echo $result['que_id'];?>" class='questions'>
<h2 id="question_<?php echo $result['que_id'];?>">
<?php echo $result['que_id'].".".$result['que_desc'];?>
</h2>
<div class='align'>
<label class="containerg">
<input type="radio" value="1" id='radio1_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans1_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans1'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="2" id='radio2_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans2_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans2'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="3" id='radio3_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans3_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans3'];?></label>
<span class="checkmark"></span>
</label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result[' que_id '];?>' name='<?php echo $result[' que_id '];?>'>
</div>
<br/>
<input type="button" id='next<?php echo $result[' que_id '];?>' value='Next!' name='question' />
</div>
<?php }?>
</form>
<div id='result'>
Result will Appear Here test
<br/>
</div>
<script>
$(document).ready(function() {
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i) {
hider = i + 2;
if (i == 0) {
$("#question_" + hider).hide();
createNextButton(i);
} else if (count == i + 1) {
var step = i + 1;
$("#next" + step).on('click', function() {
submit();
});
} else {
$("#question_" + hider).hide();
createNextButton(i);
}
});
function submit() {
// post to ajax
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i) {
var step = i + 1;
var step1 = i + 2;
$('#next' + step).on('click', function() {
$("#question_" + step).hide();
$("#question_" + step1).show();
});
}
});
</script>
</body>
</html>
The problem with your code the that you are creating element using the data with given id values and in your jQuery event bind logic you assume that these values are always in continuation.
If you remove any row from the data the continuation and the logc both will be broken.
You need to update your logic based on the class selector.
You can update your code logic like this.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<?php
$data = '[{"que_id":"1","que_desc":"The Best Coders Network","ans1":"Stackoverflow","ans2":"none","ans3":"none"},
{"que_id":"2","que_desc":"Who Founded Stackoverflow","ans1":"Jeff Atwood and Joel Spolsky.","ans2":"none","ans3":"none"},
{"que_id":"3","que_desc":"Stackoverflow was founded in what year","ans1":"2008","ans2":"none","ans3":"none"},
{"que_id":"4","que_desc":"Stack Overflow is a privately held by a website","ans1":"Stack Exchange Network","ans2":"none","ans3":"none"}]';
$characters = json_decode($data);
//echo $characters->que_desc;
//echo print_r($characters);
//var_dump($characters);
?>
<form method='post' id='quiz_form'>
<?php
foreach ($characters as $value) {
$result['que_id']= $value->que_id ;
$result['que_desc']= $value->que_desc ;
$result['ans1']= $value->ans1 ;
$result['ans2']= $value->ans2 ;
$result['ans3']= $value->ans3 ;
?>
<div id="question_<?php echo $result['que_id'];?>" class='questions'>
<h2 id="question_<?php echo $result['que_id'];?>"><?php echo $result['que_id'].".".$result['que_desc'];?></h2>
<div class='align'>
<label class="containerg">
<input type="radio" value="1" id='radio1_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans1_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans1'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="2" id='radio2_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans2_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans2'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="3" id='radio3_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans3_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans3'];?></label>
<span class="checkmark"></span>
</label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
</div>
<br/>
<input type="button" class="next" id='next<?php echo $result['que_id'];?>' value='Next!' name='question'/>
</div>
<?php }?>
</form>
<div id='result'>
Result will Appear Here test
<br/>
</div>
<script>
$(document).ready(function(){
var steps = $('form').find(".questions");
$(".questions").hide();
var count = steps.length;
steps.each(function(i){
if (i == 0) {
createNextButton(i);
$($(".questions").get(i)).show();
}
else if(count==i+1){
$($(".next").get(i)).off().on('click',function(){
submit();
});
}
else
{
createNextButton(i);
}
});
function submit(){
// post to ajax
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i){
$($(".next").get(i)).on('click',function(){
$(".questions").hide();
$($(".questions").get(i+1)).show();
});
}
});
</script>
</body>
</html>
I have done a quiz website which shows a question and 4 options with radio button. the questions are fetched from database. but all questions are showing up all at a time. i want to show one question at a time when the user clicks the option. soon after he clicks the option the current question should fade and show the next question. i have tried many ways using javascript and all but nothing is working. can anyone help me. here is my html code
<div class="services">
<div class="container">
<?php $response=mysql_query("select * from questions");?>
<form method='post' id='quiz_form'>
<?php while($result=mysql_fetch_array($response)){ ?>
<div id="question_<?php echo $result['id'];?>" class='question'> <!--check the class for plurals if error occurs-->
<h2 id="question_<?php echo $result['id'];?>"><?php echo $result['id'].".".$result['question_name'];?></h2>
<div class='align'>
<input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans1_<?php echo $result['id'];?>' for='1'><?php echo $result['answer1'];?></label>
<br/>
<input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans2_<?php echo $result['id'];?>' for='1'><?php echo $result['answer2'];?></label>
<br/>
<input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans3_<?php echo $result['id'];?>' for='1'><?php echo $result['answer3'];?></label>
<br/>
<input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans4_<?php echo $result['id'];?>' for='1'><?php echo $result['answer4'];?></label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
</div>
<br/>
<input type="button" id='next<?php echo $result['id'];?>' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
</form>
</div>
</div>
that is because you're using select * from questions, this will fetch everything in the questions database, what you would be doing is requesting one question at a time select * from questions LIMIT 0, 1 // index_from, amount, And then next time increase your limit with one LIMIT 1, 1
A general and efficient approach to achieve this by loading the question in UI one at a time, when your desired event fired in UI.
Lets elaborate the strategy here
Step 1: there will be js function call to load the desired question.
the desired or existing question id will be argument to this js
function.
Step 2 the js function will have a ajax call to a php sript with the argument.
Step 3 backend php should return a json object array with desird question and option.
Step 4:js function should now arrange to print the return value accordingly
YOU CAN TRY THIS OUT:
php code can be:
$sql = "SELECT * FROM questions";
if ($result = $conn->query($sql)){
// output data of each row
while ($row = $result->fetch_assoc()) {?>
<div id="question_<?php echo $row['id'];?>" class='question'>
<h2><?php echo $row['id'];?></h2>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer1'];?>"><?php echo $row['answer1'];?>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer2'];?>"><?php echo $row['answer2'];?>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer3'];?>"><?php echo $row['answer3'];?>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer4'];?>"><?php echo $row['answer4'];?>
</div>
<?php }
} else {
echo "0 results";
}
js code :
jQuery(document).ready(function(){
jQuery('.question').hide();
jQuery('.question').first().show();
jQuery('.quiz-radio').change(function(){
console.log(jQuery(this).val());//display answer
var current=jQuery(this).closest('.question');
current.hide();
current.next().show();
});
});
NOTE: you need to call the js file in the .php or .phtml file.
I executed this code in my system , where all my questions and answers are in the database . i have stored them in a php variable.
Here I've made an example of how you can realize this solution. You will need 3 files.
1) Download jquery library and put it in site root folder, in this example I use jquery-3.3.1.min.js
2) Create file index.php with this content
<html>
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="services">
<div id="container"></div>
</div>
<script>
$(document).ready(function(){
$('body').on('click','#next', function(){
var curr_id = $(this).data('nextQuestion');
var answer1 = $('#radio1').is(':checked');
var answer2 = $('#radio2').is(':checked');
var answer3 = $('#radio3').is(':checked');
var answer4 = $('#radio4').is(':checked');
getQuestion(curr_id, answer1, answer2, answer3, answer4);
});
function getQuestion(curr_id, answer1=false, answer2=false, answer3=false, answer4=false){
$.post("ajax.php",
{
next_id: parseInt(curr_id)+1,
answer1: answer1,
answer2: answer2,
answer3: answer3,
answer4: answer4,
},
function(data, status){
$('#container').html(data);
});
}
getQuestion(-1);
});
</script>
</body>
</html>
2) Create ajax.php
<?php
$con=mysqli_connect("localhost","root","","quiz"); // change here to your data
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Check the number of all questions, if next_id is more than last question, back to first or whatever you want;
$response=mysqli_query($con,"select * from questions");
$number_of_all_questions = mysqli_num_rows($response);
if($number_of_all_questions <= $_POST['next_id']){
$_POST['next_id'] = 0;
}
// query next question
$response=mysqli_query($con,"select * from questions WHERE id =(select min(id) from questions where id > {$_POST['next_id']})");
?>
<?php while($result=mysqli_fetch_array($response,MYSQLI_ASSOC)){ ?>
<div id="question_<?= $result['id'] ?>" class='question'> <!--check the class for plurals if error occurs-->
<h2><?= $result['id'].".".$result['question_name'] ?></h2>
<div class='align'>
<input type="radio" value="1" id='radio1' name='1'>
<label id='ans1' for='1'><?= $result['answer1'] ?></label>
<br/>
<input type="radio" value="2" id='radio2' name='2'>
<label id='ans2' for='2'><?= $result['answer2'] ?></label>
<br/>
<input type="radio" value="3" id='radio3' name='3'>
<label id='ans3' for='3'><?= $result['answer3'] ?></label>
<br/>
<input type="radio" value="4" id='radio4' name='4'>
<label id='ans4' for='4'><?= $result['answer4'] ?></label>
</div>
<br/>
<input type="button" data-next-question="<?= $_POST['next_id'] ?>" id='next' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
<?php mysqli_close($con); ?>
I am performing a Form Validation in PHP. My purpose is to show the error message at the same page with form, in order to be clear for the user.
But I have to problems. First how to hide my form, where are no errors in submitting it(I want to print onl one message in this case and to hide the frm). I am trying to use:
if(false === $error)
{
//Validimi perfundoi me sukses!
echo "<script>
document.getElementById('wrap').style.display = 'none';
</script>";
echo $name;
}
but it does not function.
Second I am having problems with checkbox validation. I am using the array $activity, to save values from checkbox, as they may be multiple values, but when the user select no value at all at the checkbox part, it gives me the error that: Warning: in_array() expects parameter 2 to be array, null given even i have initialized $activity as an arra: $activity=array();.
<?php
$name_error='';
$device_error ='';
$OS_error='';
$activity_error='';
$device='';
$OS='';
$activity=array();
if(!empty($_POST['submitted']))
{//nese form eshte submitted atehere validohen fushat
$name = trim($_POST['name']);//heq hapesirat
$error = false;
if(empty($name))
{
$name_error='Emri eshte bosh. Ju lutem plotesoni emrin.';
$error=true;
}
if(empty($_POST['device']))
{
$device_error = "Ju lutem selektoni nje pajisje";
$error=true;
}
else
{
$device = $_POST['device'];
}
if(empty($_POST['OS']))
{
$OS_error ="Ju lutem selektoni sistemin operativ";
$error=true;
}
else
{
$OS = $_POST['OS'];
}
if(empty($_POST['activity']) || count($_POST['activity']) < 2)
{
$activity_error = "Ju lutem selektoni te pakten 2 aktivitete";
$error=true;
}
$activity = $_POST['activity'];
if(false === $error)
{
//Validimi perfundoi me sukses!
echo "<script>
document.getElementById('wrap').style.display = 'none';
</script>";
echo $name;
}
}
?>
<!DOCTYPE html>
<html >
<head>
<title>Computer Form</title>
<link href="compForm.css" rel="stylesheet" type="text/css" />
</head>
<body >
<div id="wrap" style="display: block">
<form method="post" action='?' id="compform" >
<div>
<div class="cont_order">
<fieldset>
<legend>Beni zgjedhjen tuaj!</legend>
<div class='field_container'>
<label >Zgjidhni pajisjen qe perdorni me shpesh:</label>
<span class="error"><?php echo $device_error;?></span>
<label class='radiolabel'><input type="radio" name="device" value="Desktop"
<?php echo ($device=='Desktop')? 'checked':''; ?>/>Desktop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Laptop"
<?php echo ($device=='Laptop')? 'checked':''; ?> />Laptop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Tablet"
<?php echo ($device=='Tablet')? 'checked':''; ?> />Tablet</label><br/>
</div>
<div class='field_container'>
<label for="OS">Zgjidhni Sistemin e Operimit qe perdorni:</label >
<span class='error'><?php echo $OS_error?></span>
<select id="OS" name='OS' >
<option value="">Zgjidhni OS</option>
<option <?php echo $OS=='Windows'?'selected':''; ?> >Windows</option>
<option <?php echo $OS=='Linux'?'selected':''; ?> >Linux</option>
<option <?php echo $OS=='Mac'?'selected':''; ?> >Mac</option>
</select>
</div>
<div class='field_container'>
<label >Selektoni dy aktivitetet qe preferoni me shume:</label>
<span class='error'><?php echo $activity_error ?></span>
<label><input type="checkbox" value="Programim Desktop" name='activity[]'
<?php echo (in_array('Programim Desktop',$activity)) ?'checked':'' ?> />Programim Desktop</label>
<label><input type="checkbox" value="Programim Web" name='activity[]'
<?php echo (in_array('Programim Web',$activity)) ?'checked':'' ?> />Programim Web</label>
<label><input type="checkbox" value="Dizenjim" name='activity[]'
<?php echo (in_array('Dizenjim',$activity)) ?'checked':'' ?> />Dizenjim</label>
<label><input type="checkbox" value="Analize te dhenash" name='activity[]'
<?php echo (in_array('Analize te dhenash',$activity)) ?'checked':'' ?> />Analize te dhenash</label>
<label><input type="checkbox" value="Kerkim shkencor" name='activity[]'
<?php echo (in_array('Kerkim shkencor',$activity))?> />Kerkim shkencor</label>
</div>
</fieldset>
</div>
<div class="cont_details">
<fieldset>
<legend>Detajet e kontaktit</legend>
<label for='name'>Emri</label>
<input type="text" id="name" name='name'
value='<?php echo htmlentities($name) ?>' />
<span class='error'><?php echo $name_error ?></span>
<br/>
<label for='address'>Adresa e emailit</label>
<input type="email" id="address" name='address' />
<br/>
</fieldset>
</div>
<input type='submit' name='submitted' id='submit' value='Submit' />
</div>
</form>
</div>
</body>
</html>
Here's my quick solution (untested). Let's clean up your code a little:
Instead of using (and wasting) separate variables for each error message, let's use an associative array called $errors. The keys will be the name of the inputs and the values will be their respective error messages.
To ensure that you don't get warnings from undeclared variables, we will declare variables for each input at the top of the page.
Let's also use a new variable $submitted to know whether the form was submitted or not.
Now, if the form was $submitted and there are no (!) $errors, then we hide the form. Otherwise, we show the form and any errors if there are any.
<?php
$name = '';
$device = '';
$OS = '';
$activity = array();
$submitted = !empty($_POST['submitted']);
$errors = array();
if ($submitted) {
//nese form eshte submitted atehere validohen fushat
if (empty($_POST['name'])) {
$errors['name'] ='Emri eshte bosh. Ju lutem plotesoni emrin.';
} else {
$name = trim($_POST['name']);
}
if (empty($_POST['device'])) {
$errors['device'] = "Ju lutem selektoni nje pajisje";
} else{
$device = $_POST['device'];
}
if (empty($_POST['OS'])) {
$errors['OS'] = "Ju lutem selektoni sistemin operativ";
} else {
$OS = $_POST['OS'];
}
if (empty($_POST['activity']) || count($_POST['activity']) < 2) {
$errors['activity'] = "Ju lutem selektoni te pakten 2 aktivitete";
} else {
$activity = $_POST['activity'];
}
}
?>
<!DOCTYPE html>
<html >
<head>
<title>Computer Form</title>
<link href="compForm.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php if ($submitted && !$errors) : ?>
<?php echo $name ?>
<?php else : ?>
<div id="wrap">
<form method="post" action='?' id="compform" >
<div>
<div class="cont_order">
<fieldset>
<legend>Beni zgjedhjen tuaj!</legend>
<div class='field_container'>
<label >Zgjidhni pajisjen qe perdorni me shpesh:</label>
<span class="error"><?php echo isset($errors['device']) ? $errors['device'] : '' ?></span>
<label class='radiolabel'><input type="radio" name="device" value="Desktop"
<?php echo $device == 'Desktop' ? 'checked' : '' ?>/>Desktop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Laptop"
<?php echo $device == 'Laptop' ? 'checked' : '' ?> />Laptop</label><br/>
<label class='radiolabel'><input type="radio" name="device" value="Tablet"
<?php echo $device == 'Tablet' ? 'checked' : '' ?> />Tablet</label><br/>
</div>
<div class='field_container'>
<label for="OS">Zgjidhni Sistemin e Operimit qe perdorni:</label >
<span class='error'><?php echo isset($errors['OS']) ? $errors['OS'] : '' ?></span>
<select id="OS" name='OS' >
<option value="">Zgjidhni OS</option>
<option <?php echo $OS == 'Windows' ? 'selected' : '' ?> >Windows</option>
<option <?php echo $OS == 'Linux' ? 'selected' : '' ?> >Linux</option>
<option <?php echo $OS == 'Mac' ? 'selected' : '' ?> >Mac</option>
</select>
</div>
<div class='field_container'>
<label >Selektoni dy aktivitetet qe preferoni me shume:</label>
<span class='error'><?php echo isset($errors['activity']) ? $errors['activity'] : '' ?></span>
<label><input type="checkbox" value="Programim Desktop" name='activity[]'
<?php echo in_array('Programim Desktop', $activity) ? 'checked' : '' ?> />Programim Desktop</label>
<label><input type="checkbox" value="Programim Web" name='activity[]'
<?php echo in_array('Programim Web', $activity) ? 'checked' : '' ?> />Programim Web</label>
<label><input type="checkbox" value="Dizenjim" name='activity[]'
<?php echo in_array('Dizenjim', $activity) ? 'checked' : '' ?> />Dizenjim</label>
<label><input type="checkbox" value="Analize te dhenash" name='activity[]'
<?php echo in_array('Analize te dhenash', $activity) ? 'checked' : '' ?> />Analize te dhenash</label>
<label><input type="checkbox" value="Kerkim shkencor" name='activity[]'
<?php echo in_array('Kerkim shkencor', $activity) ? 'checked' : '' ?> />Kerkim shkencor</label>
</div>
</fieldset>
</div>
<div class="cont_details">
<fieldset>
<legend>Detajet e kontaktit</legend>
<label for='name'>Emri</label>
<input type="text" id="name" name='name' value='<?php echo htmlentities($name) ?>' />
<span class='error'><?php echo isset($errors['name']) ? $errors['name'] : '' ?></span>
<br/>
<label for='address'>Adresa e emailit</label>
<input type="email" id="address" name='address' />
<br/>
</fieldset>
</div>
<input type='submit' name='submitted' id='submit' value='Submit' />
</div>
</form>
</div>
<?php endif ?>
</body>
</html>
You can check the $_POST['submitted'] as below pseudocode:
//form is submitted
if isset $_POST['submitted']
//process form and show error message
else
//show form