I have an HTML select with default value and I would like to keep Data on this select, if nothing was selected before, I would like to keep the first value like this :
HTML Side :
<select id="gender" name="gender" class="form-control" required>
<option selected disabled>Gender</option>
<option value="1">Male</option>
<option value="2">Female</option> </select>
PHP Side :
$_SESSION['post'] = $_POST;
// I first protected the data with html_entities
$_SESSION['post']['gender']=$this->_dataProtected['gender'];
// I redirect just for test (it works well with other values from input)
header('Location: ?page=children&action=add');
exit();
Javascript side :
$(window).on('load',function (){
var idGender = document.getElementById('gender').value = "<?php echo $_POST['gender'] ?? " + $('#gender').val($('#gender option:first').val()) + " ?>";
});
Thank you for your help
The result after submit the form : it fill my select with null value in the case I haven't choose an option and the same when I chose an option.
You cannot get a value passed back from an disabled option. Since the selection is required, instead check if the returned value is NULL, then you know that nothing else was selected.
Example:
If (is_null($_SESSION['post']['gender'])) {
$_SESSION['post']['gender'] = 'Gender';
}
With this if/else, you're changing the variable to Gender (The selected disabled option) if the disabled option is "selected".
Thanks you #Stoff,
After adding a value="" to option selected, I changed the Javavscript to this :
var idGender = document.getElementById('gender').value = "<?php echo
$_SESSION['post']['gender'] ?? '' ?>";
And now, its works :D
Related
So to continue my last question (link). I've finally got that sorted out (with help), but now the value of the name is only the first value of the drop down list.
A brief explanation, I have 2 drop down menu's and when you select a option from one (A) the other drop down menu is updated (B). I know it has something to do with an array but I can't figure this out.
Here are my files.
HTML
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<?php
$sttub = str_replace('&', 'en', $stub);
$q = $row["Categorie"];
echo "
<option class='dropdownmenu_A' value='".$sttub."' name='".$q."'>"
.$row["Categorie"]."
<span style='font-size:1.2rem;color:#F8F8F8;'>
(" . $row['x'] . ")
</span>
</option>
";
}}?>
</select>
<select name="sub_cat" id="sub_cat" disabled="disabled"></select>
JavaScript
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
var $mainName = $(".dropdownmenu_A").attr("name");
// call ajax
$("#sub_cat").empty();
$.ajax({
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_call&main_catid=' + $mainCat + '&main_name=' + $mainName,
success:function(results)
{
// alert(results);
console.log($mainCat,$mainName);
$("#sub_cat").removeAttr("disabled");
$("#sub_cat").append(results);
}
});
}
);
});
function.php
function implement_ajax() {
if(isset($_POST['main_catid']))
{
$q = $_POST['main_catid'];
$x = $_POST['main_name'];
echo '<option value="-1" selected="selected">'.$x.'</option>'.$option;
die();
} // end if
}
I have tried using <select id="main_cat" name="main_cat[]"> like I found on google but this didn't work. Using $x[] = $_POST['main_name']; just echos the word Array. How do I get this to work and display the correct option that is selected and not just the first every time.
To be clear, here are my drop down menu's (sometimes my brain goes faster then I can type, so I hope it's clear).
select{height:30px}
<select id="main_cat" name="main_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_A' value='option-1' name='Option 1'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
<option class='dropdownmenu_A' value='option-2' name='Option 2'>
</select>
<select id="sub_cat" name="sub_cat">
<option selected="-1" select="selected">Select something</option>
<option class='dropdownmenu_B' value='sub-option-1' name='Sub Option 1'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
<option class='dropdownmenu_B' value='sub-option-2' name='Sub Option 2'>
</select>
So right now if I select Option 1 from dropdownmenu_A it only echo's the first value from dropdownmenu_A to dropdownmenu_B and not Option 2 or Option 3.
1- You can't have <span/> tags inside <option/> tags as the latter cannot have any child elements.
2- <option/> doesn't have a name attribute. If you want to create a custom attribute, use HTML5 data attributes. That's what they are for.
3- printf is your new friend.
printf('<option class="dropdownmenu_A" value="%s" data-name="%s">%s (%s)</option>', $sttub, $q, $row["Categorie"], $row['x']);
4- I believe the problem is $(".dropdownmenu_A").attr("name") as this would always pull the same name and not the selected name. In your particular case, I would do
$(function(){
$('#main_cat').change(function(){
var $option = $(this).find('option:selected'),
id = $option.val(),
name = $option.data('name');
// open your browser's console log and ensure that you get the correct values
console.log(id, name);
$("#sub_cat").empty();
// call ajax
$.ajax({
url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data: {
action: 'my_special_ajax_call',
main_catid: id,
main_name: name
},
success: function (results) {
$("#sub_cat").removeAttr('disabled').html(results);
}
});
});
});
You should add a selected attribute to your selected option:
https://www.w3schools.com/tags/att_option_selected.asp
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;
});
A dropdown select box is populated from a database and the selected option is matched against a variable $comp_cntry currently on the page:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
Then later on a telephone prefix (dialling code) box is populated from the same database, matching the dialling code to the country:
<?php
// Get Dialling Codes
$telephone_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country = $tq['country_name'];
// Show Prefix
if ($country == $comp_cntry) {
$prefix = $tq['dialling_code'];
}
}
?>
<input type="text" name="telephone_prefix" value="+<?=$prefix?>" readonly>
How, using JavaScript, can I get the telephone prefix to automatically change on page when a new option is chosen from the country dropdown? I have no real knowledge of JavaScript at all, unfortunately, but assume I would need to somehow convert my PHP associated array in to JSON so that I can use it?
I know I haven't provided any JavaScript code to show that I've made a start on this part of the problem, but if someone could point me in the right direction that would be swell.
Disclaimer: please ignore my terrible use of the mysql_ extension
I would add a data attribute (here it might be called data-prefix) to the element, like
<option value='country' data-prefix='+44'/>
and get this when the onChange event is fired for the select. In jQuery you could do something like
$('[name="country"]').change(function(){
$('[name="telephone_prefix"]').val($(this).find(':selected').data('prefix'));
});
which would update the value accordingly.
I would say the best way of doing this would be joining the two PHP codes like this:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $cq['dialling_code'];
// Select Current Country
echo "<option data-prefix='{$prefix}' value='{$country}' ";
if($country == $comp_cntry) echo "selected";
echo ">{$country}</option>";
}
?>
</select>
<input type="text" name="telephone_prefix" value="" readonly>
And this would return a list of the countries in a dropdown each with a data-prefix attribute of the appropriate prefix that they have.
We would then need to trigger jQuery on change and update the value, and this would look something like:
$("select[name=country]").on('change', function() {
var prefix = $("option:selected", this).attr('data-prefix');
$("input[name=telephone_prefix]").attr('value', prefix);
})
And this would have the following effect: http://jsfiddle.net/Tm75y/1/
I hope that's what you need.
Simply pass the prefix as an attribute of the select options:
<select id="country-select" name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $tq['dialling_code'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" prefix="<?=$prefix?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
<input id="prefix-input" type="text" name="telephone_prefix" value="" readonly>
JAVASCRIPT
Then add a change handler to your select to get the prefix attribute of the selected option and set the text input:
$(function(){
$("#country-select").change(function(){
var prefix = $(this).find("option:selected").attr("prefix");
$("#prefix-input").val(prefix);
});
});
My suggestion would be to saving a javascript object which maps countries to phone codes, so when your country select has a change, you can trigger a change to the telephone prefix via javascript.
So let's assume you have a map (associative array) in javascript that is something like this:
$country_to_phone_prefix_map = array(
'country name A' => 'phone prefix A',
'country name B' => 'phone prefix B',
...
);
This could be built in your query while loop:
$country_to_phone_prefix_map = array();
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country_to_phone_prefix_map[$tq['country_name']] = $tq['dialing_code'];
}
Then when rendering the page, inject this map into javascript
<script type="text/javascript">
var countryToPhonePrefixMap = <?php echo json_encode($country_to_phone_prefix_map); ?>;
</script>
Now, you build a change event listener on the country dropdown to change the value:
$('select[name="country"]').change(function() {
// get phone prefix from map
var selectedCountry = $(this).val();
var phonePrefix = countryToPhonePrefixMap[selectedCountry];
// change value of telephone prefix input
$('input[name="telephone_prefix"]').val(phonePrefix);
}
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."'");
}
}
?>
I am working on a project in which I need to create a form with a dropdown field for category. And according to the category selected, I have to populate the second drop down called subcaste.
This I am achieving through AJAX.
I also wrote a method which will be called on change of the category to disable the sub caste dropdown box if the selected category is OPEN as:
if(str=="OPEN"||str=="open"){
document.form.subcaste.disabled=true;
}
But when I hit the submit button, i get a null pointer exception in the line:
subCaste = request.getParameter("subcaste");
in the servlet. (This line takes the value of the subcaste from the jsp page).
I have also done: <option value="none" selected="selected">Select</option>
in the drop down of the subcaste so that a default value is selected. But I still get a null pointer exception. I believe that after I disable the dropdown box, the value isnt available to the servlet at all.
The detailed code is:
JSP:
<td id='category'><select name='category' onchange="showSubCaste(this.value);">
<option value="none" selected="selected">Select</option>
<% for (i = 0; i < categorySize; i++) {%>
<% category = (String) categoryArr.get(i);%>
<option value=<%= category%>><%= category%></option>
<% }%>
</select>
</td>
<td >SubCaste</td>
<td id='subcaste'> <select name='subcaste'>
<option value="none">Select</option>
</select>
</td>
JavaScript:
function showSubCaste(str){
...
if(str=="OPEN"||str=="open"){
document.form.subcaste.disabled=true;
document.form.issuingAuthority.disabled=true;
}
else{
document.form.subcaste.disabled=false;
document.form.issuingAuthority.disabled=false;
var url="SubCasteController";
url +="?caste=" +str;
...}
After retrieving the values in a servlet and passing it to another JSP:
<%String buffer = "<select name='subcaste' onchange='subCasteChanged(this.value);'><option value='none' selected='selected'>Select SubCaste</option>";
for (int i = 0; i < sizeInfo; i++) {
subCaste = (String) retrievedInfo.get(i);
buffer = buffer + "<option value='" + subCaste + "'>" + subCaste + "</option>";
}
buffer = buffer + "</select>";
response.getWriter().println(buffer);
%>
I do not know how to proceed with this. Please help me.
Thank you in advance.
Yes , you are right . If the <select> is disabled , its values will not be POSTED. So when you get its value using request.getParameter() , it will return null pointer exception.
The standard practices to get a disabled <select> to post its value are
Add a hidden input field that will submit the same value and copy the value from the disabled <select> to this hidden field in the <form> 's onsubmit() event
or
Re-enable the disabled <select> in the <form> 's onsubmit() event
Or alternatively , as you believe the null pointer exception is because subCaste is set to null ,you can try to to set subCaste variable to some specific value if the subCaste parameters is null to see if it can be solved.
if ( request.getParameter("subcaste") != null){
subCaste = request.getParameter("subcaste");
}else{
subCaste = "xxxxx"; //set to a specific value according to your requirement.
}
Reference
HTML form readonly SELECT tag/input