PHP/Javascript to update input fields - javascript

OK, So not a big HTML or Javascript person. But I am doing what I can to get by.
I am working on a project for a Marine Cadets Explorers Post to create a online database for them to help manage their membership and other functions. In entering their membership records they will have multiple families that will have several kids in the post, so they don't want to have to re-enter their parents records. I wanted to create a drop down box that is populated by a SQL Database lookup (Which I did) and then, if they select a parent from that list, the form will populate, saving the entry.
I only provided a snipped of the HTML, since the form has over 50 fields and for example, I only really need to show one.
So the HTML is below.
<form name="YouthApp" class="form-application" method="post" id="application-form">
<div style="height:0.20in; left:1.75in; overflow:hidden; padding:2px; position:absolute; top:4.10in; width:1.48in; ">
<select name="selSupp" style="width:1.46in;">
<option value="">Existing Supporters</option>
<?php makeSuppDropdown() ?>
</select>
<div style="height:26px; left:0.36in; overflow:hidden; padding:2px; position:absolute; top:4.52in; width:353px; ">
<input style="height:0.20in; width:3.64in; " name="SuppFirst" required value="<?php if(isset($_POST['SuppFirst'])){ echo $_POST['SuppFirst']; } ?>" maxlength="20" type="text" placeholder="First Name" >
</div>
</div>
</form>
It calls a PHP Function that populates the drop down:
function makeSuppDropdown() {
include("dbconnect.php");
$sql = "SELECT SupporterId, ".
"CONCAT(LastName, ',', FirstName,' ',MidName,' ',trim(Suffix)) as 'SuppLookup' ".
"FROM tblsupporters ".
"ORDER BY LastName, FirstName, MidName, Suffix";
$sql_result = mysqli_query($conn,$sql);
$field= mysqli_fetch_fields($sql_result);
while ($row = mysqli_fetch_array($sql_result)) {
echo ' <option value="'.$row['SupporterId'].'" >'.$row['SuppLookup'].'</option>'.chr(10);
}
}
The function provided the following output:
<select name="selSupp" style="width:1.46in;">
<option value="">Existing Supporters</option>
<option value="32517-02" >Truxton,Karla Andrianne </option>
<option value="32517-01" >Truxton,Tommie Lee </option>
</select>
If the user selects a Parent Supporter then I wanted to start filling in the input fields. This is where I am having a problem.
Here is the PHP/Javacode I am using that is not working:
<?php
if (isset($_POST['selSupp'])) {
?>
<script type="text/javascript">
document.getElementById("SuppFirst").value = "Tommie";
</script>
<?php
} ?>
Now I know that PHP and Javascript don't always play well together, but I'm hoping that there is a solution that will allow me to fill in the fields.
Thank you in advance.

