how to get all values from a select2 multiple after submitting form php? - php

After selection of several elements (tasks) inside the select2 multiple, I submit a form and I would like to get in POST the data with PHP.
However, I get only the last selected value and can't get the others (dd($_POST['ovr_tch']); returns only the last value).
<select name="ovr_tch[]" id="field_ovr_tch" class="form-select" multiple style="resize: vertical; width: 100%">
<option value="" selected disabled>
Veuillez sélectionner une tâche...
</option>
<?php foreach ($tasks as $task) { ?>
<option value="<?php echo $task['PK_TACHE_TCH']; ?>">
<?php echo $task['LB_TACHE_TCH']; ?>
</option>
<?php } ?>
</select>
<script>
$('#field_ovr_tch').select2();
</script>
Any help would be grateful!

Based on what you have
<select name="ovr_tch[]" id="field_ovr_tch" class="form-select" multiple style="resize: vertical; width: 100%">
You can access the selected values like this
$selectedValues = $_POST['ovr_tch'];
Edit: Make sure your select2 library is properly configured
$('#field_ovr_tch').select2({
multiple: true
});
Then loop through $selectedValues to access each value
foreach ($selectedValues as $selectedValue) {
// do something with $selectedValue
}

Related

How to keep value of selected value after form submission?

I know there are a lot of questions related to it but believe me, no solution is working for me.
<form action="index" method="post" >
<select id="s" name="dtype" class="dropdown" required
style="float: left; text-align: left;width: 20%; margin: 10px;">
<option value="400">Select Data Type</option>
<option value="401">Current</option>
<option value="402">Voltage</option>
<option value="403">kWh</option>
</select>
</form>
What I have tried
I have tried the following
<option <?php if ($_GET['dtype'] == '401') { ?>selected="true" <?php }; ?>value="401">Current</option>
<option <?php if ($_GET['dtype'] == '402') { ?>selected="true" <?php }; ?>value="402">Voltage</option>
<option <?php if ($_GET['dtype'] == '402') { ?>selected="true" <?php }; ?>value="402">kwh</option>
Tried below solution
Keep values selected after form submission
PHP keep dropdown value after submit
All the solution gives me unidentified index: dtype error
Any help would be highly appreciated.
In your form you have: method="post"
And then you use the $_GET['dtype']
Either change the method of the form to method="get" or change the if conditions to check for $_POST['dtype'].
That's why it says unidentified index. You are sending the data as post and trying to get it from the $_GET array.
Apart from this, if you are using xhtml the attribute value should be selected="selected" whereas if you use an html 5 doctype it should be just selected.
The first option (Select Data Type) must have an empty value in order for "required" option to work.
<form action="index.php" method="POST">
<select id="s" name="dtype" class="dropdown" required style="...">
<option value="">Select Data Type</option>
<option value="401" <?php if(isset($_POST['dtype']) && $_POST['dtype']=="401") {echo'selected';} ?>>Current</option>
<option value="402" <?php if(isset($_POST['dtype']) && $_POST['dtype']=="402") {echo'selected';} ?>>Voltage</option>
<option value="403" <?php if(isset($_POST['dtype']) && $_POST['dtype']=="403") {echo'selected';} ?>>kWh</option>
</select>
</form>

Assign "select" attribute to jquery select2 dropdown dynamically

I am working on jquery select2 dropdown. I have to display the multiple selected option in select area. For this purpose i loop through each of select2. If condition is met i will assign 'selected' attribute property to option so that it may appears in the select area.
But somehow the select2 fails to display the selected ''.
HTML CODE:
<div class="form-group col-md-12">
<label for="inputsskill">Skill<span class="required-field">*</span></label>
<fieldset>
<select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
#if(!$skills->isEmpty())
#foreach($skills as $skill)
<option value="{{$skill->id}}">{{$skill->name}}</option>
#endforeach
#endif
</select>
</fieldset>
</div>
JQUERY CODE:
// parse skills
var parseData = JSON.parse(skill);
// parseData is an array which contain 1,2,3 values like ['1','2','3']
$("#skill_name > option").each(function() {
// if select2 and array values matches assign selected attribute to that option
if( $.inArray($(this).val(), parseData) !== -1 ) {
$(this).attr('selected', 'selected');
}
});
Select2 Jquery:
$( "#skill_name" ).select2({
});
I dont know where i am going wrong, i would appreciate if someone guide me in this.
Thanks,
you can achieve this functionality with PHP easily.
E.g : fetch skills from the database which you want to preselect and create an array of skills. Then match this in your loop.Like
<div class="form-group col-md-12">
<label for="inputsskill">Skill<span class="required-field">*</span></label>
<fieldset>
<select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
#if(!$skills->isEmpty())
#foreach($skills as $skill)
<option value="{{$skill->id}}" <?php
if(in_array($skill->name, $selectedskillsArray)){
echo $selected = 'selected';
}
?> >{{$skill->name}}</option>
#endforeach
#endif
</select>
</fieldset>
</div>
Try this one.
Jquery solution
$( "#skill_name" ).select2({
});
$('#skill_name').val(["1","2","3"]).trigger('change');

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

