Set the selected value in select2 multiple using PHP - php

How will i set the selected item in select2 multiple ? i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
<?php
$mytitle = array(
"867310020292434, 867310021548131, 867310021561670");
$test = implode(',', $mytitle);
$query=mysqli_query($link,"select * from inventory where ITEM_CODE_MX='OPP01-3006GRY'");
while($row=mysqli_fetch_array($query))
{
$imei=$row["IMEI_MX"];
$title = explode(',', $imei);
}
?>
<script>
$(function () {
$('#tags').select2();
function select (event){
$("#tags").select2({
maximumSelectionLength: $('#quantitytotransfer').val(),
formatSelectionTooBig: function (limit) {
$('#box').show().text('Callback!');
parseInt($("#quantitytotransfer").val())
return 'Too many selected elements (' + limit + ')';
}
});
}
$('#quantitytotransfer').on('keyup', select);
select()
});
</script>
<select id="tags" name='title[]' style="width:300px;" class="form-control select2-offscreen" onchange="getCount()" multiple>
<?php
foreach ($title as $opt) {
$sel = '';
$wew = trim($is);
if (in_array($opt, $mytitle)) {
$sel = 'selected="selected" ';
}
if (!empty($opt)) {
echo "<option ' . $sel . ' value='$opt'>$opt</option>";
}
}
?>
</select>

if you want to select the first option here is the code
$sel = "selected";
foreach ($title as $opt) {
if (!empty($opt)) {
echo "<option value='" . $opt . "'" . $sel . ">" . $opt . "</option>";
$sel = "";
}

Related

Dropdown function is losing words after space in submitted output

I'm trying to create my first function in PHP, a drop down. It's almost working, but when I submit/post the data the options with a space in it will only show the first word in the output.
In the example I have 'First Name' as an option in the drop down list. When I hit submit, the output will only be 'First'. When I change 'First Name' to 'First-Name' it works, the output is 'First-Name'. So I think I need to add quotes somewhere in the code so that it is handled as a string??
Hope someone can help me out, I'm so close to what I want.
<!DOCTYPE HTML>
<html>
<body>
<?php
include('db_functions.php');
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = clean_input($_POST['first_name']);
}
//drop down function
function dropdown($name, $options) {
$dropdown = '<select type="text" name='.$name.'>'."\n";
$rows = $options;
if($rows === false) {
$error = db_error();
}
$totalrows = count($rows);
for ($x = 0; $x < $totalrows; $x++) {
$dropdown .= '<option value=' . $rows[$x][$name] . '>' . $rows[$x][$name] . '</option>'."\n";
}
$dropdown .='</select>'."\n";
return $dropdown;
}
echo '<form action="' . htmlspecialchars($_SERVER["PHP_SELF"]) . '" method="post">';
//start dropdown
echo 'First Name:';
$name = 'first_name';
$options = db_select("SELECT DISTINCT first_name FROM nametable GROUP BY first_name ORDER BY first_name ASC LIMIT 20");
echo dropdown($name, $options);
//end dropdown
echo '<input type="submit" name="submit" value="Submit">';
echo '</form>';
echo $fName;
?>
</body>
</html>
Your code is writing
<option value=First Name>
The space ends the value, so Name is a separate attribute. You need to put the value in quotes, so it's
<option value="First Name">
The code should be:
$dropdown .= '<option value="' . $rows[$x][$name] . '">' . $rows[$x][$name] . '</option>'."\n";

selecting option from select element with php

I have a database field country which I want to query and select that country option from a select element. Is there any way to do this without adding:
if (query->country == "<some country>"){echo "selected"}
in every single option tag? As there are hundreds of country options. Here is a little example of the code. Thank you.
$query = $query->fetch_object();
// which ever country is held in the variable `$query->country` should be selected
echo"<select>
<option>Afghanistan</option>
......
......
<option>Zimbabwe</option>
</select>";
Don't you have a list of all countries on your server?
$countries = ["Afghanistan", ... , "Zimbabwe"];
You could do something like this:
$selection = "Some country";
echo "<select>";
foreach($countries as $country)
{
if($country == $selection)
echo "<option selected>" . $country . "</option>";
else
echo "<option>" . $country . "</option>";
}
echo "</select>";
The IF still needs to be "placed" on every <option> but as a programmer you should do something like this:
$options = array( 'Afghanistan', '...', 'Zimbabwe' );
foreach( $options as $option )
{
$selected = ( $query->country == $option )? ' selected': '';
echo '<option' . $selected . '>' . $option . '</option>';
}
and if you're unfamiliar with ternary operator, the $selected = ... part above can be written like this:
if ( $query->country == $option )
{
$selected = ' selected';
}
else
{
$selected = '';
}