I don't really understand your question, however, to the best of my knowledge, you want the users after choosing their parents' information, a form appears with filled parents' info and extra fields.
If so, i suggest creating a submit button, since I'm not sure if a drop-down select can be submitted on itself:
if ($_POST['sbm']) { //if submit button is pressed
$option = mysqli_real_escape_string($conn, $_POST['select-name']);
//Get option from the users
if ($option == '') { //If $option == '' means if there is no value
header("Location: this_file.php?error=notselected"); //Redirect to the desired page
exit();
}
else {
header("Location: this_file.php?error=noerror");
exit();
}
}
And in the desired page (the page that contains the select form), you add:
if (isset($_GET['error'] && !empty($_GET['error'])) { //Check if error parameter exists
$error = $_GET['error'];
//Get the error
switch ($error) {
case "notselected": echo "<b style=\"color:red;\">Error!</b>"; break;
case "noerror": echo "<script>$(document).ready(function(){$('input-wanted-to-show').show();});</script>"; break; //Print out the script part that you need or show the hidden input. After this php code, please go to html and add desired input fields.
}
}
Overall, I know you want to submit that select form and add javascript if it is done, so I advice is to add a submit button, add parameter when option is valid, then use $_GET to check the parameter, print out the approriate tags.
If you still want to keep the select value, use AJAX.
If there is any problem, just comment.
I will be glad to help you figure out!

Related

Javascript - Select from DropDown - Run once

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

use ajax/js to update one of multiple select tags

I am running into a roadblock when attempting to use JavaScript to update a <select> tag on a page that I am creating. The issue I have is that this is a management style page, so there are multiple forms on one page, each one generated through PHP for an entry in a SQL database. For a better understanding of what I am talking about, here is some code from my project:
<?php
$query = "SELECT * FROM tableA ";
$data = $PDOcon->query($query);
$rows = $data->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$head = $row['head'];
$cont = $row['content'];
$app = $row['Product'];
$category = $row['CatID'];
Print "<form class='mgmt-ListView-Tall' action=\"#Anchor$id\" method=\"post\" width=\"60%\">
<input type=\"hidden\" name=\"id\" value=\"$id\" readonly />
<label for='pHead'>Heading: </label>
<input id='pHead' class='lbl-w25' name='pHead' value='$head' />
<label for='pCont'>Content: </label>
<input id='pCont' class='lbl-w20' name='pCont' value='$cont' />
<label for='pProd' >Product: </label>
<select id='pProd' name='pProd' class='pProd'>
<option value='0'>Product 1</option>
<option value='1'>Product 2</option>
</select>
<label for='pApp'>Application: </label>
<select id='pApp' name='pApp' class='pApp'>
</select>
</select>
<span><input class='mgmt-Button' id='editbtn' type=\"submit\" name='edit' value='Edit' /></span>
</form>";
}
?>
<script type="text/javascript">
$('.pProd').change(function(){
var string = this.value + ',' + '-1';
$.ajax({
url: 'scripts/get_app.php',
type: 'POST',
data: {get_option:string},
success:function(data){
document.getElementById('pApp').innerHTML=data; //This updates the select tag in the first form on the page, not the same form that the user was making changes in.
}
});
});
</script>
I have a table (TableB) that contains a list of all applications linked with their product, and what I am attempting to do currently is set up the page so that if the user changes the product in the select field on one of the forms that is generated, the application select tag is updated through AJAX. I am able to get it to update the first form on the page using document.getElementById, but I need it to update the tag with that id that is in the same form as the select tag the user was modifying (example: user makes a change to the pProd tag in the 4th form, the pApp tag in the 4th form gets updated)
I have attempted to call $(this).next(".pApp").innerHTML=data;, but this does not appear to find the tag with the correct class. I have also tried using closest() and sibling() to no avail. I have also tried referencing both id, and class with the same results, and I have searched around and could not find any solution to a problem similar to this. Does anyone have any suggestions?
The id attribute needs to be unique:
The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).1
So one solution is to append $id to the id attributes of the select lists.
<label for='pProd$id' >Product: </label>
<select id='pProd$id' name='pProd' class='pProd'>
<option value='0'>Product 1</option>
<option value='1'>Product 2</option>
</select>
<label for='pApp$id'>Application: </label>
<select id='pApp$id' name='pApp' class='pApp'>
Then in the AJAX updater, parse out that value for $id using String.replace():
$('.pProd').change(function(){
var id = this.id.replace('pProd','');
var string = this.value + ',' + '-1';
$.ajax({
url: '<?php echo $_SERVER['PHP_SELF'];?>',
type: 'POST',
data: {get_option:string},
success:function(data){
document.getElementById('pApp'+id).innerHTML=data; //This updates the select tag in the first form on the page, not the same form that the user was making changes in.
}
See it demonstrated in this phpfiddle.
Additionally, since jQuery is being used, the id selector and html() could be used to update the second select list:
success:function(data){
$('#pApp'+id).html(data);
}
1https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

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

Using Jquery to change form based on user input

I have a form with a select tag. I need my form to change based on the selection from the user. I am given to believe that the easiest way to do this is to use JQuery.
Here is my code:
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
</div>
<div id="addhtml"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
alert("event triggered");
var val = $(this).val();
if (val == "number" || val == "symbol") {
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
} else if (val == "letter") {
$("#addhtml").html(<?php include("html/form_letter.html"); ?>);
} else {
$("#addhtml").html(<?php include("html/form_other.html"); ?>);
}
});
});
</script>
Note: the php while statement just sets up the current three options of "number", "symbol" or "letter" with ids of 1,2 and 3 respectively
When I change the category, it does not trigger the jquery.change()
I would like to code the form without using the addhtml div but am willing to use it if necessary.
Questions:
Is the reason the change function is not being triggered because I am using php to set the values of the select options?
If so how can I resolve?
If not, why isn't it being triggered?
How can I accomplish my goal of not using the addhtml div?
Is there a better way to accomplish what I am going for?
Thanks in advance.
EDIT:
Answers to initial questions: As stated by bistoco, php is pre compiled by the server and sent in as html so the issue is not from using php to set the values of the select tag.
I have now determined that it is due to the content of my php include files. I have determined that it registers the change event and loads the content just fine if my file is simple like this:
"<div><label>New Number</label></div>"
but if I add any white space or \n characters for human readability like this:
"<div>
<label>New Number</label>
</div>"
Not only does it not work, but it also completely skips the change event.
New Questions: Does the jquery html function have a list of illegal characters that would cause it to fail? Why is it not even registering the change function when it doesn't like the contents of my php include file?
First thing that you must understand is that php runs on the server, all the output is rendered and sent as html code to the browser, and is not available there.
That said, you have at least 2 options :
1.- echo all form options, each one inside a div, that you can hide/show based on the selected choice.
<div class="form-group">
<label for="category" >Category</label>
<select id="category" name="category" class="form-control">
<option value="0" >Select Category</option>
<?php
$sql_cat= "SELECT * FROM category";
$result = mysqli_query($conn,$sql_cat);
$cat_items="";
if($result) {
while($cats = $result->fetch_assoc()) {
echo '<option value="'.$cats['id'].'" >'.$cats['cat_name'].'</option>';
}
} else {
echo '';
}
?>
</select>
<!-- ECHOING ALL FORM OPTIONS -->
<div class="option-form" id="form-option-symbol"><?php include("html/form_number.html"); ?></div>
<div class="option-form" id="form-option-letter"><?php include("html/form_letter.html"); ?></div>
<div class="option-form" id="form-option-other"><?php include("html/form_other.html"); ?></div>
</div>
<style>
div.option-form {
display:none; /* HIDE ALL DIVS BY DEFAULT */
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#category").change(function() {
// HIDE ALL DIVS
$('div.option-form').hide();
var val = $(this).val();
if (val == "number" || val == "symbol") {
$('form-option-symbol').show();
} else if (val == "letter") {
$('form-option-letter').show();
} else {
$('form-option-other').show();
}
});
});
</script>
2.- Using a template system or load partial html pieces with ajax.
PHP Is a pre-processor so adding later into the website is useless. Just create your form with either setting its html or by using .prepend() or .append() with your form elements.
<form class="myform">
</form>
and in jquery
$('.myform').html('<input type="submit">');
or
$('.myform').append('<input type="submit"');
EDIT :
Read your code wrong looked up
<?php include('test.html'); ?>
don't think that would work.
Instead of
$("#addhtml").html(<?php include("html/form_number.html"); ?>);
and such, try
$("#addhtml").html("<?php include("html/form_number.html"); ?>");
so that the html will be treated as a string.
Also make sure the form files don't have tags such as html, head, and body, and only contain the actual form.
EDIT: I just saw that #nnnnnn already stated this, gotta give credit where credit is due
I think you might just need to change your variable "val" declaration to get your code to work.
I don't think
var val = $(this).val();
will work. Based on the comparison you are making, I believe it should be:
var val = $(this).children("option:selected").text();
which will allow you to get the text value of the select element's selected option.

