I have select, I want user to choose one of its option .according to the selected option the other select show some options.
the second select retrieve its value from db via query . the some value should be a selected value from the first select .can any body help?
<select name="select2">
<option value="--">--------</option>
<?php
$stmt = "SELECT * FROM XXX where f=somevalue";
$data = sqlsrv_query ($conn, $stmt);
if ($data == false){}
elseif (sqlsrv_fetch_array($data) == 0){}
else {$data = sqlsrv_query ($conn, $stmt);
while ( $row = sqlsrv_fetch_array( $data, SQLSRV_FETCH_ASSOC)){ ?>
<option value="<?php echo $row["id"] ?>"><?php echo $row["name"]?></option>
<?php }}?>
</select>
Once you got what to show on second select, create an array and pass it to this function
function addToSelect(optionsToAdd) {
sNum = 0
for(option of optionsToAdd) {
sNum += 1
indivOption = document.createElement("option")
indivOption.innerText = option
indivOption.setAttribute("value", sNum)
document.getElementsByClassName("select-class")[0].appendChild(indivOption)
}
}
addToSelect(["choice 1", "choice 2", "choice 3", "choice 4"])
<html>
<head></head>
<body>
<select class="select-class">
</select>
</body>
</html>
Related
<select rows='3' name="user_id[]" required="required" multiple class="form-control select2" style="width: 100% !important">
<?php
$qid = $_GET['id'];
$student = $conn->query('SELECT u.*,s.course as ls, s.branch, s.year FROM users u left join students s on u.id = s.user_id where u.user_type = 3 ');
while ($row = $student->fetch_assoc()) {
$user_id = $row['id'];
$result = $conn->query('SELECT * FROM quiz_student_list where quiz_id ="'.$qid.'" and user_id = "'.$user_id.'"');
if ($result->num_rows == 0) {
?>
<option value="<?php echo $row['id'] ?>"><?php echo ucwords($row['name']) . ' ' . $row['ls'] . ' ' . $row['branch'] . ' ' . $row['year'] ?></option>
<?php }
}
?>
</select>
$(".select2").select2({
placeholder: "Select here",
width: 'resolve'
});
I have a students dropdown in select2 jquery but suppose I click on any one of the name it got selected but the options disappears. I have to click again to see the students list and click again on any other name. I want to select multiple in one go only.
$(".select2").select2({
placeholder: "Select here",
width: 'resolve',
closeOnSelect: false
});
closeOnSelect: false
by using this property I have actually got what I was looking for. I have set it to false so that it doesn't get closed on selection of any one of the options.
I have a form where user selects the category while adding the product.
When user want to edit the product, i am displaying all the previously populated values but could not able to figure out how to display the category he selected.
addproduct.php (displaying the categories from the database)- this code is working fine and can see all the categories in dropdown
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
In the edit product i want to display all the categories like above, but want to display the selected category in the form which i could not able to do.
editproduct.php (rough draft code) -- not working
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option select="<?php echo $cat;?>"value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
$cat - category value(previously selected) pulled from database
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
<option value="<?php echo $cat;?>"><?php echo $cat;?></option>
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<?php if($cat!=$subjectData['name']){?> <option value="<?
php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
<?php } ?>
Try using this code and please use mysqli as mysql is deprecated. previously selected category should be before while loop. Hope it helps
Two issues with your code:
You are using mysql functions, which are depreciated and don't even exist in the current version of PHP. Use mysqli or PDO functions.
The html you are generating is invalid syntax.
I'll leave the first issue to you to correct.
For the 2nd issue, all of the non-selected options in your dropdown will not have the selected attribute.
Only the selected item will have that attribute. The code below assumes that the variable $cat has the previously selected value, and each row has a
column named 'cat'. When $cat matches the value in the column 'cat', it will add selected='selected' to the option.
<?php
require 'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];
$selected = "";
if($cat == $subjectData['cat']) {
$selected = "selected='selected' ";
}
echo "<option ".$selected."value=".$subjectData['name'].">";
echo $subjectData['name'];
echo "</option>\n";
}
?>
I have a multidimensional php array as following:
$country = array ("India" => array("Maharashtra","Tamil Nadu","West Bengal"),
"USA"=> array ("New York", "California", "Florida"),
"Canada"=>array("Ontario", "Alberta", "Manitoba"));
I want to create two drop down boxes. One will have the country name. The other will have the state name, which will get populated when the first box is selected.
I have written the code for the first box:
echo "<select name='name'>\n";
foreach($country as $key => $item) {
echo "\t<option>$key</option>\n";
}
echo "</select>\n";
Can anyone suggest me how to create the next drop down box?
Take a look at this sample code. From my understanding you don't want to make use of a database or an additional ajax call so I populated a javascriopt cache variable object with all states
<?php
$data = array("India" => array("Maharashtra", "Tamil Nadu", "West Bengal"),
"USA" => array("New York", "California"),
"Canada" => array("Ontario", "Alberta", "Manitoba"));
$countries = array_keys($data);
?>
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>-->
<script>
//Store country as a javascript object
var countries = <?php echo json_encode($data); ?>;
$(document).ready(function () {
$('select[name="countries"]').change(function () {
var country_val = $(this).val();
if (countries[country_val]) {
var options = '<option value = "">Select State</option>';
for (i in countries[country_val]) {
var state = countries[country_val][i];
options += '<option value = "' + state + '">' + state + '</option>';
}
$('select[name="states"]').html(options);
}
});
});
</script>
<!--First Dropdown-->
<div class="country">
<select name="countries">
<?php foreach ($countries as $country): ?>
<option value="<?php echo $country; ?>"><?php echo $country ?></option>
<?php endforeach; ?>
</select>
</div>
<!--Second Dropdown-->
<div class="states">
<select name="states">
<option>Select State</option>
</select>
</div>
It will work. Follow step by step.
YourPage.php
<?
$country = array ("India" => array("Maharashtra","Tamil Nadu","West Bengal"),
"USA"=> array ("New York", "California"),
"Canada"=>array("Ontario", "Alberta", "Manitoba"));
?>
<div class='country'>
<select name="country_name" class="Country">
<?
foreach($country as $countryName => $states) {?>
<option value="<? echo $countryName;?>"><?echo $countryName?></option>
<?}?>
</select>
</div>
<div class="State">
<select>
<option>Select Country</option>
</select>
</div>
Add this code in your .js file.
<script>
$('.Country').change(function(){
var StateName= $('.Country').val();
$.ajax({url:"AjaxSelectState.php?CountryName="+CountryName,cache:false,success:function(result){
$('.State').html(result);
}});
});
</script>
AjaxSelectState.php
(Create this page. And, make sure if you want to change name of this page, change in <script></script> tag too. Both are related)
<?
$CountryName=$_GET['CountryName'];
$totalState=sizeof($country[$CountryName]);
?>
<select name="states_<?echo $CountryName;?>">
<?
for($i=0;$i<$totalState;$i++)
{?>
<option value="<?echo $country[$CountryName][$i];?>"><?echo $country[$CountryName][$i];?></option>
<?}?>
</select>
Try this:
// Build country array
$country = array ("India" => array("Maharashtra","Tamil Nadu","West Bengal"),
"USA"=> array ("New York", "California", "Florida"),
"Canada"=>array("Ontario", "Alberta", "Manitoba"));
// Output the country selection
echo '<select name="country_name" id="country_select">';
foreach($country as $countryName => $states) {
echo '<option value="'.$countryName.'">'.$countryName.'</option>';
}
echo '</select>';
// Output a select for the state selection per country
foreach($country as $countryName => $states) {
echo '<select class="state_dropdown" name="states_'.$countryName.'" style="display: none;">';
foreach($states as $state){
echo '<option value="'.$state.'">'.$state.'</option>';
}
echo '</select>';
}
Please note that this will actually create 4 selects. This is because depending on the selection for the first < select >, you should show the appropriate second < select >
Example Javascript:
This JS requires jQuery be loaded on your page before this code is run.
// When the document has loaded...
jQuery(document).ready(function(){
// Find the country select and listen for a change...
jQuery('#country_select').change(function(){
// When this change happens, hide all state fields
jQuery('.state_dropdown').hide();
// Get the country the user selected
var country = jQuery(this).val();
// And show only the state field they need to see.
jQuery('select[name=states_'+country+']').show();
});
});
I am trying to create a filter for a gallery that I've created. The gallery has 5 filters using dropdown menu's. When a item is selected from one of the 5 filters it has to filter the images. When a second filter is selected it has to filter the results of the first filter and so on.
I am using the onchange='this.form.submit()' script but I don't know how to assign a certain action to it when an item is selected. This is my code at the moment of writing:
<td>
Kleur:
<form method="POST">
<select name="kleur" onchange='this.form.submit()'>
<option> -- Geen optie -- </option>
<?php while ($line1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $line1['kleur']; ?>"> <?php echo $line1['kleur']; ?>
</option>
<?php } ?>
</select>
</form>
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
</br>
</td>
The following part doesn't seem to work:
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
Does anyone know how to use this script? and perhaps explain how to save the selected item in the dropdown menu too?
You can add an attribute with all the information you need to filter to your images
<img filterInfo="Kleur|Geur|Bloemvorm|Gezondheid|Type|Zoeken">
then set a class for all your filters to catch the changes
$(".filters").on("change",function(){
var kleur = $('[name=Kleur]').val();
var Geur = $('[name=Geur]').val();
...
...
...
$.each($('#gallery img'),function(i,v){
var attrs = $(v).attr("filterInfo").slice("|");
if((kleur == "" || kleur == attrs[0]) && (Geur == "" || == attrs[1]) .... other filters)
$(this).show(); //or fadeIn();
else
$(this).hide(); //or fadeOut();
});
});
I needed make a dinamic dependent dropdown in a form,so i found this solution that uses the JS auto-submit function:
function autoSubmit()
{
var formObject = document.forms['dados'];
formObject.submit();
}
then I use the onchange event in the first dropdown to call the auto-submit function:
<label>Campus:</label>
<select name="campus" onchange="autoSubmit();">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
with this the element "campus" will be setted to be used in the second dropdown SELECT statement:
$campus = $_POST['campus'];
...
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso">
<option VALUE="null"></option>
<?php
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
</select>
this code is working,but the problem is that in this way I cant set a action atribute in the form because if i do this every time the first dropdown changes it will redirect to the action's URL.this is the form that works:
<form name="dados" method="POST" onsubmit="return validar();">
with no action atribute I cant use a submit button to send the data of all the others elements to the right URL.there is a way to this?
You should use Ajax code to populate the second dropdown values.
On Form's page:
<label>Campus:</label>
<select name="campus" id="campus">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso" id="curso">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#campus').change(function(){
var campusName = $(this).val();
$('#curso').load('generateCurso.php?campus='+campusName);
});
});
</script>
Write a PHP file, called generateCurso.php
<?php
$campus = $_GET['campus'];
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
?>
<option VALUE="null"></option>
<?php
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
I solved this issue using a ajax script triggered by "on change" event.the ajax script call a external file that return an array of elements.the script use these elements to populate the dropdown list.