Change the list of dropdown according to the selection of other dropdown

I have two dropdowns .i want second dropdown list shoul changed according to the value selected in first dropdown.
this is my first dropdown
Category :<select name="Category" id="a1_txtBox5" required="required">
<option value="select">select..</option>
<?php while($selectcategoryarray=mysql_fetch_array($selectcategory)) {
?>
<option value="<?php echo $selectcategoryarray[1];?>"><?php echo $selectcategoryarray[1];?></option>
<?php
}
?>
</select>
And here is my second dropdown:
<label style="margin-left:24px;">Subcategory :</label><select style="margin-right:35px;" name="subcategory" id="a1_txtBox3" required="required">
<option value="select"> select..</option>
<?php while($selectsubcategoryarray=mysql_fetch_array($selectsubcategory)) {
?>
<option value="<?php echo $selectsubcategoryarray[2];?>"><?php echo $selectsubcategoryarray[2];?></option>
<?php
}
?>
</select>
Please help.
Exactly you need to handle the Change Event for your first Select element and in the body of the event you need to send request to server for getting data of second Select element.
I recommend to use an ajax process to doing this.
And o this you should use jQuery for handling events and have ajax.

how to get dynamic element for ajax

I know i made lots of mistake thats why I come to here.
Actually I have some data
According to data I have Indication 1, Indication 2, Indication 3 and Indication 4, for each indication there is some message for user and if I select 2, 3 or 4 then the message will move to that corrosponding indication. And really I dont have idea how to do it becouse these message are coming from dynamicaly as:
$i=1;
while($row=mysqli_fetch_array($qry))
{
?>
<div class="solo"><div style=" width:100px;height:24px;float:left;padding:4px ;">
<select style="width:60px;font-size:14px;" onchange="move(this.value);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<!--<option value="60min">60min</option>
<option value="other">other</option>-->
</select>
</div>
<div style=" width:600px;height:24px;float:left;padding-top:8px;text-align:center;"> <?php echo $row['message'];?></div>
<div style=" width:100px;height:24px;float:left;padding:4px ;">
<div style="width:100px; float:left;">
<input style="float:left;" type="checkbox" value="<?php echo $row['id']; ?>" id="<?php echo $row['id']; ?>" name="foo[]"/><div style="padding:2px; float:left;">Kill</div>
</div>
and I am using to get these message id
<script type="text/javascript">
function move(str)
{
var a=document.getElementsByClassName("mid")[0].value;
alert(a);
}
</script>
and i display this message id as in hidden text box:
<input type="hidden" name="msg" class="mid" value="<?php echo $row['id']; ?>">
am just confuse how to get a particuler message id for each message becouse above move() function is only giving one id by [0]
So I just want to know how to do this for each element when all the input box have same class.
If i understand correctly you want to iterate over the result list of getElementByClassName.
For this have a look at: https://stackoverflow.com/a/15843940/1885950
In your case it will look like:
var mid_holders = document.getElementsByClassName("mid");
for(var i = 0; i < mid_holders.length; i++)
{
alert(mid_holders.item(i).value);
}
document.getElementsByClassName("mid") gives you an array of dom elements. You are currently taking only the first element in that array. So loop through it and get each ones value attribute
function move(str) {
var a=document.getElementsByClassName("mid");
for(var i=0;i<a.length;i++)
alert(a[i].value);
}
update
Its not clear what you are trying to achieve.
If you are trying to alert the value of dom element with index as str, then the function could be as simple as
function move(str) {
alert(document.getElementsByClassName("mid")[str].value);
}
if not please mention what you are trying to achieve in your question.

Categories