Keep the selected options after submitting the form - javascript

Good morning, I have a problem that is: I can not keep several options selected after submitting the form and I would like someone to help me.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>"><?php echo $reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>
this is my code to have the various options in the select box

You have to check if $_POST['utilizadores'] or $_GET['utilizadores'] it depends on your request type. I will use $_POST in here for explain my answer.
your select is multiple, you can use in_array function for checking that if result from db record is in array of $_POST['utilizadores']
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
**<option value="<?php echo $reg_sql['ID_USER']; ?>"
<?php
if(isset($_POST['utilizadores'])){
if(in_array($reg_sql['ID_USER'], $_POST['utilizadores'])){
echo 'selected';
}else{
echo '';
}
}
?>
>**<?php echo
$reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>

You may be able to do it more efficiently if your database result also contains which rows are selected, but when you loop through, just add the selected="selected" attribute to the <option> tag.
Assuming your $_POST array exists in this scope, you can use the in_array function in PHP to determine if the option has been selected (docs).
The ternary based operation is as follows:
in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : ''
Which says "if the ID_USER is in the post array, then print the selected attribute, otherwise, print a blank string"
Putting it all together:
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>" <?= in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : '' $?>>
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>

An example of how you can do this. Either add the "selected" string if yes or leave blank if no. You can also write selected="selected". You can do the same thing to set disabled or readonly.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<?php $selected = isset($reg_sql["mi_variable"]) ? "selected" : ""; ?>
<option value="<?php echo $reg_sql['ID_USER'];?>" <?php echo $selected; ?> >
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>

Related

OnChange with javascript/ajax result, also with a php foreach loop

