I have a form with text boxes and drop down menus. One of the drop down menus is Dependant on the value of another, e.g. InventoryUsage is dependent on the value in InventoryID.
So far I have done the entire site using PHP since I do not know JavaScript, though I found a JavaScript function that can get the value entered in InventoryID, but I cannot use that value in the PHP since PHP is server-side.
What I need to do is change the second dropdown options depending on that of the first dropdown. Then submit the data as I would with a normal form.
Edit:
I used ob_start and included the tpl page and sent all the variables to the page which were pulled from the database prior. All the variables have the same index meaning that InventoryID['0']=ID3456 corresponds to InventoryUsage['0']=60. Therefore when InventoryID is ID3456 i would like to display the Number located at InventoryUsage['0']. I hope this adds some context to the problem.
The index is determined by the php variable $i in my code snippet. The $i would be changed to match the index of the InventoryID field. Say the value of InventoryUsage is 20 then I want to display numbers 1 to 20.
Snippet of code below:
<label>TypeOfSurgery</label> <input type="text" name="TypeOfSurgery" size="35" value="" />
<label>CauseOfSurgery</label> <input type="text" name="CauseOfSurgery" size="35" value="" />
<label>AnaesthesiaUsage</label> <input type="text" name="AnaesthesiaUsage" size="35" value="" />
<label>SurgeryOutcome </label> <input type="text" name="SurgeryOutcome" size="35" value="" />
<label>RecoveryTime</label> <input type="text" name="RecoveryTime" size="35" value="" />
<label>Stages </label> <input type="text" name="Stages" size="35" value="" />
<label>EmployeeName </label> <p>
<select name="EmployeeName">
<option value=""></option>
<?php
for($i=0;!empty($EmployeeName[$i]);$i++)
echo '<option value="">'.$EmployeeName[$i].'</option>';
?>
</select><p>
<label>Cost</label> <input type="text" name="Cost" size="35" value="" />
<label>InventoryID</label> <p>
<select name="InventoryID">
<option value=""></option>
<?php
for($i=0;!empty($InventoryID[$i]);$i++)
echo '<option value="">'.$InventoryID[$i].'</option>';
?>
</select><p>
<label>InventoryUsage </label> <p>
<select name="InventoryUsage">
<option value=""></option>
<script type="text/javascript">
var model= document.getElementById('InventoryUsage');
</script>
<?php
//if inventory in
for($i=0;!empty($InventoryUsage[$i]);$i++)
echo '<option value="">'.$InventoryUsage[$i].'</option>';
?>
</select><p>
In order to populate the InventoryUsage dropdown you need to use JavaScript.
You can use the onChange event for the dropdown InventoryID then fetch the corresponding values via Ajax.
$('#InventoryID').change(function () {
var value =$(this).val(); // selected InventoryID option
//get InventoryUsage values
$.ajax({
method: "POST",
url: "myfile.php",
data: { data: value },
success: function(data){
// Populate new dropdown $("#InventoryUsage")
// this is an example without knowing what is the returned data
var Newoptions = [];
for (var i = 0; i < data.length; i++) {
Newoptions.push('<option value="',
data[i].someValue, '">',
data[i].someName, '</option>');
}
$("#InventoryUsage").html(Newoptions .join(''));
}
});
});
});
then in your PHP file you need to handle the $_POST['data'] , then query your database and return the drop-down options( Arrays ) that will be populated above...
edit :
If you are sure that this index matches the Inventory_Usage and that the InventoryUsage dropdown has previously been populated then
you could try to select the InventoryUsage option using the index of the InventoryID dropdown on change and load events...
try adding this function to you select :
<select name="InventoryID" onChange="set_inventory_usage()"></select>
then add this script to your page's HEAD section..
<head>
<script type="text/javascript">
function set_inventory_usage(){
// Change to getElementById if it is the ID not the name
var Inventory_ID = document.getElementsByName('InventoryID')[0];
var Inventory_Usage = document.getElementsByName('InventoryUsage')[0];
// returns the index of the selected option in the InventoryID dropdown
var InventorySelected = Inventory_ID.selectedIndex ;
// Sets the Usage dropdown to the same index as the Inventory selected option
Inventory_Usage.selectedIndex = InventorySelected ;
}
window.onload = set_inventory_usage ;
</script>
</head>
Option 1: Without JavaScript, the best option is to add an onchange to your first dropdwon list, and when a value is selected submit the form. Since the form is not complete, and only the dropdown value and elements before that are passed, you can set a condition to query the database, get values based on first drop down and reload the form with those options. IThere is nothing wrong with this solution if done properly but to be honest I perfer to do such things with Ajax, hence option 2 below.
Option 2: Learn some JavaScript and use Ajax (Use caution when using other people's scripts in your system)
Edit: Perhaps instead of wring Ajax code from scratch, use jQuery where most things are already done for you. Learning jQuery is very useful if you are going to do web development
Related
I have an issue with the code below where the floating label stops working when executing the php script via function "loadStaff". The floating label works prior to the execution of the php script. My limited knowledge suggests that the issue is caused by the option select value not being passed on to the angular model which in turn did not trigger the floating label since the option select retains the selected value ($('select#account_list').val('<?php echo $_POST['account_list'];?>') as I can see it showing up. However, the floating label is not executing even though I see the selected value in the option select field. How do we pass the selected value to the angular model for it to trigger the floating label? I could be wrong with my reasoning.
<div ng-app="myApp">
<form id="orderformstaff" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<div class="field" style="width: 100%">
<label class="show-hide" ng-show="account">Account</label>
<div class="input-group mb-4">
<span class="input-group-addon gi gi-user-key"></span>
<select id="account_list" class="form-control custom-select" name="account_list" ng-model="account" onchange="loadStaff()" autocomplete="on" required/>
<?php
$a_list = $DB_CON_A->query("SELECT `id`, `email` FROM `staffs` ORDER BY `id` ASC");
$data_row = '<option value="" disabled>Choose an account</option>';
if($a_list !== false) {
foreach($a_list as $row){
$data_row .= '<option value="'.$row['email'].'">'.$row['email'].'</option>'."\n";
}
}
unset($row);
echo $data_row;
?>
</select>
</div>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-animate.js"></script>
<script> var myApp = angular.module('myApp', ['ngAnimate']);</script>
<script>
function loadStaff() {
var form =
document.getElementById('orderformstaff');
form.submit();
};
</script>
<script type="text/javascript"> <!--allows option select to retain value after executing loadStaff-->
$(document).ready(function(){
$('select#account_list').val('<?php echo $_POST['account_list'];?>');
});
</script>
Actualy you don't need using AngularJS because did all jobs with PHP.
However if you want to fix current code
REMOVE
$('select#account_list').val('<?php echo $_POST['account_list'];?>');
THEN set attribute on select element
<select id="account_list" class="form-control custom-select" ng-init="account = <?php echo $_POST['account_list'];?>" name="account_list" ng-model="account" onchange="loadStaff()" autocomplete="on" required/>
EDIT
If you want to use AngularJS you should bind data with angularjs not with PHP.
If there is no JQuery you cannot use $(document).ready etc...
If you want to start learn AngularJS, you can start from here http://www.journaldev.com/7750/angularjs-simple-forms-tutorial
It use PHP on back-end.
I am trying to update two cascading drop down inside a table there are many answers on SO for drop downs, but I was unable to find help on cascading updates inside a Table with dynamically added rows.
Given the many rows they all have varying Id's filter #Id does'nt work. So, How do I identify which rows Dropdown triggered the change & cascade the update another Dropdown/cell in the next col of the same row?
There are 2 DropDownList (select box) inside a table row cell. To simplify this, the first is Country -> Second is state. So a user is expected to select the country and then the state.
My pseudo algorithm:
find which one was fired, and which row (unsure if its needed, should I wire in place)
then fire an ajax call... to get the values based on country
update the second drop down with value in the same table row.
Case 1 Change country and then change state.
Case 2 Just change State, but first get the Country value in the first dropdown of the same row.
I know how to get the change and value in a regular page, but how do I get those changes and update the adjacent dropdown.
$(document).on('change', 'select', function(){
var data = $(this).val();
alert(data);
});
Edit, Stephen request to show HTML
<tr>
<td>
//DropDown 1 (Imagine Country)
<span class="projectcodeid">
<select class="form-control" id="Records_1__TCode_Project_ID" name="Records[1].TCode.Project.ID"><option value=""></option>
<option value="1">Plumbing</option>
<option value="2">Modeling</option>
</select></span>
</td>
<td>
//DropDown 2 (Imagine State)
<input type="hidden" name="Records.Index" value="1">
<input class="timecodeid" name="Records[1].TCode.ID" type="hidden" value="5">
<span class="timecode timecodeDdlId"> <select class="form-control timecodeDdlId" id="Records_1__TCode_ID" name="Records[1].TCode.ID"><option value=""></option>
</select></span>
</td>
<td>
<input name="Records[1].DataRecords[0].ID" type="hidden" value="">
<input class="hours" name="Records[1].DataRecords[0].Work" type="text" value="">
</td>
<td>
<input class="bs-checkbox" name="Records[1].DeleteRow" type="checkbox" value="true"><input name="Records[1].DeleteRow" type="hidden" value="false">
</td>
</tr>
Sample image for clarification
Assuming that you can't identify dropdwns by class or anything.
Assuming that every time you change the value in a dropdown you want to update the other dropdown on the same row.
Assuming that you have only two dropdowns per row:
$('table').on('change', 'select', function() {
var $current_dropdown = $(this),
$other_dropdown = $(this).closest('tr').find('select').not(this);
/// perform any task you need with current and other dropdown
});
You need to give both your <select> elements class names and use relative selectors to select the associated element in the same row.
Assuming your html is
<table id="table"> // give this an id attribute
<tbody>
<tr>
<td><select class="country" ....> ..... </select></td>
<td><select class="state" ....> ..... </select></td>
</tr>
</tbody>
</table>
Then your script will be
$('#table').on('change', '.country', function() {
var selectedValue = $(this).val();
var row = $(this).closest('tr'); // get the row
var stateSelect = row.find('.state'); // get the other select in the same row
// make you ajax call passing the selectedValue to your controller
// in the success callback, update the options of stateSelect
$.ajax({
url: ...
data { id: selectedValue },
....
success: function(data) {
stateSelect.empty();
$.each(data, function(item, index) {
stateSelect.append($('<option></option>').val(iem.ID).text(item.Name));
}
}
});
}
Refer also better way to load 2 dropdown in mvc for details of the code for populating cascading dropdownlists (consider caching the options as per the 2nd code example to avoid repeated ajax calls)
I need to update one dropdwonlist without reload the page, I mean, I have a form where I add the elements that I need, then I have another form where I have the dropdownlist conected to my database but if I do not have the element I need to select, I have to add it from the other form, but the problem is that i need to reload the page in order to the dropdownlist show the new element then I loose the data I was typing.
I wish to know a way to update the dropdownlist without reload the page.
Im using php and mysqli my code is simple:
<form action="edit_col_exe.php" method="post">
<p><label>Add Element:</label>
<input autofocus type="text" name="elemnt" class="input" required />
</p>
<table>
<tr>
<td><input type="submit" name="Save" value="Save" /></td>
</tr>
</table>
</form>
Form2:
Select Element
query("select * from Elements order by Element asc") or die("fail");
echo "Select an option";
while($reg=$con ->fetch_assoc()){
echo "";
echo $reg['Element'];
}?>
I hope someone can help me!
regards!
Use Ajax (I prefer jQuery) and remove your form.
JS
function addElement(){
// get new name
var name = $("#newElementsName").val();
// create ajax call
$.ajax({
type: "POST",
url: "edit_col_exe.php", // URL to php script
data: { // post data for php script (I use the data from your form (including the typo))
elemnt: name,
save: 'Save'
},
success: function(data){
// this function will be called when php script run successful (HTTP-Status 2xx)
// Clear the input filed
$("#newElementsName").val('');
// Add new name to dropdown
$("#elements").append("<option>"+name+"</option>");
}
});
}
HTML
<div>
<p><label>Add Element:</label>
<input autofocus type="text" id="newElementsName" class="input" required />
</p>
<table>
<tr>
<td><button type="button" onclick="addElement()">Save</button></td>
</tr>
</table>
</div>
<div>
<select id="elements" size="1">
</select>
</div>
I solved my problem and I want to share with you my solution, its simple:
setInterval(function(){
$('#searchelement').load('addelements.php');
});
<p><label>Element</label>
<select id="searchelement" name="element" required />
</option>
</select></p>
So everytime I add an element at 'addelements.php', I can search the new element in the select list.
I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]
Hi I have a form that has a button used to prefill my form with data from my database. Using Json It works fine to populate text inputs but how do I get it to select a radio button based on the value returned from my database?
FORM
<form action="#">
<select id="dropdown-select" name="dropdown-select">
<option value="">-- Select One --</option>
</select>
<button id="submit-id">Prefill Form</button>
<input id="txt1" name="txt1" type="text">
<input id="txt2" name="txt2" type="text">
<input type="radio" id="q1" name="q1" value="4.99" />
<input type="radio" id="q1" name="q1" value="7.99" />
<button id="submit-form" name="Submit-form" type="submit">Submit</button>
</form>
SCRIPT
<script>
$(function(){
$('#submit-id').on('click', function(e){ // Things to do when
.......
.done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
$('#q1').val(data.q1);
});
});
});
</script>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
........
while ($row = mysqli_fetch_assoc($result))
{
echo json_encode($row);
die(); // assuming there is just one row
}
}
?>
Don't use ID because you have same ID of both radio buttons
done(function(data) {
data = JSON.parse(data);
$('#txt1').val(data.txt1);
$('#txt2').val(data.txt2);
// Don't use ID because the name of id is same
// $('#q1').val(data.q1);
var $radios = $('input:radio[name=q1]');
if($radios.is(':checked') === false) {
$radios.filter('[value='+data.q1+']').prop('checked', true);
}
});
You currently have both radio buttons using the same ID. ID's should be unique.
You can use the [name] attribute to do this, or you can set a class on the element. Here is an example:
$('input[name=q1][value="'+ data.q1 +'"]').prop('checked', true);
You can do it based on the value of said input:
instead of
$('#q1').val(data.q1);
Try
$('input:radio[value="' + data.q1 + '"]').click();
On a side note, you have both radios with the same ID, the results of an id based selector are going to vary from browser to browser because an id should be UNIQUE
you can refer the following link to solve your problem. works fine for me
JQuery - how to select dropdown item based on value