Country list selection box - Set one as selected

I have a country list of every country in a form to get a parcel quote.
When a user presses the "Get Quote" button, all the text forms retain the information previously entered using PHP.
How can I do this with the country list box? As I can't have PHP on every option checking if that is the country selected and adding "Selected" to the html.
Is there a better way other than generating the country list from a file in a loop?
EDIT:
Going for the method of looping through a file, and checking..
This is what I have so far:
$countries = fopen("includes/countries.txt", "r");
$countries = explode(";", $countries);
Then in the HTML:
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
echo("<option value=\"" . $country . "\">" . $country . "</option>");
}
?>
</select>
Not yet finished.
I assume you have an array with your countries stored. You could try something like this:
$countries = array('Albania', 'Egypt');
$selected_country_id = $_GET['c_id']; // You may need to change this to match with your code
$country_selected = array();
foreach($countries as $country) {
if($country['id'] == $selected_country_id) {
$country_selected[ $country['id'] ] = ' selected ';
} else {
$country_selected[ $country['id'] ] = '';
}
}
Then, assuming that you dynamically add your Select-Options, do this:
// In your each-fn
echo '<option value="' . $country['id'] . '" ' . $country_selected[ $country['id'] ] . '>' . $country['name'] . '</option>';
Something like this would be better
foreach ($countries as $country) {
?>
<option value="<?php echo $country" <?php echo ($country == $_POST['country'] ? 'selected' : ''; ?>><?php echo $country; ?></option>
<?php
}
<select id="countries" name="countries">
<?php
foreach ($countries as $country){
if(isset($_POST["country"]) && $_POST["country"] == $country){
$sel = "selected";
}else { $sel= ""; }
echo("<option value=\"" . $country . "\"" .$sel.">" . $country . "</option>");
}
?>
</select>
Get All Country-State-City Selectbox ....!!!
See Link : GitHub

Get data from DB to set as default in dropdown HTML/CSS/MYSQL/PHP

Hello guys I want to get data from the DB to set as default/selected in my dropdown.
I have a page named Update Project, in that page I have a dropdown component that is filled by records from my data, however I want to set the selected value from the query result.
This is what I've tried so far:
$st_ac = $conn->prepare( "SELECT p.project_code, m.type
FROM tblprojects as p
JOIN tblprojectsmaster as m
ON p.project_code = m.project_code
WHERE p.project_code = :code" );
$st_ac->execute(array(':code' => $code));
$result = $st_ac->fetch(PDO::FETCH_ASSOC);
$ptype = $result['type']; // the data to be selected in the dropdwon
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value"' . $type . '"';
if($ptype == $type)
echo 'selected="selected"';
echo '>' . $description . '</option>';
echo '<br />';
?>
<option value="<?php echo $type; ?>"><?php echo $description; ?></option>
<?php
}
?>
But I can't be able to achieve what I want. Any ideas? Your help will be truly appreciated. Thanks.
Try this
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value="'.$type.'"';
if($ptype == $type)
{
echo 'selected="selected"';
}
echo '>'.$description.'</option>';
}
?>
May be you can use like this
echo '<option value="' . $type . '"'; if($ptype == $type) { echo 'selected="selected" } >'; echo $description . '</option>'; echo '<br />';

How to set multiple select options by default from array

I'm trying to retrieve options/values from my database in the from of an array i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary.
//data in database
$mytitle = array(
'Arbitrator',
'Attorney',
'Student',
'Other'
);
//data for multiple select
$title = array(
'Judge' ,
'Magistrate' ,
'Attorney' ,
'Arbitrator',
'Title Examiner' ,
'Law Clerk','Paralegal' ,
'Intern' ,
'Legal Assistant',
'Judicial Assistant',
'Law Librarian' ,
'Law Educator' ,
'Attorney',
'Student',
'Other'
);
echo "<select name='title[]' multiple='multiple'>";
$test = implode(',', $mytitle);
for ($i=0; $i<=14; $i++) {
if($test == $title[$i]) {
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}
else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
echo "</select>";
I think you may have a logic error. Try this as your loop:
foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}
Use the in_array() function.
for ($i=0; $i<=14; $i++) {
if(in_array($title[$i], $mytitle)){
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
Very simple with the help of jQuery where the select has the id test
$('#test option').attr('selected', 'selected');
JSFiddle Example

Categories