I have 3 dropdown lists like this:
The code I have for this is as follows:
<td class="tditemlabel">Category*</td>
<td>
<select id='catselect' class='catselect' name='catselect' onclick="document.getElementById('subcatselect').disabled=false">
<option value="0">--Select a category--</option>
<?php getAllCategories(); ?>
</select>
</td>
<td class="formhelp">Choose item category</td>
</tr>
<tr>
<td class="tditemlabel">Subcategory*</td>
<td>
<select id='subcatselect' class='catselect' name='subcatselect' disabled onclick="document.getElementById('subsubcatselect').disabled=false">
<option value="0">--Select a subcategory--</option>
</select>
</td>
</tr>
<tr>
<td class="tditemlabel">Sub-subcategory*</td>
<td>
<select id='subsubcatselect' class='catselect' name='subsubcatselect' disabled>
<option value="0">--Select a sub-subcategory--</option>
</select>
</td>
</tr>
The data in the dropdown boxes is correctly fetched from my MySQL database. So, based on what is selected in the category dropdown list, the second one enables and the data is correctly inserted there. No problems so far.
At this point I encounter a couple of problems:
The first one is when for example (as soon in the picture below) is when I select the 'electronics' category, the subcategory list enables and shows me the 3 possible values it has ('computers&tablets','smartphones','photography'), now as can be seen, the first option is automatically selected and thus the 3rd dropdown list is not automatically enabled and filled with content. And clicking on this first one does not work either, i have to click on another one and then click again on the first one to see its contents in the 3rd dropdown.
A solution could be to add a 'dummy-option' everywhere, however this seems like a somewhat bad use case in my example. Since I have 9 categories, which all have 2 to 3 subcategories, and these subcategories all have 3 to 4 subcategories on their turn. If i have to add 'select a subsubcat' in every dropdown list (with e.g. 2 items) this seems a lot of useless information. (Could anyone provide me a solution to this? if not could anyone also explain me how to get this dummy text everywhere since I only know how to do that if it is in the database as well.)
And so we come to my second problem is let's say a user clicked on a category, a subcategory and a sub-subcategory, but now he wants to change the category again, this is what happens:
How can I disable again the sub-subcategory dropdown lists when the user changes category (and instantly enable the correct subcategory list)
The JQuery code I have so far is this:
$("#catselect").on("change", function() {
var categoryid = document.getElementById("catselect").value;
$.post('category_list.php', { catid: categoryid }, function(result) {
$('#subcatselect').html(result);
}
);
});
$("#subcatselect").on("change", function() {
var subcategoryid = document.getElementById("subcatselect").value;
$.post('subcategory_list.php', { subcatid: subcategoryid }, function(result) {
$('#subsubcatselect').html(result);
}
);
});
and the PHP code:
'category_list.php' (the 'subcategory_list.php' file is pretty much the exact same)
<?php
require 'includes/functions.php';
$cat_id = $_REQUEST['catid'];
if ($cat_id != 0)
{
$result = db_query("SELECT categoryid, name FROM category WHERE parent = '$cat_id'");
}
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['categoryid'] . '">' . $row['name'] . '</option>';
}
?>
VERY EDITED (context remains):
First thing first, you PHP is SQLinjection-ready... You send the input from your select (catid) directly to the db... Change it... Make sure it's numeric before you create your query.
Also, if your query never gets executed, you will probably get an exception when trying to fetch rows... So put it all under if:
$cat_id = $_REQUEST['catid'];
if ( is_numeric($cat_id) && $cat_id != 0 ) {
$result = db_query("SELECT categoryid, name FROM category WHERE parent = '$cat_id'");
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['categoryid'] . '">' . $row['name'] . '</option>';
}
}
Now, let's take it to your question. This is the full javascript you should need.
var subcat = '<option value="0">--Select a category--</option>';
var subsubcat = '<option value="0">--Select a sub-subcategory--</option>';
// ^^ these should be placed in the new controls
$("#catselect").on("change", function() {
$.post('category_list.php',
{ catid: categoryid },
function(result) {
$('#subcatselect').html(subcat+result);
$('#subcatselect').change();
}
);
});
$("#subcatselect").on("change", function() {
$.post('subcategory_list.php',
{ catid: subcategoryid },
function(result) {
$('#subsubcatselect').html(subsubcat+result);
$('#subsubcatselect').change(); // I guess you don't need this
}
);
});
Related
I am trying to fetch two variables from a mysql db table which is supposed to auto-populate once a user selects a dropdown option.
The dropdown menu will show a list of teams and the input boxes will display the names of the Captain and the Vice-Captain once the team is selected (actually it will only capture their MemberID in the backend and save them in a table)
I had been able to fetch the name of one Captain, using a Javascript function and Ajax. That part is working fine.
What I am after is getting the second captains name/id.
My HTML/PHP code is here:
<script type="text/javascript" src="js/capt-dropdown.js"></script>
...
<table>
<?php $x = 0; ?>
<tr style="background-color:#FFF9C4">
<td>Select Team: </td>
<td><select name="teamcode" id="teamcode">
<option disabled selected value> - Select Team - </option>
<?php $sql_select = mysqli_query($conn, "SELECT teamcode, team FROM team");
while ($row = mysqli_fetch_assoc($sql_select)){
echo '<option value = " '.$row['teamcode'].'"> '.$row['team'].' </option>';
} ?>
</select>
</td>
</tr>
<tr>
<td>Captain 1: </td>
<td><input type="text" name="captain1" id="captain1"></td>
</tr>
<tr>
<td>Captain 2: </td>
<td><input type="text" name="captain2" id="captain2"></td>
</tr>
</tr>
</table>
The JS file: capt-dropdown.js
$(document).ready(function() {
$("#teamcode").change(function() {
var team = $(this).val();
if(team != "") {
$.ajax({
url:"get-captain.php",
data:{teamcode : team},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#captain1").html(resp);
}
});
} else {
$("#captain1").html("<option value=''>--- Select ---</option>");
}
});
});
The php file: get-captain.php is here:
if(isset($_POST['teamcode'])) {
$teamcode = trim($_POST['teamcode']);
$sql_select = mysqli_query($conn,"SELECT surname, preferred_name, memberid FROM member WHERE memberid in
((SELECT captain FROM captain WHERE year = YEAR(CURDATE()) AND teamcode = '$teamcode'),
(SELECT vcaptain FROM captain WHERE year = YEAR(CURDATE()) AND teamcode = '$teamcode'))");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['preferred_name']);
echo '<option value = " '.$result['memberid']. '">'.$name.'</option>';
}
}
Member table contains the name, surname and member-id of members
Captain table contains historic data of team captains
Captain table
The query in get-captain.php is working, and is able to retrieve the captain and vcaptain’s names & ids.
Read several posts but couldn't find anything similar to what I am doing here.
Can anyone please suggest how to fetch the second captains (the vice-captains) details? (ie. Display his name and capture his member-id)
Pls Note: this is an extract of a form which contains lot of other information, hence my apologies if I missed a line while cutting & pasting here)
Thank you in advance.
Sorry I cannot comment yet due to my rep, but captain 1 & 2 are inputs why are you trying to echo out option tags and insert them inside captain1.
You should change get-captain.php to fetch an associative array and echo json_encode($array); Your javascript can then parse json array
var array=JSON.parse(response);
finally putting your array values inside your input
$("#captain1").html(arr[0]["surname"] + "," + arr[0]["preferred_name"]);
$("#captain1").val(arr[0]["memberid"]);
$("#captain2").html(arr[1]["surname"] + "," + arr[1]["preferred_name"]);
$("#captain2").val(arr[1]["memberid"]);
If your dealing with more than 2 captains then you can just loop through your array and add a counter. Hope this makes sense i've never been good at explaining.
I've searched around to find the answer of my problem but I didn't find any.
I have a table contain 2 columns: kode_barang (Item ID) and nama_barang (Item Name). Kode_barang is a dropdown option which it's data populated dynamically from another table. Each time user select an option, the name of the item will appear automatically.
Here is my code:
<td>
<select name='kode_barang' type = "text" id='kode_barang1' onchange="changeValue(this.value)">
<option>Choose</option>
<?php
$sql="SELECT * FROM input_data_barang ";
$result=mysql_query($sql);
$met = "var kode_barang = new Array();\n";
while ($row = mysql_fetch_array($result)) {
$id=$row["kode_barang"];
echo "<OPTION VALUE=$id>$id</option>";
$met .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
?>
</select>
</td>
<td><input type="text" name='nama_barang' id="nama_barang1"/readonly>
<script type="text/javascript">
<?php echo $met; ?>
function changeValue(id){
document.getElementById('kode_barang1').value = kode_barang[id].name;
document.getElementById('nama_barang1').value = kode_barang[id].desc;
};
</script>
</td>
Dropdown option and Item ID appear perfectly. The problem is, when I select an Item ID, the name of the ID (nama_barang) appear automatically, but then the Item ID disappear. The dropdown become blank. I need the Item ID persist after option selected so the ID can be saved to the database.
Anybody please help me.
The issue that I can see is that you are assigning kode_barang1 the name stored. kode_barang1 is the name of a SELECT object which uses numbers for the ID so when you assign it, it goes to NULL because a name doesn't exist in the <OPTION>.
Create a new input variable called kode_barang2 and change
document.getElementById('kode_barang1').value = kode_barang[id].name;
to
document.getElementById('kode_barang2').value = kode_barang[id].name;
And you will see that would work.
I'm new at this and i'm asking for help.
Here is the rundown. it's a web-shop with an P.O.S ( Point of Sale) interface . when the cashier logs in the POS interface , i need to auto-select a category ( let's say i have two distinct categories of products, identical in products , one is for online sales and other is for the cashier . when the cashier sells a product, i don't want him to sell by mistake a product identical in name but meant for online sales. so i need to auto-select a given category and run the submit button once
This is the original code that pulls out the category lists as a drop down from the database.
<select class="form-control category-selector" id="cramadevapat" name="category" placeholder="<?php echo JText::_('COM_POS_PRODUCTS_INPUT_SEARCH_CAT_PLACEHOLDER') ?>">
<option value=""><?php echo JText::_('COM_POS_PRODUCTS_INPUT_SEARCH_CAT_PLACEHOLDER') ?></option>
<?php
foreach($items as $item){
$selected = (isset($params->category) && $params->category == $item->category_id) ? 'selected' : '';
echo '<option value="'.$item->category_id.'" '.$selected.'>'.$item->category_name_with_depth.'</option>';
}
?>
</select>
This is what I've been able to do so far.
function selectFromDropdown(selector, text) {
$(selector).find('option').each(function() {
if ($(this).text() == text) {
$(selector).val($(this).val());
return false;
}
})
}
setTimeout(function() {
selectFromDropdown('#cramadevapat', 'Magazin Pallady')
jQuery(function(){ jQuery ('#submit').click();});
},500)
Here's what I've manage to do so far, but now the code lock in the drop down list, selects the thing I need, and then it runs it over and over again.
All I need is this to run only submit only once
I'm not really sure what exactly you are trying to do there but you could assign the timer to a variable and then stop the timer once it triggered:
myTimer = setTimeout(function() { ........
clearTimeout(myTimer);
Can anyone guide me to get a solution. For example , there is a dropdown down in the form contains some animals name. If the user select the one animal from that, it saved in dropdown. Again in selection process, that saved data want to become disabled. The other options only able to select. This is the solution i want.
You can achieve this with a helper method for your view, or you could set instance variables in your controller but here is some pseudo code to get you going.
def disabled_animals
Animal.where(already_selected: true).pluck(:name)
end
def selectable_animals
Animal.all.pluck(:name) - disabled_animals
end
the idea is to get 2 arrays, one without the disabled animals and one with the disabled animals and pass those to your select helper method, then you could do something like this in your view.:
select("post", "animal", selectable_animals, {disabled: disabled_animals})
Which would produce this:
<select name="post[animal]" id="post_animal">
<option value=""></option>
<option value="joke">joke</option>
<option value="poem">poem</option>
<option disabled="disabled" value="zebra">zebra</option>
</select>
Reference: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
Highlevel idea:
Get selected value from UI and pass it to mysql query to exclude it
Code:
Get value from dropdown through jQuery:
var selectedAnimal = $('.animals').find('#animal option:selected').text().trim();
Please change according to your UI
Pass selected animal in query to exclude it
$sql = "SELECT DISTINCT `animal` FROM " . $animalTable . " where animal <> '<selectedAnimal>';
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);
if ( $num_rows > 0 ) {
for ($row_no=1; $row_no <= $num_rows; $row_no++) {
$row = mysqli_fetch_array($result);
$dropdown.= "<option value='" .$row['animal']. "'>" .$row['animal']. "</option>";
}
}
echo "<select class='dropdownselect' id='animal'> " .$dropdown. "</select>";
Please change according to your query and language used
I have two dropdown lists, the first is populated from database and works fine, the second dropdown must be populated dynamically from what user has chosen from the first dropdown list. For example, my first dropdown contains many country's name, when user choose a country, the second dropdown will be populated by city's of that country which are in same database. Have anyone an example of this?
This is the first dropdown list
<select size="1" name="listeOrg">
<option value = "0" selected>---Choisir une région---</option>
<?php
$link3 = mysql_connect_db();
$query3 = "SELECT nom_region FROM region ";
$result3 = mysql_query($query3, $link3) or die();
while ($row = mysql_fetch_array($result3)) {
echo '<option value="'.$row['nom_region'].'">'.$row['nom_region'].'</option>';
}
mysql_close($link3); ?>
</select>
And the second:
<?php
$link4 = mysql_connect_db();
$selectregion=$_POST['listeOrg'];
$query4 = "SELECT organisme FROM region_organisme where nom_region='$selectregion' ";
$result4 = mysql_query($query4, $link4) or die();
while ($row2 = mysql_fetch_array($result4)) {
echo '<option value="'.$row2['nom_region'].'">'.$row2['nom_region'].'</option>';
}
mysql_close($link4); ?>
<option value="1" >autre
</select>
I found finally a good solution with a proper code. This is the link to the tutorial if someone has been stacked on this case.
A good explained tutorial with demo