I'm having a little trouble with my code and I'm hoping someone can help. I'm trying to have the user select an option from a select box and then another select box to be based on that queries result. I know this should be simple but I can't seem to get it to work. Here's the code I've got so far.
The First select box:
select id="selCategory" name="category" class="chzn-select"<?php if (in_array('category',$_SESSION['iserror'])) {echo ' class="isError" ';} ?> >
<option value ="" ">
<?php
while ($row = hesk_dbFetchAssoc($res))
{
echo '<option value="' . $row['id'] . '"' . (($_SESSION['c_category'] == $row['id']) ? ' "' : '') . '>' . $row['name'] . '</option>';
}
?>
</select>
The second select box:
<select id="selAsset" name ="asset" class="chzn-select">
<option value="" selected="selected"></option>
<?php
while ($row = odbc_fetch_array($Assets))
{
echo '<option value="' . $row['AssetID'] . '"' . (($_SESSION['c_asset'] == $row['AssetID']) ? ' selected="selected"' : '')
. '>' . $row['AssetName']. '</option>';
}
odbc_close($conLansweeper);
?>
</select>
The code to handle if the second drop down box is displayed.
<script language="Javascript" type="text/javascript">$(function()
{
$(".selCategory").chosen().change(function(){
var selectedCategory=$(this).find("option:selected").val();
if(selectedCategory == "1")
{
$(.selAsset).show();
}
else
{
$(.selAsset).hide();
}
});
});
</script>
Footer Code:
<script type="text/javascript" src="script/chosen/jquery.min.js"></script>
<script type="text/javascript" src="script/chosen/chosen.jquery.js"></script>
<!--<script type="text/javascript" src="script/jquery/jquery-1.10.2.min.js"></script>-->
<script type="text/javascript">$(".chzn-select").chosen({disable_search_threshold: 10, width:200, placeholder_text_single:" ", search_contains: true, allow_single_deselect: true });</script>
The basic aim is for the second select box to be hidden when the page loads and the display when the appropriate value is selected in the first select box.
Can anyone help me out? I've not managed to get this working before and If i can get a working example and some help to show where I'm going wrong would really help.
Approach 1 (using existing html):
Hide with css:
#selAsset {
display:none;
}
Then jQuery:
$(function(){
var selCategory = $('#selCategory');
$(selCategory).change(function() {
$('option:selected').each(function() {
if($(this).text() === '3') {
jQuery('#selAsset').show();
}
});
});
});
This uses text() to check the selected option. In your code there is no need for .chosen() and you can change this: $(.selAsset).show(); to this: $('#selAsset').show(); (to match the html).
Demo: http://jsfiddle.net/dRM92/1/
A better approach (from comments):
We can use .change(function(){ and a switch case to check the option's value; then manipulate accordingly.
var selCategory = $('#selCategory');
var selAsset = $('#selAsset');
selCategory.change(function() {
switch ($(this, 'option:selected').val()) {
case "3":
selAsset.show();
break;
case "please select":
selAsset.hide();
break;
}
});
This is more extendable than the previous approach. There are many ways to check an option's value or text; for this instance we need to check the selected value only and the argument/s you wish to have.
Demo: http://jsfiddle.net/gzWGQ/1/
Related
I have created a drop down menu in php that is displayed however, when a value has been clicked, I don't know how to collect this information.
<html>
<body>
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
</body>
</html>
Based on your last comment, "i want it to be dynamic so as soon as the user clicks on something the relevant information will pop up", it sounds like you will probably want to use Ajax/JavaScript (I will demonstrate a simple jQuery example, notating for clarity):
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
?>
<html>
<!-- Add the jQuery library -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Act when the document is ready
$(function(){
// listen for the select to change
$('select[name=TeacherID]').on('change',function(){
// Run the ajax – you can also use the shortcut $.post method found at:
// https://api.jquery.com/jquery.post/
$.ajax({
// This is the page that is going to do the data lookup/display action
url: '/lookup.php',
// This is how it's sending the data to that page
type: 'post',
// This is what is being sent ($_POST['submit'] in this case)
data: {
// Use $(this) to isolate the current selected element and get value (.val())
// The value is represented as $topic in your php
'submit': $(this).val()
},
// If all goes well and the page (lookup.php) returns a response
success: function(response) {
// Place the response into the div (see html snippet)
$('#loadspot').text(response);
}
});
});
});
</script>
<body>
<?php
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
<!---------------------------------------------->
<!-- THIS IS WHERE THE CONTENT WILL LOAD INTO -->
<!---------------------------------------------->
<div id="loadspot"></div>
</body>
</html>
In order for this to work, you need the page lookup.php in the domain root (you can make it whatever/where ever you want, but you need to match in the javascript url):
/lookup.php
<?php
# This is what will get placed into the parent page <div id="loadspot"></div>
# Do you your php here in place of this line and return whatever "relative information" you want
print_r($_POST);
You should review the jQuery page I have linked to to get more information and direction for that library and make sure you use your browser's developer tools to monitor javascript errors in the console. Ideally, you want to understand all this via the documentation instead of just copy and paste and move on...
i have the code below that will change the image based on a dropdown
the image in db is stored example as mypicture.jpg and all thumbshot image is located at /images/thumbshots/
right now the image selected is displayed when we load the page but when changing the drop down the picture is not showing
i got
mydomain.com/mypicture.jpg instead of mydomain.com/images/thumbshots/mypicture.jpg
my code so far
echo "<label for='image'> Select Image File :</label>
<select name='image' id='selectsrc' class='form-control'>
<option value=''>Select Image </option>";
foreach(glob(dirname(__FILE__) . '/images/thumbshots/*.{jpg,png,gif}', GLOB_BRACE) as $image_db){
$image_db = basename($image_db);
if($image == $image_db) {
echo "<option value='" . $image_db . "' selected>".$image_db."</option>";
}
else
{
echo "<option value='" . $image_db . "'>".$image_db."</option>";
}
}
echo "</select></div>";
if ($image!='')
{
echo "<img src='images/thumbshots/$image' id='changesrc'>";
}
else
{
echo "<img src='".MY_URL."/images/blank.gif' id='changesrc'>";
}
?>
<script type="text/javascript">
var jQuery_1_9_1 =$.noConflict(true);
</script>
<script>
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1('#selectsrc').change(function(){
jQuery_1_9_1("#changesrc").attr('src',jQuery_1_9_1(this).val());
});
});
</script>
i think i need to change this code but im currently stuck with it..any input is much appreciated..thank you
<script>
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1('#selectsrc').change(function(){
jQuery_1_9_1("#changesrc").attr('src',jQuery_1_9_1(this).val());
});
});
</script>
As you are getting only image name you need to prefix your directory before name. And you dont need such a big selector jQuery_1_9_1 you can use simple one with single letter.
OR
Just add full path in option value then dont need any prefix your code will work in that case.
<script>
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1('#selectsrc').change(function(){
var img_path = 'images/thumbshots/' + jQuery_1_9_1(this).val();
jQuery_1_9_1("#changesrc").attr('src', img_path);
});
});
</script>
I'm trying to add a value from a selected in my html into a PHP file using jQuery. I have 2 php file, chainmenu.php and function.php. function.php contain 2 functions to get some data from my database. chainmenu.php is used to show the result of a function from function.php. It requires a variable, that is a value from selected option in my html. I was able to retrieve the value, but my problem is that my $.post function doesn't work. I dont know where is the error, is it in my chainmenu.php or in my function.php.
This is my code
jQuery CODE
<script type="text/javascript">
$(document).ready(function() {
$("select#trafo").attr("disabled","disabled");
$("select#gi").change(function(){
$("select#trafo").attr("disabled","disabled");
$("select#trafo").html("<option>wait...</option>");
var id = $("select#gi option:selected").attr('value');
$("select#trafo").html("<Option>"+id+"</Option>");
$.post("chainmenu.php", {id:id}, function(data){
$("select#trafo").removeAttr("disabled");
$("select#trafo").html(data);
});
});
});
</script>
Function.php
<?php class SelectList
{
//$this->conn is working fine here
public function ShowGI()
{
$sql = "SELECT * FROM gi";
$res = mysqli_query($this->conn,$sql);
if(mysqli_num_rows($res)>=1){
$category = '<option value="0">Pilih GI</option>';
while($row = mysqli_fetch_array($res))
{
$category .= '<option value="' . $row['idgi'] . '">' . $row['namegi'] . '</option>';
}
}
return $category;
}
public function ShowIt()
{
$sql = "SELECT * FROM It WHERE idgi=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Choose/option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['idIt'] . '">' . $row['name'] . '</option>';
}
return $type;
}
}
$opt = new SelectList();
?>
chainmenu.php
<?php include "/opsi.class.php";
echo $opt->ShowIt(); ?>
HTML Code
<head>
<!-- the script here -->
</head>
<body>
<select id=gi>
<option value="0"> Select </option>
</select>
<select id=It>
<!-- chainmenu.php result should be here -->
</select>
</body>
This explanation a little bit messy, but i hope anyone could help me and give me some good advice.
Thank you.
try like this in chainmenu.php
<?php include "/opsi.class.php";
echo $opt->ShowIt($_POST['id']); ?>
in function.php replace ShowIt() method like below,
public function ShowIt($id)
{
$sql = "SELECT * FROM It WHERE idgi=$id";
$res = mysql_query($sql,$this->conn);
$type = '<option value="0">Choose/option>';
while($row = mysql_fetch_array($res))
{
$type .= '<option value="' . $row['idIt'] . '">' . $row['name'] . '</option>';
}
return $type;
}
There are a few typos in ShowIt() function for e.g $type = '<option value="0">Choose/option>'; the tag isn't closed properly.
In the jquery code you are retrieving the value and adding the html to select tag having id trafo. whereas in html code the id of the select is It.
<select id=It>
<!-- chainmenu.php result should be here -->
</select>
i have a select with some options generated from content:
<select style="color: #444;">
<?php
$select_optd = 0;
foreach($DATA as $EACHOPTION){
// Checking some internal stuff, this works
if(IFISVALID){ // Now lets say it is valid, it will output some options
// Option echo
echo '<option';
// Some code to show the first option as selected and setting some
// later needed POST javascript variables
if($select_optd == 0){
echo ' selected="selected" ';
$select_optd = 1;
$show_ctrl_id = $EACHOPTION['id'];
$show_ctrl_spot = $EACHOPTION['spot'];
}
// echo the option html data
echo ' id="PRJ_OPT_'.$EACHOPTION['id'].$EACHOPTION['spot'].'" >';
echo $EACHOPTION['title'] . ' - Spot: ' . $EACHOPTION['spot'];
echo '</option>';
?>
<script type="text/javascript">
// Now the Javascript for when the option is selected
$(document).ready(function(){
$('#PRJ_OPT_<?php print($EACHOPTION['id']); print($EACHOPTION['spot']);?>').click(function(){
// An image showing the option selected
$('#PRJ_IMG_SHOW').attr('src','<?php print($EACHOPTION['image_url']); ?>');
// Some posting inputs for later on
$('#w_prj_id_send').val('<?php print($EACHOPTION['id']); ?>');
$('#w_prj_spot_send').val('<?php print($EACHOPTION['spot']); ?>');
// An alert to test if it's working
alert('Changed');
});
});
</script>
<?php
}else{ // that option was not valid, next one. }
} // End of Foreach
?>
</select>
The problem is this .click() event on the options is only working on firefox. I've tried on Chrome, IE... only works Firefox.
Is there any resolution or explanation for this problem?
// ----------------------------------------------------------------- //
RESOLUTION:
<script type="text/javascript">
$(document).ready(function(){
$('#prj_selector').change(function(){
var SELECTED_PRJ = $('#prj_selector').val();
<?php
foreach($DATA as $EACHOPTION){
?>
if(SELECTED_PRJ == '<?php echo $EACHOPTION['title'] . ' - Spot: ' . $EACHOPTION['spot']; ?>'){
$('#PRJ_IMG_SHOW').attr('src','<?php print($EACHOPTION['image_url']); ?>');
$('#w_prj_id_send').val('<?php print($EACHOPTION['id']); ?>');
$('#w_prj_spot_send').val('<?php print($EACHOPTION['spot']); ?>');
}
<?
}
?>
});
});
</script>
Because <select> is a control, not a normal element.
Use .change() instead on the select element itself.
For select boxes you can use the .change() event instead of .click
http://comp345.awardspace.com/select_element_cheatsheet.pdf
I am pulling out record from the database and inserting them inside a dropdown like this:
echo "<select>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option>" . $drow['id'] . "</option>";
}
echo "</select>";
It works but I need to be able to click on an option on the dropdown and make it link just like:
Record1Here
Record2Here
Record3Here
UPDATE: Latest code:
<script>
function doSomething() {
var currentval = this.options[this.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
</script>
...
echo "<select onchange='doSomething();'>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option value=\"view.php\">" . $drow['id'] . "</option>";
}
echo "</select>";
You can't place anchors on an option within a select list.
What you can do is use JavaScript and then do something on the change event of the select list :
echo "<select onchange='doSomething(this);>';
then in JavaScript do something based on the selected value :
function doSomething(elem) {
var currentval = elem.options[elem.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
Example here
you could update your PHP code to include a value in each option :
echo "<option value=\"urlhere.php\">" . $drow['id'] . "</option>";