I have this interesting setup that I hope someone can help me fix. I've searched and found some solutions but nothing that comes close to what I'm trying to achieve, so nothing really lead me in a direction that could get me to a solution for what I'm doing
I have a dropdown of litters. You select a litter, onchange happens, it gets the available pick spots from the database, then echos out the results with another foreach to another dropdown menu
The problem is, these dropdown menus are inside of a foreach loop (for each client available to the site user). So the first client works as expected, but because it has the same ID, the second client's dropdowns don't do anything since it's still on the same page
Hopefully someone has some insight on how to make this work :(
Here's the dropdown:
<select class="form-control mb-3" name="the_chosen_litter" id="litter" required>
<option disabled selected>First, Choose A Litter...</option>
<?php
foreach($labradoodle_two as $litter_waitlist_form){
?>
<option id="<?php echo $litter_waitlist_form['litter_id']; ?>" value="<?php echo $litter_waitlist_form['litter_id']; ?>" style="<?php if($litter_waitlist_form['status']=='LITTER CLOSED'){ echo 'color:red;'; }else{ echo 'color:green;'; } ?>" >
<?php echo $litter_waitlist_form['litter_names']; ?>
</option>
<?php } ?>
</select>
<select class="form-control mb-3" name="buyer_pick_gender" id="pick_list" required> <!-- uses jquery to fill in this field -->
<option disabled selected>Litter Selection Required...</option>
</select>
Here's the javascript/ajax:
$(document).ready(function() {
$("#litter").on("change", function() {
var litterID = document.getElementById("litter").value;
$.post('secure/litter_list_dropdown.php', { littersubmit: litterID }, function(result) {
$('#pick_list').html(result);
}
);
});
});
And for reference, here's my "litter_list_dropdown" code that pulls from the database and echos out the available "pick spots":
<?php
session_start();
include '../../database/dbh.class.php';
$litter_id = $_REQUEST['littersubmit'];
$femalespickedquery = $dbpdo->query("SELECT * FROM pick_assignment WHERE litter_id=? AND gender_id=?",$litter_id,"1")->fetchAll();
$malespickedquery = $dbpdo->query("SELECT * FROM pick_assignment WHERE litter_id=? AND gender_id=?",$litter_id,"2")->fetchAll();
?>
<option disabled="disabled" selected="selected">Choose A Pick</option>
<?php foreach ($femalespickedquery as $pick){
$picktaken=$pick['user_id'];
$pickcustom=$pick['custom_name'];
$pickposition=$pick['pick_id'];
$suffix=ordinal($pickposition);
?>
<option value="<?php echo $pickposition.' 1'; ?>" <?php if($picktaken!="0" OR $pickcustom==true){ echo "disabled"; } ?>>
<?php echo "FEMALE - " .$pickposition.$suffix. " Pick"; if($picktaken!="0" OR $pickcustom==true){ echo " *RESERVED*"; }?>
</option>
<?php } ?>
<?php
foreach ($malespickedquery as $pick){
$picktaken=$pick['user_id'];
$pickcustom=$pick['custom_name'];
$pickposition=$pick['pick_id'];
$suffix=ordinal($pickposition);
?>
<option value=<?php echo $pickposition.' 2'; ?>" <?php if($picktaken!="0" OR $pickcustom==true){ echo "disabled"; } ?>>
<?php echo "MALE - " .$pickposition.$suffix. " Pick"; if($picktaken!="0" OR $pickcustom==true){ echo " *RESERVED*"; }?>
</option>
<?php } ?>

How to hide select options when there is no data

I'm building a drop-down list with options containing data from a database and want to hide options which have zero data.
I have tried an if statement using continue but failing to catch the live data values from the database.
<select name='Database' title="Choose from database">
<option value="">All</option>
<?php foreach($database as $row):
if ($row['topic'] == 0) {
continue;
}
else {
?>
<option value="<?= $row['topic']; ?>"
<?php if ($row['topic'] == $_SESSION['prosess']){echo "
selected";}?>>
<?= $row['topic']; ?>
<?php }?>
</option>
<?php endforeach; ?>
</select>
Is there any clever javascript-, php-, etc. code that can deactivate/hide options from a database which are empty.
Add this in your css:
select option:empty {
display:none
}
I think you should try this.
<select name='Database' title="Choose from database">
<option value="">All</option>
<?php
if(count($database) > 0)
{
foreach($database as $row)
{
?>
<option value="<?= $row['topic']; ?>"
<?php if ($row['topic'] == $_SESSION['prosess']){echo "
selected";}?>>
<?= $row['topic']; ?>
<?php }?>
</option>
<?php
}
}
?>
</select>
Hope it helpful for you.

how to avoid repetition of values in dropdown list while updating in php

I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>

How can I store the value of 'series' as a session variable?

Heading
how i get the selected value of city_id from drop down list and store in a session??
`
<form action="dynamic.php" method="post">
<select name="city" >
<option value="">Select City</option>
<?php
$sql="select * from city ORDER BY city_name";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result)){
?>
<option value="<?php echo $row["city_id"];?>"><?php echo $row["city_name"];?></option>
<?php
}
?>
</select>
</form>
<?php
session_start();
if(!empty($_POST['city'])){
$_SESSION['city'] = $_POST['city'];
}
?>
You will need to session_start();
Then
$_SESSION['city'] = 'somecity';
you need use this in each page that you use the var:
session_start();
then you can add this
$_SESSION["myvar"] = "something"

How to call HTML required attribute when the value is 0?

I have a drop down list where I'm populating data from the database.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<!-- <option value="" selected="selected">?</option> -->
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
</div>
My form,
How values are populated from the database,
My database table,
I want to add a validation when the title form is populated with the value "0", which is "?", it should call the HTML required attribute.
Or I would like to disable the option with the '?' mark.
How can I do achieve this?
I have managed to find a solution to my issue. I managed to do it without any JS or Jquery. Just added an if statement.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<?php if(($this->session->userdata('Title') == 0)) { ?>
<option value="" selected disabled><?php echo $row->value; ?></option>
<?php } else{?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php } ?>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
you can use jquery like this: you can use an id for ? like id="yourZeroOption" and then
$('option#yourZeroOption').each(function() {
if ($(this).isChecked())
$("select").attr("required", true);
else
alert('this filled cannot be ?');
});
since what you asked was'nt clear enough this code might helf and if you manipulate this code you can get what you want from your code. but this for sure will give you a gist of what you should do. by the way this code does not need to submit it will show the alert before that
If this is in Laravel there is a way to catch certain number to be pass. In this case, try with greater_than rule with a custom message.
Example
$this->form_validation->set_rules('title', 'Title', 'greater_than[0]');
$this->form_validation->set_message('greater_than', 'Please select one of these value');
Note: JS validation works, But keep mind it's not always.
You should mark your <select> field as required, then the first option as disabled (and selected):
<select required>
<option value="" selected disabled>?</option>
<option value="1">Mr.</option>
<option value="2">Miss</option>
<option value="3">Mrs.</option>
</select>
This will make the first entry work as a placeholder basically.
we cant make it require with 0 value it can be done only if value=""
here is my idea,
<form action="/action_page.php">
<select required>
<option value="0">?</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select option:selected").val("");
});
</script>
<style>

Categories

Resources