php drop down button selected - php

in form edit data wants to display in the form...but drop down values should not get selected ...i want drop down value get seleted
here is code in list_search function id return cmb_fruit, val return Apple or Orange
<tr>
<td width="38%" height="28" align="left"><span class="style20"><font color="#DC143C">*</font>Profession</span></td>
<td width="62%" align="left"><label for="profession"></label>
<select name="cmb_fruit" size="1" id="cmb_fruit">
<option value="Select">Select</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select>
<script language="javascript" type="text/javascript">
list_search('cmb_fruit',<?php echo "'" . #mysql_result($rs_modify,0,'fruit') . "'";?>)
</script>
</td>
</tr>
function list_search(id,val)
{
cnt=document.getElementById(id).length
for(x=0; x<cnt; x++ )
{
if( document.getElementById(id).options(x).value==val)
{
document.getElementById(id).options(x).selected=true
break;
}
}
}

var fruit = document.getElementById("fruit");
fruit.options[fruit.options.selectedIndex].selected = true;

You can set the value property of the select. Also, make sure the list_search function is declared in the head if you are calling it from a script that runs in the body.
function list_search(id, val) {
document.getElementById(id).value = val;
}
Note that you don't need javascript for this and you could simpy put the selected attribute on the option element you want to select.
<option value="Apple" selected>Apple</option>

Related

How to POST two parameters in PHP using Ajax

I want to pass two parameters into the function getStuName() but found that there is error. Can anyone help me with the syntax?
<script language="javascript">
function getStuName1(val, val1) {
if(val!=''){
$.ajax({
type: "POST",
url: "get_stuname1.php",
data:'yr='+val+'&classname='+val1,
success: function(data){
$("#stu-list1").html(data);
}
});
alert(data);
}else{
document.getElementById('stuname').options.length=1;
document.getElementById('stuname').options[0].text='Please select';
}
} //end function
</script>
<select style="font-size: 18px;" name="yr" onChange="getStuName1(this.value);">
<option value="2021-2022">2021-2022</option>
<option value="2022-2023">2022-2023</option>
<option value="2023-2024">2023-2024</option>
<option value="2024-2025">2024-2025</option>
<option value="2025-2026">2025-2026</option>
<option value="2026-2027">2026-2027</option>
</select>
<select style="font-size: 18px;" name="classname" id="class-list" class="demoInputBox" onChange="getStuName1(this.value);">
<option value="" selected>please select</option>
<?php
$sql="SELECT classname FROM class";
$class_result = mysqli_query($db_link,$sql);
while($rs = mysqli_fetch_array($class_result, MYSQLI_ASSOC)) {
?>
<option value="<?php echo $rs["classname"]; ?>"><?php echo $rs["classname"]; ?></option>
<?php
}
?>
</select>
Content of get_stuname1.php
<?php
require_once("connMysql.php");
$sql_stu ="SELECT * FROM stu_hist WHERE enabled='1' AND sch_yr = '" . $_POST['yr'] . "' AND classname = '" . $_POST['classname'] . "' ORDER BY classno";
$stu_result = mysqli_query($db_link,$sql_stu);
while($rs = mysqli_fetch_array($stu_result, MYSQLI_ASSOC)) {
?>
<option value="<?php echo $rs["stu_name"]; ?>"> <?php echo $rs["stu_name"]; ?></option>
<?php
}
?>
I want to get the yr and classname and pass them into the function getStuName1 but cannot display student name
To ensure that the values from both select menus ( or all if there are more ) are used in the ajax request one method you might consider would be to use a global variable that you populate when a select menu triggers the change event. This global variable could be an object or array - it is the effective length when populated that is of interest as we can decide to send the AJAX request only when both/all select menus have been changed. This is all done without jQuery but the fetch code could very easily be replaced with suitable jQuery code. No need for buttons to fire the request...
// populate this with select name & value pairs
let args={};
// a function to process the response from the server
let callback=(r)=>{
document.getElementById('stu-list1').innerHTML=r;
}
// delegated event handler bound to the document
document.addEventListener('change',e=>{
if( e.target instanceof HTMLSelectElement && e.target.classList.contains('required') ){
// store this select menu name/value
args[ e.target.name ]=e.target.value;
// if BOTH (all) select menus are populated, do the AJAX request
if( Object.keys( args ).length==document.querySelectorAll('select.required').length ){
let payload=Object.keys( args ).map(name=>{
return [ name, args[name] ].join('=')
}).join('&');
fetch( 'get_stuname1.php', { method:'post', body:payload } )
.then(r=>r.text())
.then(callback)
.catch(alert)
}
}
});
<select name="yr" class='required'>
<option selected hidden disabled>please select...
<option>2021-2022
<option>2022-2023
<option>2023-2024
<option>2024-2025
<option>2025-2026
<option>2026-2027
</select>
<select name="classname" id="class-list" class="demoInputBox required">
<option selected hidden disabled>please select...
<option>geronimo
<option>horatio
<option>mimosa
</select>
<div id='stu-list1'></div>
Since you are passing two parameters to the getStuName1 function, so instead of using onChange (for a change in one select box) , it is recommended that you have a button which submit the two selected values when both of the them are selected (a "confirm submission" button is the preferred choice because normally a person needs to make up his/her mind that all the select boxes are properly chosen before the actual submission, and actually there is no point to trigger the ajax if only one of the select boxes are selected)
Hence
make sure that both select box are having a unique id (so add id="yr" for the yr select box)
add say a button which trigger passing the selected values of the two select boxes, such as:
<input type=button value="Confirm" onclick="javascript:trigger1();">
and
<script>
function trigger1() {
var e = document.getElementById("yr");
var value1 = e.value;
var e2 = document.getElementById("class-list");
var value2 = e2.value;
getStuName1(value1, value2);
}
</script>
So, change your code to
<script language="javascript">
function getStuName1(val, val1) {
if(val!=''){
$.ajax({
type: "POST",
url: "get_stuname1.php",
data:'yr='+val+'&classname='+val1,
success: function(data){
$("#stu-list1").html(data);
}
});
alert(data);
}else{
document.getElementById('stuname').options.length=1;
document.getElementById('stuname').options[0].text='Please select';
}
} //end function
</script>
<select style="font-size: 18px;" name="yr" id="yr">
<option value="2021-2022">2021-2022</option>
<option value="2022-2023">2022-2023</option>
<option value="2023-2024">2023-2024</option>
<option value="2024-2025">2024-2025</option>
<option value="2025-2026">2025-2026</option>
<option value="2026-2027">2026-2027</option>
</select>
<select style="font-size: 18px;" name="classname" id="class-list" class="demoInputBox" >
<option value="" selected>please select</option>
<?php
$sql="SELECT classname FROM class";
$class_result = mysqli_query($db_link,$sql);
while($rs = mysqli_fetch_array($class_result, MYSQLI_ASSOC)) {
?>
<option value="<?php echo $rs["classname"]; ?>"><?php echo $rs["classname"]; ?></option>
<?php
}
?>
</select>
<input type=button value="Confirm" onclick="javascript:trigger1();">
<script>
function trigger1() {
var e = document.getElementById("yr");
var value1 = e.value;
var e2 = document.getElementById("class-list");
var value2 = e2.value;
getStuName1(value1, value2);
}
</script>
[Additional point]
Last but not least, please amend your PHP script to use parameterized prepared statement which is resilient against SQL injection. You may refer to the following:
For Mysqli:
https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
For PDO
https://www.php.net/manual/en/pdo.prepare.php

How to have an HTML input field appear when the value 'other' is selected with PHP

What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>

Count & Highlight Table Row Elements Dynamically

I want to be able to do two things. The first, is look at all "selected" items of a certain value. Say I have a, b, c ; I want to look for all items selected as "c" and highlight that table row as a different color. In addition, upon opening the form, I want the items counted, and be able to display a message div at the top of the screen showing those highlighted items. What is the best practical way of doing this? This is my original code :
//Start loop of items
<?php foreach ( $data['Detail'] as $key=>$item){?>
<tr id="tr_<?php echo $key+1?>">
<td>
<select value="<?php echo $location; ?>" name="[<?php echo $key;?>][location]" id="location_<?php echo $key+1?>" class="form-control>
<option value="Selection1" <?= ($item['location']) == 'Selection1' ? 'selected' : '' ?>>Selection1</option>
<option value="Selection2" <?= ($item['location']) == 'Selection2' ? 'selected' : '' ?>>Selection2</option>
<option value="Selection3" <?= ($item['location']) == 'Selection3' ? 'selected' : '' ?>>Selection3</option>
</select>
</td>
</tr>
// Segment here to count? Example :
// $location_count = 0; If $location = 'c' then $location_count++;
<?php } ?>
Sample Div Code :
<div>
<p>You have <?php echo $location_count?> Locations that need reviewed</p>
</div>
Image Sample of Working Code :
the theory is:
loop through the table's select elements
check each select's value and update the row style
when a select changes, do the same to the current row.
count the rows with the highlight
append the row count to the div
You can see the theory in practice with the code/link below.
The code is purposefully simplistic for demonstration and could be improved for performance/terseness. However it's not bad code :)
$(function() {
/* function to run for select boxes in table */
function rowState( $select ) {
var selected = false;
/* set boolean for selected */
if ( $select.val() === "c" ) {
selected = true;
}
/* apply css class to the row if selected */
$select.closest("tr").toggleClass("c", selected);
/* count rows */
var n = $( "table tr.c" ).length;
/* change the html element's text to the count */
$( ".snippet span" ).text( n );
}
$("table select").each(function() {
/* on page load, set selected states */
rowState($(this));
}).on("change", function() {
/* on state change, set selected states */
rowState($(this));
});
});
table {
width: 100%;
}
tr td {
background: #eee;
}
tr.c td {
background: #cfc
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="snippet">
Please review <span>x</span> items
</div>
<table>
<tr>
<td>
<select>
<option value="a" selected>a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option value="a">a</option>
<option value="b">b</option>
<option value="c" selected>c</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option value="a">a</option>
<option value="b" selected>b</option>
<option value="c">c</option>
</select>
</td>
</tr>
</table>

differentiating identical select names

how can I differentiate the 'select name' of 'f1' and 'f2' currently both named 'subcat' while still having only 1 subcat variable? this code works accurately only if cat value=2, if cat value=1 then subcat value always =0
<?php
$cat=$_POST['cat'];
$subcat = $_POST['subcat'];
?>
<form action='submitsite.php' method='POST'>
<table>
<tr>
<td>category(optional)</td>
<td>
<select name='cat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "1">music </option>
<option value = "2">film </option>
</select>
<div id = "f1" style="display:none">
<select name='subcat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "3">pop</option>
<option value = "4">rock </option>
</select>
</div>
<div id = "f2" style="display:none">
<select name='subcat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "5">comedy</option>
<option value = "6">drama</option>
</select>
</div>
</form>
</div>
<script type = "text/javascript">
function showForm(){
var selopt = document.getElementById("opts").value;
if (selopt == 1) {
document.getElementById("f1").style.display="block";
document.getElementById("f2").style.display="none";
}
if (selopt == 2) {
document.getElementById("f2").style.display="block";
document.getElementById("f1").style.display="none";
}
}
</script>
Add [] to the name. The selects will then be interpreted as an array when submitted.
<select name="subcat[]">...</select>
With PHP it can be accessed (if POSTed) like this:
<?php
$subCatArr = $_POST['subcat'];
$firstIndex = $subCatArr[0];
$secondIndex = $subCatArr[1];
Oh yeah, and reusing IDs in HTML is not valid. They must be unique.
UPDATE After better understanding OP's intent:
If I understand the intent of this spaghetti code (that's a term of endearment, OP), the user may select one category and one subcategory, which is based on the category that he/she selected. Then the user submits the form and that selection is recorded in the database.
First of all, let's get rid of the use of table elements, because they're unnecessary. Secondly, you only need one select for the subcategory.
<form action='submitsite.php' method='POST'>
<label>category(optional)</label>
<select name='cat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "1">music </option>
<option value = "2">film </option>
</select>
<div id="subcatDiv" style="display:none;">
<select name='subcat' id='opts'></select>
</div>
.
.
.
<input type='submit' />
</form>
We can leave it blank, since it's not being displayed anyway.
Now, when the user makes a change, we'll either display the appropriate subcategories, or we'll just hide the div again:
<script type = "text/javascript">
function showForm(){
var selopt = document.getElementById("opts");
var seloptVal = selOpt.value;
var subcatDiv = document.getElementById("subcatDiv");
var options = "";
switch(seloptVal * 1) {
case 1:
options = "<option value='0'>Select</option>" +
"<option value='3'>pop</option>" +
"<option value='4'>rock</option>";
break;
case 2:
options = "<option value='0'>Select</option>" +
"<option value='5'>comedy</option>" +
"<option value='6'>drama</option>";
break;
default:
break;
}
if (options == "") {
subcatDiv.style.display = "none";
selopt.innerHTML = options;
} else {
selopt.innerHTML = options;
subcatDiv.style.display = "block";
}
}
</script>
Now you only have to deal with one select for the subcategory.
I have altered a lot of your code to make it valid html and also work as i "think" you want it as your question did not make it very clear.
Here is a list of amends I had to make:
Changed ID's to make it clear what they are for.
Removed duplicate ID's.
Closed off your table properly.
Completely changed your JavaScript to show and hide certain select's
Many more things that I have forgotten.
Please see this jsfiddle.
Fixed html:
<form action='submitsite.php' method='POST'>
<table>
<tr>
<td>category(optional)</td>
<td>
<select name="cat" id="selectType">
<option value="0">Select</option>
<option value="1">music</option>
<option value="2">film</option>
</select>
<div id="f1" style="display:none">
<select name='music' id="selectMusic">
<option value="0">Select</option>
<option value="3">pop</option>
<option value="4">rock</option>
</select>
</div>
<div id="f2" style="display:none">
<select name="type" id="selectFilm">
<option value="0">Select</option>
<option value="5">comedy</option>
<option value="6">drama</option>
</select>
</div>
</td>
</tr>
</table>
</form>
Fixed JavaScript:
$("#selectType").change(function() {
var selected = $(this).val();
$("#f1, #f2").hide();
switch (selected) {
case "1":
$("#f1").show();
break;
case "2":
$("#f2").show();
break;
}
});​​
document.forms[0].subcat will be an array.
document.forms[0].subcat[0] will be the first instance, etc.
p.s. IDs are supposed to be unique.
document.getElementById('f2').getElementsByTagName('select')[0]
You are violating HTML standards by reusing IDs, by the way.

Basics of dynamic loading a drop down box

I'm new to php/ajax and to an extent sql. I'm trying to add a dynamic drop down box which when select will either load up another drop down box with dates or another text box. Can someone point me towards some simple examples that are not very confusing. I understand that ajax is best for this.
script
function showfield(name){
if(name=='byreturn')document.getElementById('div1').style.display="block";
else document.getElementById('div1').style.display="none";
}
if(name=='forwardorder')document.getElementById('div2').style.display="block";
else document.getElementById('div2').style.display="none";
}
function hidefield() {
document.getElementById('div1').style.display='none';
}
page
<tr><td> <body onload='hidefield()'>
Choose Delivery Type </td>
<td> <select name = 'elementtype1'id='elementtype1' onchange='showfield(this.options[this.selectedIndex].value)'>
<option value='forwardorder'>Forward Order</option>
<option value='byreturn'>By Return</option>
</select></td>
<td>
<div id='div1'>Enter By Return Date<input type='text''name='whatever1' />
</div>
<div id='div2'>
<td>Capacity</td>
<td><select name='deliveryDate'>
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
<option value='" . $x[cap] . "'</option>;
</div>
</td></tr>
This is very simple
<select name="first" onChange="populateNextBox(this)">
<options value="1">Microsoft</options>
<options value="2">Oracle</options>
</select>
<div id="populate"></div>
When user select the value from the drop down
required java script function
function populateNextBox(e) {
alert(e.value); //will print the selected value
//used jquery for populating data
$.post('ajax/test.php?id='+e.value, function(data) {
$('#populate').html(data);
});
}
//Your ajax/test.php will create the content for the dropdown

Categories