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.
Related
I am creating a listbox box with 2 optional values Ja(Yes) or Nein(No). Additional iam using a default Value which is taken from the database for the record.
Here the code:
<td>
<select name="s_BKAG">
<option selected="selected" ><?php $bkagbruggwert = ''.$abc['BKAG (Brugg)']. ''; if ($bkagbruggwert==1){echo 'Ja';} else {echo 'Nein';};?></option>
<option value="1">Ja</option>
<option value="0">Nein</option>
</select>
</td>
Problem: Now i want that when Yes or No is selected, then id should take their value and if nothing is selected it should take the Value of the preselected default value. But the problem is the variable which i have created has the value "Ja", it does not matter what I'am changing on the formular. I do not know if I overseeing something.
The code of variable defining is here:
$BKAG_Brugg = $_POST['s_BKAG'];
I could take $BKAG_Brugg and define a new variable which i am asking, if the $BKAG_Brugg is "Ja" then set 1 to the new variable. But it's my first project on php and i do not really now how to do the query for the new variable.
Can someone help me with that? i would be thankful for every little help.
regards:
okanog
I think you can do like this:
<select name="s_BKAG">
<option></option>
<?php $bkagbruggwert = $abc['BKAG (Brugg)']; ?>
<option value="1" <?php if($bkagbruggwert == 1) { echo 'selected'; } ?>>Ja</option>
<option value="0" <?php if($bkagbruggwert == 0) { echo 'selected'; } ?>>Nein</option>
</select>
This way, if there is no preselected value, the empty option will be displayed; if there is a preselected value and this value is same as value of any option, it will be selected.
I hope this works for you.
You can do it this way,
Assign the default value to the hidden element
In case, if the user doesn't select one option, then assign the default value from the hidden element
function fetchValue()
{
var selectedValue = document.getElementById("s_BKAG").value;
if(selectedValue == "")
{
selectedValue = document.getElementById("default-value").value;
}
console.log("The selected value is: " + selectedValue);
}
<select id="s_BKAG" name="s_BKAG">
<option value="">None</option>
<option value="1">Ja</option>
<option value="0">Nein</option>
</select>
<input id="default-value" type="hidden" value="<?php echo $abc['BKAG (Brugg)'] ?>" />
<input type="button" value = "Fetch Value" onclick="fetchValue()" />
I have a search form that uses Javascript to change the input method depending on what's selected. So if you have "Name" selected you get a text box, but if you have "Rating" selected you get a drop-down list from 1-5.
<form method="GET" action="results_sample.php">
<p>Search by: <!-- Dropdown list allows users to search by different elements -->
<select id="searchtype" name="searchtype" onchange="changeview()"> <!-- onchange calls changeview() every time the dropdown value is changed. Allows ratings to be seen -->
<option value="School">School</option>
<option value="Name">Name</option>
<option value="Rating">Rating</option>
<option value="Class Location">Class Location</option>
<option value="Subject">Subject</option>
</select>
</p>
<span id="standard" style="display:inline">Search Query: <input type="text" name="query"></span>
<span id="locationsearch" style="display:none"> (Longitude-Lattitude pair) <input type="number" id="longitude" step="any"> - <input type="number" id="latitude" step="any"> </span>
<span id="ratevalue" style="display:none"> Choose rating:
<select id="ratings">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
</span>
<p><input type="submit"></p>
</form>
The relevant code in results_sample.php is:
<?php
if (isset($_GET['searchtype'])) {
if (!empty($_GET['query'])) {
$search = $_GET['query'];
} elseif (!empty($_GET['ratings'])) {
$search = $_GET['ratings'];
} elseif (!empty($_GET['longitude']) || isset($_GET['latitude'])) {
$search = 'more to come...';
}
echo '<p>Entries containing "', $search, '" in "', $_GET['searchtype'], '"</p>';
}
?>
I have two problems:
1) If I type text into the search query, then switch to ratings, and try to search by ratings, it still has the textbox invisible in the background, and uses that information instead.
2) If the textbox is empty and I want to search by Longitude-Latitude, Rating is still set at a default of 1 (invisible in the background) and it takes that value.
One option is to check $_GET['searchtype'] value and select another $_GET variable according to it, something like:
switch ($_GET['searchtype']) {
case 'Name':
$search = $_GET['query'];
break;
case 'Rating':
$search = $_GET['ratings'];
break;
case 'Class Location':
$search = 'other value';
break;
// add more cases as you wish
}
Other option can be using javascript to clear other fields' values when you change #searchtype but in this case select#ratings still will be sent to server.
I'm trying to make appear some HTML code if the selected option is the right one, is it possible?
example:
<select name="ref_rubrique">
<option value="1"> number 1 </option>
<option value="2" selected> number 2 </option>
</select>
and
<?php if( $selected==true ): ?>
<p>hello<p>
<?php else(): ?>
<p><p>
<?php endif(); ?>
When the form is submitted you can check $_REQUEST['ref_rubrique']. You can then compare the value, e.g. 1 == $_REQUEST['ref_rubrique']. Both "1" and "2" are truthy values.
In order for this to happen immediately without refreshing the page, it needs to happen entirely in client-side code (JavaScript). So, let's start with your page elements:
<select name="ref_rubrique">
<option value="1"> number 1 </option>
<option value="2" selected> number 2 </option>
</select>
You'll also need some sort of placeholder for the output. And let's use id attributes so we can easily uniquely identify the elements in question. So let's use this:
<select name="ref_rubrique" id="ref_rubrique">
<option value="1"> number 1 </option>
<option value="2" selected> number 2 </option>
</select>
<div id="ref_output"></div>
For now the output is empty. It will be populated by our JavaScript code when the select element's value changes. So now we need a script code block to attach that functionality to the change event of that element:
<select name="ref_rubrique" id="ref_rubrique">
<option value="1"> number 1 </option>
<option value="2" selected> number 2 </option>
</select>
<div id="ref_output"></div>
<script type="text/javascript">
var selectElement = document.getElementById('ref_rubrique');
var divElement = document.getElementById('ref_output');
selectElement.onchange = function () {
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
if (selectedValue == '1') {
divElement.innerHTML = '<p>hello</p>';
} else if (selectedValue == '2') {
divElement.innerHTML = '<p></p>';
}
};
</script>
So what I've done here is:
Get a reference to each of the HTML elements as JavaScript variables
Bind a function to the change event for the select element, which will...
Get a the selected value of the select element
If that selected value is something, write HTML to the output div element
If it's something else, write other HTML to the div element
You can see a live example of this here.
I did it that way if anyone is looking for my solution:
<select name="ref_rubrique" id="ref_rubrique">
<option value="11">11</option>
<option value="12" selected>12</option>
<option value="13">13</option>
</select>
<div id="ref_output">
<?php
if (isset($_GET["id_rubrique"])){
if($_GET["id_rubrique"]==12){
?>
<p>Your question here !</p>
<p><input name="type" type="radio" value="1" <? if($page_type=='true'){ ?>checked<? } ?>>Oui<input name="type" type="radio" value="0" <? if($page_type=='false'){ ?>checked<? } ?>>Non</p>
<?php
}
}
?>
</div>
<script language="javascript" type="text/javascript">
var selectElement = document.getElementById('ref_rubrique');
var divElement = document.getElementById('ref_output');
selectElement.onchange = function () {
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
if (selectedValue == '12') {
divElement.style.display = "block";
} else if (selectedValue != '12') {
divElement.style.display = "none";
}
};
</script>
Thanks to everyone for the help, bye :)
You probably should use id better than name
<select id="ref_rubrique">
<option value="1"> number 1 </option>
<option value="2" selected> number 2 </option>
</select>
<div id="textPlace"></div>
You can use JQuery to check for the value that has been selected, then get the p or div element and add your text to it.
//check if the selected option has a value of 2, than set the text
if($('#ref_rubrique').val() == 2){
$("#textPlace").html("My text");
}
Here is a live example: Here
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.
Hmm...this question may sounds silly , hope you all don't mind...
If I have a drop list:
<select name="myoption" onchange="document.textbox.value=this.value">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<input type="text" name="textbox" id="textbox">
So with this now the textbox will display what is selected , but is it possible to display the A,B,C instead of 1,2,3?
Actually I need a drop-list which will display 2 different values to 2 textbox,such as if A is selected,textbox1 will display "A" and textbox2 will display "1".
I don't know if it is possible and I tried for some times already...can someone give me some hints?
Thanks in advance.
Yes, it is possible. I would just externalize all javascript into a separate file to avoid mixing markup and scripts.
So the script:
// subscribe for the DOM ready event to ensure that you
// are manipulating the DOM only when it is loaded
window.onload = function() {
// subscribe for the onchange event of the dropdown
document.getElementById('myoption').onchange = function() {
// fetch the text of the currently selected element
var text = this.options[this.selectedIndex].innerHTML;
// and assign it to the corresponding input
document.getElementById('textbox').value = text;
};
};
and the markup:
<select name="myoption" id="myoption">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<input type="text" name="textbox" id="textbox" />
and a live demo.