passing dropdown selevect option to the url using javascript and it is working fine but problem is that <option>Select</option> also passing to the url now how could i disabled <option>Select</option> while passing the select option values to the url? i want to send only name to the url except <option>Select</option>?
function getComboC(sel) {
var name=document.getElementById("name");
var input_val = document.getElementById("name").value;
name.action = "searchexpense.php?name="+input_val+"";
name.submit();
<form name="name" id="name"><select class="select10"
name="pname" id="name" style="width:150px;" onChange="getComboC(this)">
<option value="0"><--Select--> </option>
<?php
$query=mysql_query("SELECT pname from expenses order by id");
while($row=mysql_fetch_assoc($query))
{
$val2=$row['pname'];
?>
<option value="<?=$val2;?>" <? if ($_GET['pname'] == $val2)
{ echo "selected='selected'"; }?> >
<?=$row['pname'];?>
</option>
<?php }?>
</select></form>
Url While Select <option>Select</option>
searchexpense.php?pname=0
Dynamically Option Select
searchexpense.php?pname=Test
you arr using same id for multiple elements, like for form and select. id's must be unique, so try:
<form name="my_frm" id="my_frm">
<select class="select10" name="pname" id="name" style="width:150px;" onChange="getComboC(this)">
....
and js function :
function getComboC(sel) {
//do not submit if default "select" is selected
if( sel.value != "0" ) {
var selected_value = sel.value; //selected dropdown value
document.my_form.action = "searchexpense.php?name="+selected_value;
document.my_form.submit();
}
}
Related
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
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>
I have a combo box named "Make". In that combo box I'm loading vehicle manufacturer names. When I click SEARCH button I want to display the selected manufacturer name. Below is part of my HTML code.
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" >
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="submit" name="search" value="Search"/>
Below is my PHP code so far I've done.
<?php
if(isset($_POST['search']))
{
$maker = mysql_real_escape_string($_POST['Make']);
echo $maker;
}
?>
If I select Toyota from the combo box and press SEARCH button, I'm getting the answer as '2' . It means it gives me the value of the 'Toyota'. But I want to display the name 'Toyota'. How can I do that? Please help me ....
Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']
<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['Make']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
echo $maker;
}
?>
Put whatever you want to send to PHP in the value attribute.
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="--Any--">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You can also omit the value attribute. It defaults to using the text.
If you don't want to change the HTML, you can put an array in your PHP to translate the values:
$makes = array(2 => 'Toyota',
3 => 'Nissan');
$maker = $makes[$_POST['Make']];
You can achive this with creating new array:
<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");
if (isset ($_POST['search'])) {
$maker = mysql_real_escape_string($_POST['Make']);
echo $array[$maker];
}
?>
if you fetching it from database then
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>
Change your select box options value:
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="Any">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You cann't get the text of selected option in php. it will give only the value of selected option.
EDITED:
<select id="cmbMake" name="Make" >
<option value="0">Select Manufacturer</option>
<option value="1_Any">--Any--</option>
<option value="2_Toyota">Toyota</option>
<option value="3_Nissan">Nissan</option>
</select>
ON php file:
$maker = mysql_real_escape_string($_POST['Make']);
$maker = explode("_",$maker);
echo $maker[1]; //give the Toyota
echo $maker[0]; //give the key 2
you can make a jQuery onChange event to get the text from the combobox when the user select one of them:
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$('#EvaluationName').val(str);
})
.change();
</script>
When you select an option, it will save the text in an Input hidde
<input type="hidden" id="EvaluationName" name="EvaluationName" value="<?= $Evaluation ?>" />
After that, when you submit the form, just catch up the value of the input
$Evaluation = $_REQUEST['EvaluationName'];
Then you can do wathever you want with the text, for instance save it in a session variable and send it to other page. etc.
I agree with Ajeesh, but there are simpler ways to do this...
if ($maker == "2") { }
or
if ($maker == 2) { }
Why am I not returning a "Toyota" value? Because the "Toyota" choice in the Selection Box would have already returned "2", which, would indicate that the selected Manufacturer in the Selection Box would be Toyota.
How would the user know if the value is equal to the Toyota selection in the Selection Box? In between my example code's brackets, you would put $maker = "Toyota" then echo $maker, or create a new string, like so: $maketwo = "Toyota" then you can echo $makertwo (I much prefer creating a new string, rather than overwriting $maker's original value.)
If the user selects "Nissan", will the example code take care of that as well..? Yes, and no. While "Toyota" would return value "2", "Nissan" would instead return value "3". The current set value that the example code is looking for is "2", which means that if the user selects "Nissan", which represents value "3", then presses "Search", the example code would not be executed. You can easily change the code to check for value "3", or value "1", which represents "--Any--".
What if the user clicks "Search" while the Selection Box is set to "Select Manufacturer"? How can I prevent them from doing so? To prevent them from proceeding any further, change the set value of the example code to "0", and in between the brackets, you may place your code, then after that, add return;, which terminates all execution of any further code within the function / statement.
I have the following drop down menu on my website
<select name="Templates" onchange="document.sendform.message.value = 'some text here'; return false;">
<option value="#" selected>----Templates----</option>
<option value="#">Absense</option>
<option value="#">Lates</option>
</select>
This currently sends text to a text area named "message" however I would like the text to be different for each option selected. Is there an easy way to do this at all?
Thanks!
Here it is:
http://jsfiddle.net/sinisake/3NQH7/
<form name="sendform">
<select name="Templates" onchange="document.sendform.message.value = this.value; return false;">
<option value="#" selected>----Templates----</option>
<option value="absense">Absense</option>
<option value="lates">Lates</option>
<input type="text" value="" name="message" />
</select>
</form>
the onchange event handler is what sends the text; if you want to send text based on the value of the selected option you should use a more advanced event handler:
document.TemplateForm.Templates.onchange = function () {
var value = this.value;
if (value === 'absence') {
setMessage('Absence message');
} else if (value === 'laters') {
setMessage('Laters message');
} else {
setMessage('Default message');
}
return false;
};
function setMessage(message) {
document.sendform.message.value = message;
}
I wrapped your select element in a form to be able to adress it simply in the JavaScript above:
<form name="TemplateForm">
<select name="Templates">
<option value="#" selected>----Templates----</option>
<option value="absence">Absense</option>
<option value="laters">Lates</option>
</select>
</form>
In order to see what value is selected I also added unique values for the options elements.
Live example: http://jsfiddle.net/fRB3s/1/
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.