Auto-populate two input boxes from a dropdown menu - javascript

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.

Related

Value disappear after dropdown selected

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.

how can i generate dynamic textboxes and labels depend on the selection on a popup menu

sorry but i am new here and i don't know php very well. I would like to ask how can i generate dynamic textboxes and labels depend on the selection on a popup menu. I want to make a site in wordpress that would have a popup menu that shows titles of the Thesis. I have a database with an array named wp_courses and there are course_id, Thesis_ID, course_title in it ,and an other array named Thesis with Thesis_ID,Thesis_Title.i want when a thesis is chosen to generate textboxes with the specific courses that the thesis have and labels with the title of the courses, to fill. I am confused how can i pass my database in the function.Can i do it with javascript?
//my php code so far
function showTextboxes(choise){
for(i=0;i<=choise;i++)
{
my_div.innerHTML = my_div.innerHTML +"<br>
<input type='text' name='mytext'+ i>";
}
$conn = mysqli_connect("localhost","root","","wordpress");
mysqli_query($conn,'SET NAMES utf8');
<label class='formLabel'>Title of thesis*</label><br />";
$query = "SELECT * FROM wp_thesis";
$result = mysqli_query($conn,$query);
echo"<select name='ThesisTitle' id='link_block' onChange='showTextboxes(this.selectedIndex);' required=''>
<option disabled='disabled' selected='selected' value=''></option>";
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}> {$row[Thesis_Title]}</option>";
}
echo"</select><br />";
<div id="my_div"></div>
It is generally a very good idea to separate your data from the front-end code.
Such as returning it as JSON string.
PHP has a built in function json_encode to do this with mysql results : https://stackoverflow.com/a/383664/5335350
JSON/Object example:
var Thesis = [{
Thesis_ID: 0,
Thesis_Title: 'My thesis title1'
}, {
Thesis_ID: 1,
Thesis_Title: 'My thesis title2'
}, {
Thesis_ID: 2,
Thesis_Title: 'My thesis title3'
}]
With that data is very simple to now accomplish what you want with a little JS & HTML
HTML :
<div id="courses">
<table>
<tr></tr>
</table>
<hr/>
<label for="course">Select course: <span></span>
<input name="course">
</label>
<select class="form-control" name="userName">
<option></option>
</select>
</div>
JS:
mag.module('courses', {
view: function(state) {
state.option = Thesis.map(function(thesis) {
return {
_selected: thesis.Thesis_ID == state.index ? true : null,
_text: thesis.Thesis_Title,
_value: thesis.Thesis_ID
}
});
state.select = {
_onchange: function(e) {
var i = e.target.selectedIndex
state.span = Thesis[i].Thesis_Title + ' ID:' + Thesis[i].Thesis_ID
}
}
}
});
Here is the full working example: http://jsbin.com/qafupozemu/1/edit?html,js,output
Hope that helps!

How to fill Textbox using dropdownlist

Please help me.. i have dropdownlist which i have populated from the database table, now i want to fill textbox from the database list...
i have one table
id | juice | rupees
now when i select Mango Juice from juice column from dropdownlist it should show the cost of Mango Juice in textbox by retrieving from rupees column
here is the dropdownlist which is populated from the table
<select name="drink" id="drinkid">
<option id="0">-- Select the drink --</option>
<?php
require("dbcon.php");
$getalldrinks = mysql_query("SELECT * FROM tableone");
while($viewalldrinks = mysql_fetch_array($getalldrinks)){
?>
<option id="<?php echo $viewalldrinks['id']; ?>"><?php echo $viewalldrinks['juice'] ?></option>
<?php
}
?>
</select>
and here is the textbox
<input type="text" name="juicename" id="juiceid" placeholder="Juice">
Please help me.. thanks in advance.
First add onChange() event to your select tag to call function fillTextBox() every time you change option, then the function will fill the textbox:
<select name="drink" id="drinkid" onChange="fillTextBox()">
Now you have to get rupees column & store it in every option using data attribute :
<option data-rupees="<?php echo $viewalldrinks['rupees']; ?>" id="<?php echo $viewalldrinks['id']; ?>" ><?php echo $viewalldrinks['juice'] ?></option>
Create the function fillTextBox() that will fill the textbox by rupees value of selected option :
function fillTextBox(){
var myselect = document.getElementById("drinkid");
var rupees = myselect.options[myselect.selectedIndex].getAttribute("data-rupees");
document.getElementById("juiceid").value = rupees;
}
That should do the work, hope this helps.
You'll need to use javascript to detect changes in your select box, store those values, and then populate the text box with the desired values. You haven't listed a text box in your html, so I'll have to assume that I can access this value using input[type=text]. Here's an approximation of what your javascript should look like given that I am working with incomplete information. Note that your should probably contain an attribute called value to store your id instead of using the id attribute.
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.querySelectorAll('input[type=text]')[0].value = data.text;
});
You'll need to provide more detail and more of your code if you want an exact solution to your problem.
UPDATE: I see you've added the text box HTML, so here's the updated version of the event handler:
var el = document.getElementById('drinkId');
el.addEventListener("click", function(){
var data = {"id": el.value, "text": el.innerHTML};
document.getElementById('juiceId').value = data.text;
});

Three dropdown menus responding to eachother

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
}
);
});

Populate html dropdown list dynamically from other dropdown

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

Categories