How can I hide the original checkboxes and make the labels be clickable and act like checkboxes? I am sure there is a way to do it in JS! I am loading the labels and the checkboxes with PHP, they are loaded dynamically and can always be different, depending on what the user chooses prior to this page. Thanks!
foreach ($row as $type) { ?>
<label for="<?php echo $type['id'] ?>" class="interests-span">
<h3><?php echo $type['Type'] ?></h3>
</label>
<input id="<?php echo $type['id'] ?>" type="checkbox" style="display:block;" value="<?php echo $type['Type']?>" name="options[]"/>
<?php
}
Note: Labels should be linked with id or name.
Here is custom implementation what you want.
But I don't think it is correct to select checkbox with only values
foreach ($row as $type) { ?>
<label for="<?php echo $type['Type'] ?>" class="interests-span"
onclick="toggleCheckboxFromLabel('<?php echo $type['Type'] ?>')"
>
<h3><?php echo $type['Type'] ?></h3>
</label>
<input type="checkbox" style="display:block;" value="<?php echo $type['Type']?>"
name="options[]"/>
<?php } ?>
<script>
function toggleCheckboxFromLabel(val){
var checkbox = document.querySelector('input[type="checkbox"][value="' + val + '"]')
checkbox.checked = !checkbox.checked;
}
</script>
Just add an id equals to the for attribute.
$counter = 0;
foreach ($row as $type) { ?>
<label for="<?= 'checkbox_' . $counter ?>" class="interests-span">
<h3><?php echo $type['Type'] ?></h3>
</label>
<input type="checkbox" style="display:none;" id="<?= 'checkbox_' . $counter ?>" value="<?php echo $type['Type']?>"
name="options[]"/>
<?php
$counter++;
} ?>
This is what my code does: when a username is typed in the #type input field, and if that typed value matches a row value from my database table users, then my jquery code will come to action. My jquery code will then reveal the hidden div that contains text of that typed in username. My problem is my current code ignores other typed in usernames, and for some reason will reveal only one username. Example of my issue:
allen <-- "allen" is typed in input field
--------
[allen] <-- hidden div for allen now shows
pete
-------- <-- "pete" is typed in input field
<-- but hidden div for pete does not show. Why?
Is this an event bubbling issue with my js code? Because I did add e.propagation but it didn't do anything. How would I rewrite my current code so that any username that is typed will reveal a hidden div for it. Because currently I'm only able to get a hidden div for "allen" but not for the rest of the usernames. Please help, here is my code:
<input id="type">
<?php foreach (array_combine($userids, $usernames) as $userid => $username): ?>
<div id="border<?php echo $userid; ?>" style="display: none;">
<input id="username<?php echo $userid; ?>" value="<?php echo $username; ?>" type="radio">
<label for="username<?php echo $userid; ?>"><?php echo $username; ?></label>
</div>
<?php endforeach; ?>
$("#type").on('input',function(){
var userid = '<?php echo $userid; ?>';
if (this.value == $("#username"+userid).attr('value')) {
$("#border"+userid).css("display", "block");
}
else {
$("#border"+userid).css("display", "none");
}
});
Sql code:
$stmt = $conn->prepare("SELECT userid, username FROM usern");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$userids[] = $row['userid'];
$usernames[] = $row['username'];
}
$stmt->close();
#MohammadBagheri - Output for code below:
$stmt = $conn->prepare("SELECT userid, username FROM usern");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
echo '<pre>'.print_r($row, 1).'</pre>';
}
$stmt->close();
Output:
Array
(
[userid] => 35
[username] => pete
)
Array
(
[userid] => 44
[username] => allen
)
I know what the problem is.
<input id="type">
<?php foreach (array_combine($userids, $usernames) as $userid => $username): ?>
<div id="border<?php echo $userid; ?>" style="display: none;">
<input id="username<?php echo $userid; ?>" value="<?php echo $username; ?>" type="radio">
<label for="username<?php echo $userid; ?>"><?php echo $username; ?></label>
</div>
<?php endforeach; ?>
$("#type").on('input',function(){
var username = $(this).val();
var userid = $("input[value='"+username+"']").attr("id");
$("div[id^=border]").css("display", "none");
$("#border"+userid).css("display", "block");
});
You have been selecting the userid of the last occurrence of the loop and set that in jquery code which means it will always show the user with that user id and not checking what you input.
Please let me know if you need more help.
I'm doing a program where I have several exercises with their id (e.g. Id = 1, 2, 3 ...) What I would like to do is that once the user is in an exercise, he can press the Next button and take him to the next exercise, for example id + 1.
Below I show what I've done. Can you help me?
This is my modified question, now it works:
<?php
include_once("functions.php");
// Start the session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
/*echo*/ $id=$_GET['id']; // Current question
$sql = "SELECT * FROM exercises where exercise_id='$id'";
$result = $conn->query($sql); /*Check connection*/
$question_ids = [];
$result2 = doSearch($conn, 'exercise_id');
while($row = $result2->fetch_assoc()) {
array_push($question_ids, $row["exercise_id"]);
}
$order = $_GET['order'];
$next_question_id = -1;
$next_question_order = $order + 1;
if (count($question_ids) >= $next_question_order) {
$next_question_id = $question_ids[$order];
}
?>
<div id="centered_B" class="header">
<?php
$row = $result->fetch_assoc();
?>
<p><?php echo $row["exercise_id"] . ". " . $row["text"]?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"]?>"><br/><br/>
<form action='' method='post'>
<input type="radio" name="choice" value= "1" /><img src="<?php echo $row["image_path_A"] ?>"/><br>
<input type="radio" name="choice" value= "2" /><img src="<?php echo $row["image_path_B"] ?>"><br>
<input type="radio" name="choice" value= "3" /><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p2>Select difficulty level:</p2>
<form action='' method='post'>
<select name="choose" id="choose">>
<option value="1" <?php if($row["difficulty"]=="1") { echo "selected"; } ?> >1</option>
<option value="2" <?php if($row["difficulty"]=="2") { echo "selected"; } ?> >2</option>
<option value="3" <?php if($row["difficulty"]=="3") { echo "selected"; } ?> >3</option>
<option value="4" <?php if($row["difficulty"]=="4") { echo "selected"; } ?> >4</option>
<option value="5" <?php if($row["difficulty"]=="5") { echo "selected"; } ?> >5</option>
</select>
<br><br><br>
<input class="buttonSubmit" type="submit" name="submit" value="Submit">
<?php
if ($next_question_id >= 0) {
?>
<a href="?id=<?php echo $next_question_id; ?>&order=<?php echo $next_question_order; ?>" class="buttonNext" >Next Question</a>
<?php
}
?>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
$user_id = $_SESSION['user_id'];
$user_check_query = "SELECT * FROM users WHERE id='$user_id'";
if(isset($_POST['choice'], $_POST['choose'])){
$choice_answer=$_POST['choice'];
$difficulty=$_POST['choose'];
// */$user_id = $_SESSION['user_id'];*/
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES ('$id','$user_id', '$difficulty', '$choice_answer')";
$sql=mysqli_query($conn,$query);
}
}
?>
Not sure what your JS or PHP level is, but here's a pure PHP solution - not using JS.
Things to notice:
Using PDO parameterized queries to secure against SQL injection
Using a hidden form field to pass around the current question ID. After the user submits, we insert their response in the DB, and then redirect to the next question by incrementing $id++
You had 2 <form> tags. I removed one.
Please note, this code is not tested. Let me know if you have any questions. Good luck!
<?php
session_start();
// Using PDO instead of mysqli. Nothing wrong with mysqli but I'm more comfortable with PDO.
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// This is your connection to the DB.
$pdo = new PDO($dsn, $user, $pass, $opt);
// This is the current question being displayed to the user.
$id = $_GET['id'];
// You should probably do some validation on $id here. Should it be numeric, not null etc.
// Notice that we're using ? instead of passing the value directly to the DB. This is called prepared statements.
// https://phpdelusions.net/pdo#prepared
$stmt = $pdo->query('SELECT * FROM exercises where exercise_id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// You should also validate the $row here. Did you actually find a question from the DB?
?>
<div id="centered_B" class="header">
<p><?php echo $row["exercise_id"] . ". " . $row["text"] ?></p>
<img width="603" height="auto" src="<?php echo $row["image_path"] ?>"><br/><br/>
<!-- Changed the method to GET -->
<form action="" method="GET">
<!-- Notice that we're passing the question ID to server when the form submits. -->
<input type="hidden" name="id" value="<?php echo $id; ?>">
<label>
<input type="radio" name="choice" value="1"/>
</label><img src="<?php echo $row["image_path_A"] ?>"/><br>
<label>
<input type="radio" name="choice" value="2"/>
</label><img src="<?php echo $row["image_path_B"] ?>"><br>
<label>
<input type="radio" name="choice" value="3"/>
</label><img src="<?php echo $row["image_path_C"] ?>"><br>
<br><br><br><!--- Select difficulty --->
<p>Select difficulty level:</p>
<label for="choose"> Difficulty
<select name="choose" id="choose">>
<option value="1" <?php if ($row["difficulty"] == "1") {
echo "selected";
} ?> >1
</option>
<option value="2" <?php if ($row["difficulty"] == "2") {
echo "selected";
} ?> >2
</option>
<option value="3" <?php if ($row["difficulty"] == "3") {
echo "selected";
} ?> >3
</option>
<option value="4" <?php if ($row["difficulty"] == "4") {
echo "selected";
} ?> >4
</option>
<option value="5" <?php if ($row["difficulty"] == "5") {
echo "selected";
} ?> >5
</option>
</select>
</label>
<br><br><br><!--- Button --->
<!-- <button class="buttonSubmit" >Submit</button>-->
<input type="submit" name="submit" value="Submit">
<button class="buttonNext">Next Question</button>
</form>
</div><!--- end of centered_B div --->
<?php
if (isset($_POST['submit'])) {
// Changed to a single if-statement
if (isset($_POST['choice'], $_POST['choose'])) {
$user_id = $_SESSION['user_id'];
$choice_answer = $_POST['choice'];
$difficulty = $_POST['choose'];
// Again, using prepared statements.
$query = "INSERT INTO answers (exercise_id_fk, student_id, difficulty_student, choice_answer) VALUES (?, ?, ?, ?)";
$pdo
->prepare($query)
->execute([$id, $user_id, $difficulty, $choice_answer]);
// Redirect to self with incremented question ID.
// https://stackoverflow.com/a/8131377/296555
header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $id++);
die;
}
}
Maybe this can help you:
var i=$_GET['id']){;
function getNext()
{
var = var + 1; //increase var by one
return var;
}</script>
<button class="buttonNext" onclick="getNext" >Next Question</button>
Uhm, I don't know where to start here...
Ok, for first your code is horrible - regarding in style, security and everything - sorry ;)
But to help with your problem:
Don't access the next id directly but go by
SELECT * FROM exercises WHERE exercise_id > $currentId ORDER BY exercise_id ASC LIMIT 0,2
This will help if you want to delete an exercise at some point, so have a gap like 1,2,4 (3 was deleted). You can also create a position field to sort the order of the question manually, but I guess that's too advanced for first.
However:
On start you check if there's a $_GET['id'] param and set this to $currentId. Best by $currentId = (int)$_GET['id'] to prevent a serious injection. If no GET param is there, set $currentId = 0 (first call then).
Then you run the query to get your exercise - it will be in the first row of the result.
On HTML side you just assign the exercise_id from the database result to the link which leads on the next exercise (so no JavaScript is required).
To test, if there's a next question at all check if a second row exists in the result (that's why LIMIT 0,2 instead of 0,1) to decide if to show the "next exercise button".
I'm using a select form element to render multiple options and then show corresponding text from a database in the text area using an onchange event.
The value of the select option's are very long, so I'd like to pass the id, or name of the option, to my form target favorite.php, but I don't know how to do it.
HTML:
<div class="container">
<div class="had">
<form name="det" action="vispage.php" method="POST">
<label for="hadeath">Selct Title of the Hadeath</label>
<select name="header" onchange="document.getElementById('txt').innerHTML=this.value">
<?php foreach($hadeeth as $i) {?>
<option id="<?php echo $i['id']; ?>" value="<?php echo $i['short']; ?>"><?php echo $i['name']; ?></option>
<?php } ?>
</select><br><br>
<label for="a">tree :</label><br>
<textarea id="txt" name="tree" rows="15" cols="30"></textarea><br><br>
Add to Favorites </form>
</div>
</div>
PHP:
<?php
$title = "hadeeth";
include_once ("header.php");
include 'connect.php';
//CREATE THE QUERY
$query = "SELECT * FROM `search`";
//RUN THE QUERY
$result = mysqli_query($con,$query);
$hadeeth = array();
// RETRIEVE VALUES FROM RESULT
while($row = mysqli_fetch_assoc($result))
{
$hadeeth[$row['name']] = array(
'id'=>$row['id'],
'name'=>$row['name'],
'short'=>$row['short']
);
}
?>
I have a form which has some text fields. Text fields may increase or decrease according to database table. If there are 3 warehouses in database it will show 3 text boxes with available quantity as place holder. Now user have to enter quantity no more than given in placeholder in each box. How can I do validation if user enter a value more than available (which will be shown as place holder) ?. Problem is validation should be according to foreach loop. My code is below,
<?php
if (!empty($ware_details)) {
foreach ($ware_details as $data) {
?>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
<input type="number" id="return_pro" class="form-control" base_url="<?php echo site_url(); ?>" name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
<div class="dataDrop"></div>
<input type="hidden" id="quantity" value="<?php echo $data->wh_product_qty; ?>"/>
</div>
<?php } }?>
Here as you see text boxes number is depending upon foreach loop. So how can I validate? Javascript or Ajax is ok.
I tried something like this,
<?php foreach ($ware_details as $data) {?>
<script>
function check()
{
var stock = document.getElementById('quantity').value;
var return_stock = document.getElementById('return_pro').value;
if (parseFloat(stock) < parseFloat(return_stock))
{
alert("Return product can't be more than total stock");
document.getElementById('return_pro').focus();
return false;
}
//alert(return_stock);
return false;
}
But I know it is fully wrong. Any idea?
Try to use html5 required attribute. This set of code may help you.
<input type="number"
min="1"
max="<?php echo $data->wh_product_qty; ?>"
name="<?php echo $data->wh_warehouse_id;?>"
required="required"
placeholder="<?php echo $data->wh_product_qty; ?> Available" />
You cannot use an id multiple times in the document, it needs to be unique. Either use classes to identify/group elements, or enumerate the ids:
<?php
$i = 0;
if (!empty($ware_details)) {
foreach ($ware_details as $data) {
?>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
<input type="number" id="return_pro<?php echo $i; ?>" class="form-control" base_url="<?php echo site_url(); ?>" name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
<div class="dataDrop"></div>
<input type="hidden" id="quantity<?php echo $i; ?>" value="<?php echo $data->wh_product_qty; ?>"/>
</div>
<?php
$i++;
} }?>
<script>
function check(i) {
var stock = document.getElementById('quantity'+i).value;
var return_stock = document.getElementById('return_pro'+i).value;
if (parseFloat(stock) < parseFloat(return_stock))
{
alert("Return product can't be more than total stock");
document.getElementById('return_pro'+i).focus();
return false;
}
//alert(return_stock);
return false;
}
// then in the validation trigger:
for (var i=0; i< <?php echo $i; ?>; i++)
check(i);