differentiating identical select names - php

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.

Related

Select specific <option> from <select> while having a value from PHP

I have the following HTML code for my element and it is populated with elements.
<select name="category" class = "form-control">
<option value = "Awearness">Awearness</option>
<option value = "ITandTechnology">IT and Technology</option>
<option value = "Physics">Physics</option>
<option value = "Sport">Sport</option>
<option value = "Science">Science</option>
<option value = "Social">Social</option>
</select>
I also have PHP code above tag that gets me value of category from MySQL database. So for example:
...$category = "Sport";...
What I need to know is, is there a way to select certain option when page loads that corresponds to $category variable I got in PHP?
So if
...$category = "Sport";...
it selects the Sport option from tags.
To set an option as selected on page load we can use the selected attribute.
<option value="some-value" <?= $category == 'some-value' ? 'selected' : '' >>....</option>
Then do the same for each option in your list.
I suggest using JavaScript along with your php.
For example,
<?php
$cat = 'Sport';
?>
<!DOCTYPE html>
<html>
<body>
<select name="category" class = "form-control" id = "i1">
<option value = "Awearness">Awearness</option>
<option value = "ITandTechnology">IT and Technology</option>
<option value = "Physics">Physics</option>
<option value = "Sport">Sport</option>
<option value = "Science">Science</option>
<option value = "Social">Social</option>
</select>
<script>
var a= document.getElementById('i1');
a.getElementsByTagName('option');
for(i=0;i<a.length;i++)
{
if(a[i].value=='<?php echo $cat;?>')
{
a[i].setAttribute("selected","selected");
break;
}
}
</script>
</body>
</html>

make the <select> tag selected display HTML

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

PHP code to get selected text of a combo box

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.

multiple options registering incorrectly when inserted into mysql table

I have 2 drop-down menu forms 'category' and 'sub-category'. in 'category' I have options music and film and in the subcategories I have options 'pop' and 'rock'(f1) and in film 'comedy'and 'drama'(f2). the problem is, with the code I have the subcategories for film should register as follows(cat,subcat): film-drama=2,5 and film-comedy=2,6 however they both register as 2,0 when entered in the mysql table. here is the code:
<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">
<form name= "subcat">
<select name='subcat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "3">pop</option>
<option value = "4">rock </option>
</select>
</form>
</div>
<div id = "f2" style="display:none">
<form name= "subcat">
<select name='subcat' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "5">comedy</option>
<option value = "6">drama</option>
</select>
</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";
}
}
and here is the variable declarations and mysql query:
$cat=$_POST['cat'];
$subcat=$_POST['subcat'];
$sql="INSERT INTO favorites VALUES('$cat','$subcat')";
it's not a mysql issue I just added that part to give a better overall picture.
You can't have nested forms in HTML. The markup is not valid and I guess you get unexpected behavior when submitting. The solution to this is using a single form. There's more than one way to do this, but here's one example:
HTML code:
<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='subcat1' 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='subcat2' id = "opts" onchange = "showForm()">
<option value = "0">Select</option>
<option value = "5">comedy</option>
<option value = "6">drama</option>
</select>
</div>
</form>
....
PHP code:
$cat = $_POST['cat'];
$subcat = $_POST['subcat' . $cat];
Keep in mind that all user-submitted values must be validated before being used further. In this case, you would check for is_numeric(), check to see if it's in your accepted range of values and maybe cast to an int.

How to Keep the selected value of the select box after Form POST or GET

Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>

Categories