i tried to automatically select the value of multiselect box using data retrieved from database, but its not working...
this is the code for html multiselect
<select name="category" id="category" multiple="multiple" class="select validate[required]" style="width:100%">
</select>
at page load i dynamically load options for multiselect from database (mysql)
$.ajax({
url:'search/category.php',
type:'POST',
data:{cat_id:1}, //1 means jobs category
async:true,
success: function(data){
$("#category").html(data);
}
});
but if i have to auto select value in multiselect its not working
<?php
$qry ="select tags from posts where id='$id'";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_assoc($res);
$tags = $row['tags'];
?>
<script>
$(function(){
$("#category").val(<?php echo $tags; ?>); //example: .val(3);
}
</script>
ajax is correct but you need to echo select options correctly
in category function try this :
foreach ($tags as $tag=>$val) {
echo "<option value=".$val." > ".$tag."</option>";
}
You are just missing the quotes in your $("#category").val(); line. Check this fiddle out.
$("#category").val( "'" + <?php echo $tags; ?> + "'");
should get it to work
Related
Please forgive me if I make any mistakes in english, its not really my best language. I will edit this post if I make errors please let me know.
I'm trying to make a php page with Codeigniter with a select tag whose values are from a database, and am trying to populate a second select tag based from the value placed on the former.
My college_subj database have three columns.
CollCode, SC, and Subj.
Basically, the College Code(CollCode) and Subject Code(SC) have combinations. A College Code X can have A,B,C SC, and College Code Y can have B,C,D,E SC. I am trying to make those SC appear on my second select tag when the first select tag, the CollCode, has a value.
The page's function is accept values from the two select tags and insert it into the database.
Here's the select tags on my edit.php:
<form method="post" action="<?php echo base_url();>index.php/Controller/insertfunction" id="crq">
<h3>Select College Code:</h3>
<select id="codecrq" name="code">
<option value="" selected="selected">---Select College Code---</option>
<?php foreach ($code as $row4): ?>
<option label="<?php echo $row4['Code']; ?>" value="<?php echo $row4['Code']; ?>" <?php echo set_select('code', $row4['Code'], False); ?>> <?php echo $row4['Code'] ; ?> </option>
<?php endforeach; ?>
</select>
<h3>Select SC:</h3>
<select id="sccrq" name="sc">
<option value="" selected="selected">---Select SC---</option>
</select>
</form>
Here's how I get the values that I placed in the Code select tag which is in the Model:
public function Code() {
$this->db->distinct();
$this->db->select('college_subj.CollCode');
$this->db->from('college_subj');
$query = $this->db->get();
return $query->result_array();
}
Here's a jquery that I try to use to populate the SC select tag:
$("#codecrq").change(function(){
var selectedMark = $("code").val();
if(selectedMark !== ""){
$.ajax({
type: "GET",
url: "Controller/sccrq/" + selectedMark,
success: function(data){
$("#sccrq").html("");
$("#sccrq").append("<option value=''></option>");
$.each(data, function(){
$("#sccrq").append("<option value='" + this.sc + "'>" + this.sc + "</option>");
});
}
});
}
});
and here's the sccrq code from my controller, which is supposed to get the SCs based from the College Code combination and pass it on the SC select tag:
function sccrq($code){
$this->db->distinct();
$this->db->select('college_subj.sc');
$this->db->from('college_subj');
$this->db->where($code);
$query = $this->db->get()->result_array();
return $query;
}
I try making it run, but nothing comes out from the SC select tag.
Any help will be deeply appreciated!
Thank you for you're time!
You can try
function sccrq($code){
$query = $this->db->query("SELECT SC FROM college_subj WHERE code = '".$code."'");
return $query;
}
So, I wanna change, using values from a comboBox, another comboBox values (from database MYSQL ). Don't know where the problem is but thinking about that function.
Sorry for my english btw, isn't my native language.
Here are my dropdown lists in HTML:
<select name="Discipline" id="DisciplineList">
<?php include "combo1.php";
?>
</select>
</div>
<div class="alegere2">
<?php echo "Alegeti lectia:" ;
?>
<select name="lectie" id="lectieList">
</select>
Here is the code that I use to fill the second dropdown list using the values from the first one:
< script type="text/javascript">
$(document).on("change","#DisciplineList",function(){
var val = $(this).val();
$.ajax({
url: "combo2.php",
data: {Discipline:val},
type: "GET" ,
dataType: "html",
success: function(result){
$("#lectieList").html(result);
}
});
});
< /script>
Here is the first comboBox fill: ( it fills corectly)
<?php
require("db.php");
$results = mysqli_query($db,"SELECT nume,id FROM discipline");
$nr_discipline=mysqli_num_rows($results);
while($nr_discipline > 0){
$row = mysqli_fetch_row($results);
echo '<option value="'.$row[1].'">'.$row[0].'</option>';
$nr_discipline--;
}
?>
Here is the 2nd comboBox code : (isn't working )
<?php
// Connects to your Database
require("db.php");
$id_discipline = $_GET['Discipline'];
$Query= "SELECT nume,id FROM lectii WHERE id_disciplina =2";
$lectie = mysqli_query($db,$Query);
$nr_lectie = mysql_num_rows($lectie);
while ($nr_lectie > 0) {
$row = mysql_fetch_row($lectie);
echo '<option value="'.$row[1].'">'.$row[0].'</option>';
$nr_lectie--;
}
?>
I don't know where is the problem. It looks like the function is not working at all.
$("#lectie").html(result);
here lectie is class not id replace lectie by lectieList that is the id
So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>
In a file following code is written which populate the value of combobox :
<select id="company" required="required" class="form-control" value = "select" name="subject_code" placeholder="Select" >
<?php
//Iterating list of subjects available to be filled .
echo "<option> Select </option>";
foreach ($subjects_to_fill as $subject_id => $subject_name) {
# code...
echo "<option value=".$subject_id."> ".$subject_name." </option>";
}
?>
</select>
On selecting a particular item from the combobox, I want to display the faculty_name dynamically from faculty_table on the basis of $subject_id.
table structure:
faculty_table(faculty_id,faculty_name,subject_id)
subject_table(subject_id,subject_name,faculty_id)
You will need to use ajax for this task.
Add a <div> and below script in your current file.
<div id="faculty"></div>
<script type="text/javascript">
function get_faculty()
{
var id = document.getElementById("company").value;
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_faculty.php",
data: dataString,
success: function(html)
{
$("#faculty").html(html);
}
});
}
</script>
Now create another get_faculty.php file in same folder which will be called on onchange event of company dropdown.
Write below code in that file
if($_POST['id'])
{
$id=$_POST['id'];
$con=mysqli_connect("localhost","username","pass","dbname");
$sql=mysqli_query($con,"SELECT faculty_name from faculty_table where subject_id = ".$id);
while($row=mysqli_fetch_array($sql))
{
echo $row['faculty_name'];
}
}
Dont forget to write mysqli_connect credentials and query accordingly.
I have a couple of SELECT boxes that are pulling from the database, how can I get the option that is selected in SELECT box 1 to filter the SQL in the SELECT box 2?
EG SELECT 1 - Make (Audi, BMW) SELECT 2 - Model (A1,A3, 1 Series, 3 Series)
I want to show that if I pick Audi from SELECT 1 that it will use Audi to fill the WHERE clause in my SQL to filter for the SELECT 2
<label>Manufacturer</label>
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="make" name="make" >
<option value=""></option>
<?php $sqlmake = odbc_exec($cnn, "SELECT DISTINCT Manufacturer FROM lkup.alldata ORDER BY Manufacturer ");
while($manurs = odbc_fetch_array($sqlmake)) {
echo '<option value="'. $manurs['Manufacturer'] .'">'. $manurs['Manufacturer'] .'</option>';
}
?>
</select>
From the above I've been working on this below, which returns no errors but also when you click on the SELECT returns no values in the SELECT.
Where have I gone astray?
My SELECT
<select class="select2_category form-control" data-placeholder="Choose a Category" tabindex="1" id="model" name="model">
<option value=""></option>
</select>
<script>
$(function() {
$('.make').change(function() {
var select = $('.model').empty();
$.get('assets/configs/script.php', {model: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
</script>
The script.php
<?php
session_start();
date_default_timezone_set("Europe/London");
error_reporting(0);
include 'config.php'; //my db settings
if (isset($_GET['model'])) {
$model = addslashes($_GET['model']);
$sqlmodel = odbc_exec($cnn, "SELECT DISTINCT ModelName FROM lkup.MyTable WHERE ModelName IS NOT NULL AND Make = $model ORDER BY ModelName ");
$modelrs = array();
while ($row = $sqlmodel->fetch_assoc()) {
$modelrs[] = array(
'ModelName' => $modelrs['ModelName']
);
}
echo json_encode($modelrs);
}?>
If you are familiar with javascript or jQuery you could run another php echo statement to create the other select options with all the possibilities, and then with jQuery hide or show the appropriate options.
$('select[name=first_select]').on('change', function(){
var make = $(this).val();
$.each($('select[name=second_select] option'), function(){
if($(this).prop('class') != make){
$(this).hide();
}
}
});
After a lot of problems with this I found this link that worked a treat. I think my main problem is that I'm using PHP & MS SQL Server, which makes life difficult.
This I found as my solution