Drop-down list doesn't send POST data

My situation is, I have 2 drop-down list and only one data from one of the drop-down list will be sent into the second page. That's mean, the data from another drop-down list will not be sent. So, I choose to display the drop-down list by using the radio button. If I choose the 1st button, it will only display the 1st drop-down list and vice versa.
The problem is, when I choose the 1st drop-down list, it doesn't send any POST data from the drop-down list to the second page, only blank. But, if I choose the 2nd drop-down list, it send the data properly! I thought that there are errors in 1st drop-down list codes (even both codes are practically identical). So, I add another list, and this time, only the 3rd drop-down list's data is sent. 1st and 2nd list doesn't send anything.
I realize that my problem is my codes only sent data from the last drop-down list, not both. I only need 1 data from either drop-down list, but I need both to function. If I can only choose one list, I dont even need to make 2 drop-down list.
This is my codes, but not a full code. The other data works fine, only the drop-down list is having problem.
<form name="list" action="index.php?site=11" method="post">
<script>
function check(){
if(document.getElementById('1H').checked) {
document.getElementById('D1H').style.display = 'block';
document.getElementById('D2H').style.display = 'none';
}
else {
document.getElementById('D1H').style.display = 'none';
document.getElementById('D2H').style.display = 'block';
}}
</script>
Choose:
<input type="radio" onclick="javascript:check();" name="duration" id="1H">1 Hour
<input type="radio" onclick="javascript:check();" name="duration" id="2H">2 Hour
Choose time slot:
<div id="D1H" style="display:none">
<select name="time1" >
<option value="">---Choose---</option>
<option value="8-9">8:00am-9:00am</option>
</select>
</div>
<div id="D2H" style="display:none">
<select name="time2" >
<option value="">---Choose---</option>
<option value="8-10">8:00am-10:00am</option>
</select>
</div>
<input type="submit" name="submit" value="Next">
This is php codes to show how I receive the POST data, just until the query.
include('../include/dbconnect.php');
$user = $_SESSION['username'];
if(isset($_POST['submit'])){
if(isset($_POST['time'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time'];
echo "1:".$time;
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
if(isset($_POST['time2'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time2'];
echo "2:".$time;
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
}
echo "3:".$time;
How do I solve this problem? I need to make sure that both drop-down list can sent POST data to another pages, not only one functioning at all. I hope you can understand my problem.
EDIT: I have change both select box's names.
2nd EDIT: I add Fred's code
The select boxes both have the same name. You need to set different name attributes for the two select options.
Edit
The issue is that the select box will post data even if it's not explicitly set. So each isset() will always return true.
As long as your default option has an empty value attribute you can check against that like this:
if(!empty($_POST['time']))
Or maybe set a default value to test against like so:
<option value="0">---Choose---</option>
<?php if($_POST['time'] != '0') ?>
The original issue was that the form would always post the last select even if you only made a choice with the first one. The issue now is that both if(isset clauses will be true.
What has already been said in regards to both selects holding the same name, still stands.
Sidenote: (I renamed the 2nd select to time2)
However, in order to use the time from either radio button/dropdown selects, you need to use an isset conditional statement, then use that variable for your DB insert.
Tested as follows while naming the submit button as my own self test and inside the same file. You can modify it to suit.
Scenario: The $time variable that's being (set) then passed to your DB, will be set as such, depending on which time select was chosen.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['time'])){
$time=$_POST['time'];
echo $time;
}
if(isset($_POST['time2'])){
$time=$_POST['time2'];
echo $time;
}
}
?>
<form name="list" action="" method="post">
<script>
function check(){
if(document.getElementById('1H').checked) {
document.getElementById('D1H').style.display = 'block';
document.getElementById('D2H').style.display = 'none';
}
else {
document.getElementById('D1H').style.display = 'none';
document.getElementById('D2H').style.display = 'block';
}}
</script>
Choose:
<input type="radio" onclick="javascript:check();" name="duration" id="1H">1 Hour
<input type="radio" onclick="javascript:check();" name="duration" id="2H">2 Hour
Choose time slot:
<div id="D1H" style="display:none">
<select name="time" >
<option value="">---Choose---</option>
<option value="8-9">8:00am-9:00am</option>
</select>
</div>
<div id="D2H" style="display:none">
<select name="time2" >
<option value="">---Choose---</option>
<option value="8-10">8:00am-10:00am</option>
</select>
</div>
<input type="submit" name="submit" value="Next">
EDIT (DB-related)
And in your case, it would be: (and do name your submit button to name="submit" for this):
<?php
if(isset($_POST['submit'])){
if(isset($_POST['time'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time'];
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
if(isset($_POST['time2'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time2'];
$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
}
?>

Categories