jQuery Dropdown Menu + PHP - keeping selection - php

I'm not very experienced at JS (PHP is my strong side) so I need your help about something.
I have a script with 2 drop down menus that shows hidden content. I'm using this example Change content based on select dropdown id in jquery
When I execute a PHP script, it checks for errors and if there are some it will return the user to the form. The problem with this is that it will not show the hidden content. I can set some sort of PHP vars and put them in the input like $selected_one = 'selected="selected"' and the dropdown menus will have the right selection, but the jQuery function does not work like that. I think it puts some sort of class that shows and hides the content.
I can't quite put my finger on what's going on, so I need your help. Can any body give me a hint how to fix this?
Here's some code to make things visual
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<style>
.list_publish, .list_news, option_value {
display: none;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body>
<?php
$selected_news = '';
$selected_review = '';
$selected_news_text = '';
$selected_news_video = '';
if(isset($_POST['submit_news_text'])){
$selected_news = 'selected="selected"';
$selected_news_text = 'selected="selected"';
$news_title = $_POST['news_title'];
// Checks blank forms and return error
if(empty($news_title)) {
$error_message = 'This field must not be empty!';
$proceed = false;
} else {
$proceed = true;
}
}
if($proceed){
// do stuff
echo 'do stuff';
} else {
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<select class="change_publish" name="publish_type" id="publish_type" style="width: 238px;">
<option value="publish_type" data-title="choose">Publishing...</option>
<option value="publish_news" data-title="news" <?php echo $selected_news ?>>Publish News</option>
<option value="publish_review" data-title="review" <?php echo $selected_review ?>>Publish Review</option>
</select>
<div class="list_publish publish_type">
</div>
<div class="list_publish publish_news">
<select class="change_news" name="news_type" id="news_type" style="width: 238px;">
<option value="news_type" selected="selected" data-title="choose">News Type</option>
<option value="news_text" data-title="text" <?php echo $selected_news_text; ?>>Text</option>
<option value="news_video" data-title="video"<?php echo $selected_news_video; ?>>Video</option>
</select>
<div class="list_news news_type">
</div>
<div class="list_news news_text">
<input name="news_title" type="text" id="news_title">
<input name="submit_news_text" type="submit" value="Publish" id="submit_news_text" />
</div>
<div class="list_news news_video">
> This function is not available at the moment.
</div>
</div>
<div class="list_publish publish_review">
> This function is not available at the moment.
</div>
</form>
<?php
echo $error_message;
}
?>
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
});
</script>
</body>
</html>
And here's a demo http://www.demirevdesign.com/public/form.php

Trigger the change event on document load, like here:
<script>
// дропдаун меню
$('.change_publish').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_publish').length;
$('.list_publish').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
$('.change_news').change(function(){
var selected = $(this).find(':selected');
$('.optionvalue').fadeOut(function(){
$('.optionvalue').html(selected.html()).fadeIn()
.attr('class', 'optionvalue '+selected.val());
});
var count = $('.list_news').length;
$('.list_news').slideUp(function(){
if(!--count) {
$('.'+selected.val()).slideDown();
}
});
}).change(); // HERE THE CHANGE
</script>

Related

Why My Code didn't display Date (dd-M-yy format) in the input field after selected?

Below is my code.
Firstly, run the index.php Then there is a dropdown list will display and need to select a value from the dropdown. so far, dropdown will display value 1 or 2. If you select 2 it will display the value that has been selected together with the "date" field called from the display-date.php and from the "date" field, you may choose the date from calendar which called using datepicker plugin.
Now.. the problem is...I had select the date from calendar but the date selected didn't appear in the date input field. where am I wrong?
Hope anyone could help me please... :)
Thanks.
Here is index.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<script>
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}
else {
// IE5/IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("results").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-date.php?q="+str, true);
xhr.send(null);
}
}
</script>
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.value)">';
echo '<option value="None">-- Select Option --</option>';
echo '<option value="1">One</option>';
echo '<option value="2">Two</option>';
echo '</select>';
?>
</div>
<br/><br/>
<p>You selected: <span id="results"></span></p>
</body>
</html>
Here is display-date.php
<?php
$Q = $_GET["q"];
echo $Q;
?>
<?php
if ($Q == '2'){
?>
<html>
<head>
<style>
#date_input{
text-indent: -500px;
height:25px;
width:200px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="dd-M-yy" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
<script type="text/javascript">
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px",
top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" :
($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
</script>
</body>
</html>
<?php
}
?>
Modify the display-date.php . Html base structure is no longer needed.
<?php
$Q = $_GET["q"];
echo $Q;
?>
<?php
if ($Q == '2'){
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="dd-M-yy" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
<script type="text/javascript">
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px",
top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" :
($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
</script>
<?php
}
?>
There is no need to use ajax in your case, Ajax must not be used the way you showed in your question.
Ajax not used to draw html in DOM
No need to use ActiveXObject , It is insecure and I don't think we should support IE 5 or IE 6 anyways in modern development.
If you need to use ajax, Use JQuery's ajax function instead of XMLHttpRequest, As i see you are already using it.
Here is the code which works without ajax and works as it should be.
function getData(str){
$('.showInput').hide();
$('.showText').text('');
if(str != ""){
str = parseInt($.trim(str));
if(str == 2){
$('.showInput').show();
}else{
$('.showText').text(str);
}
}
}
$(document).ready(function(){
$("#date_input").datepicker({ dateFormat: 'dd-M-yy' });
});
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
</head>
<body>
<style>
.showInput{
display:none;
}
</style>
<div>
<select title="Select one" name="selectcat" onChange="getData(this.value)">
<option value="">-- Select Option --</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<br/><br/>
<p>You selected: <span id="results">
<span class="showText"></span>
<span class="showInput">
<input id="date_input" dateformat="dd-M-yy" type="text"/>
</span>
</p>
</body>
</html>

Update <div> content on a <select> change with php

My goal is to show a second "select" in a "div" with options depending on the selection made by the user on the first "select".
The first "select" is a list of regions, while the second is the list of provinces in the forementioned region.
The function 'change' should update the div 'province', passing a value to another php file used for determining the provinces, with the second select but that doesn't happen.
Main page:
<?php
$region= array("","Abruzzo", "Basilicata", "Calabria");
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
function change(value) {
$('province').load('select.php?id='+ value);
}
</script>
<body>
<div>
<select onchange="change.call(this.value)">
<?php
for($i=0;$i<count($region);$i++)
{
echo "<option value=".$i.">".$region[$i]."</option>";
}
?>
</select>
</div>
<div id="province"></div>
</body>
</html>
Script for updating:
<?php
$vector=array(1 =>array("CH","AQ","PE","TE"),
2 => array("MT","PZ"),
3 => array("CZ","CS","KR","RC","VV"));
$id = $_GET['id'];
if($id==0)
{
echo "";
}
else{
for($i=1;$i<(count($vector)+1);$i++)
{
$n=key($vector)
if($n==$i)
{
echo "<select>";
$content=current($vector);
for($k=0;$k<count($content);$k++)
{
echo "<option>".$content[$k]."<option>";
}
echo "</select>";
break;
}
else
{
next($vector);
}
}
}
?>
You're missing the id selector # in :
$('#province').load('select.php?id='+ value);
Hope this helps.
function change(_this) {
console.log(_this.value)
$('#province').load('select.php?id='+ _this.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select onchange="change(this)">
<option value="0"></option>
<option value="1">Abruzzo</option>
<option value="2">Basilicata</option>
<option value="3">Calabria</option>
</select>
</div>
<div id="province"></div>
You are missing the # from the id selector and the ; from $n=key($vector) in your PHP file used for update. Also, if you tagged your question jQuery you should use it. Inline onchange is deprecated and I will recommend you NOT to use it anymore.
Change this:
$n=key($vector)
to this:
$n=key($vector);
jQuery code should look like this:
$('select').on('change', function() {
var selected = $(this).find(":selected").val();
$('#province').load('send.php?id=' + selected);
});
And HTML like this:
<div>
<select name='select'>
<?php for($i=0;$i<count($region);$i++) { echo "<option value=".$i. ">".$region[$i]. "</option>"; } ?>
</select>
</div>
<div id="province"></div>
**Main page:**
<?php
$region= array("","Abruzzo", "Basilicata", "Calabria");
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#region").change(function(){
var value=$(this).val();
$("#province").load('select.php?id='+value);
});
});
</script>
<body>
<div>
<select id="region" >
<?php
for($i=0;$i<count($region);$i++)
{
echo "<option value=".$i.">".$region[$i]."</option>";
}
?>
</select>
</div>
<div id="province"></div>
</body>
</html>
**Script for updating:**
<?php
$vector=array(1 =>array("CH","AQ","PE","TE"),
2 => array("MT","PZ"),
3 => array("CZ","CS","KR","RC","VV"));
$id = $_GET['id'];
if($id==0)
{
echo "";
}
else{
if(array_key_exists($id,$vector))
{
echo "<select>";
for($i=0;$i<(count($vector[$id]));$i++)
{
echo "<option>".$vector[$id][$i]."</option>";
}
echo "</select>";
}
}
?>

Dropdown list not work with data-native-menu="false"

I use dropdown list with PHP to retrieve data from my sql database, It exists on this link.
It worked well but when I change the menu style what I want, does not work.
this menu code is what I want:
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
I think the problem exists because the menu shows in popup : `#&ui-state=dialog`
but I do not know how to solve this problem.
this full HTML code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat" data-native-menu="false" class="filterable-select" data-iconpos="left">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>
Please help

PHP: Fill combobox after choosing one option from another combobox using MySQL database

I have one combobox where I choose one option filled it up with the table 'distrito' where the columns it's 'ID' and 'nome'.
So far, so good. The problem is when I want to fill it up the other combobox depending on the option select in the first combobox. The table 'localidade' that fills this combobox uses the columns 'id', 'nome' and 'id_distrito'.
This is the code to fill the first combobox called 'distrito':
<?php
// Connects to your Database
include "config.php";
$QUERY_LISTAR_DISTRITO = "SELECT id, nome FROM distrito";
$DISTRITO = mysql_query($QUERY_LISTAR_DISTRITO) or die(mysql_error());
$nr_distrito = mysql_num_rows($DISTRITO);
while ($nr_distrito > 0) {
$row = mysql_fetch_row($DISTRITO);
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
$nr_distrito--;
}
?>
This is the code to fill the second combobox called 'localidade':
<?php
// Connects to your Database
include "config.php";
$id_distrito = $_GET['distrito'];
$QUERY_LISTAR_LOCALIDADE = "SELECT * FROM localidade WHERE localidade.id_distrito = $id_distrito";
$LOCALIDADE = mysql_query($QUERY_LISTAR_LOCALIDADE) or die(mysql_error());
$nr_localidade = mysql_num_rows($LOCALIDADE);
while ($nr_localidade > 0) {
$row = mysql_fetch_row($LOCALIDADE);
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
$nr_localidade--;
}
?>
This is the HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test</title>
</head>
<body>
<form action="registarGestorBD.php" method="post" enctype="multipart/form-data">
Distrito: <select name="distrito" id="distrito">
<?php include 'listarDistritos.php'; ?>
</select> <br> <br>
Localidade: <select name="localidade" id="localidade">
<?php include 'listarLocalidades.php'; ?>
</select> <br> <br>
<input type="submit" name="button1" id="button1" value="Guardar">
</form>
</body>
</html>
Thanks in advance. :)
This will solve your problem. Change your HTML file to this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form action="registarGestorBD.php" method="post" enctype="multipart/form-data">
Distrito: <select name="distrito" id="distrito">
<?php include 'listarDistritos.php'; ?>
</select> <br> <br>
Localidade: <select name="localidade" id="localidade">
</select> <br> <br>
<input type="submit" name="button1" id="button1" value="Guardar">
</form>
<script type="text/javascript">
$(document).on('change','#distrito',function(){
var val = $(this).val();
$.ajax({
url: 'listarLocalidades.php',
data: {distrito:val},
type: 'GET',
dataType: 'html',
success: function(result){
$('#localidade').html();
$('#localidade').html(result);
}
});
});
</script>
</body>
</html>
What you need is basically an ajax call which will fire on the selection of first combo box. The ajax call will sends the value of the first combo box and will query the other table based on id.
this might help you
Combobox items based on selected item in another combobox
You need to be looking at ajax. Consider this example (modified from Wikipedia):
function sendToServer(){
// Initialize the Ajax request
var xhr = new XMLHttpRequest();
xhr.open('post', 'send-ajax-data.php');
// Track the state changes of the request
xhr.onreadystatechange = function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
var options = xhr.responseText.split(",");
populateComboBox(options)
}
}
}
// Send the request to send-ajax-data.php
xhr.send(distrito_id);
}
function populateComboBox(options){
var combo = document.getElementById("localidade");
$(options).each(function(i){
var opt = options[i];
var el = document.createElement("option");
el.textContext = opt;
el.value = opt;
combo.appendChild(el);
})
}
Then of course in your php, get the post variable distrito_id, do your query and return the results in a comma separated list!

loading php script inside html page

I want to load a page on select on change event. But it aint displaying the page. the content on the page is just: this is bank/ this is cash.
<!DOCTYPE html>
<html>
<select id = "ddl" onchange="changeSheet()">
<option value = "bank">Bank Statement</option>
<option value = "cash">Cash Book</option>
</select>
<div id = "sheet">
</div>
<script>
function changeSheet()
{
document.getElementById('sheet').innerHTML = "";
var e = document.getElementById("ddl");
var strUser = e.options[e.selectedIndex].value;
if(strUser == 'bank')
{
$("#sheet").load("bank.php");
}
else
{
$("#sheet").load("cash.php");
}
}
</script>
This is the right way to do that using JQuery: DEMO
<!DOCTYPE html>
<html>
<select id = "ddl" onchange="changeSheet()">
<option value = "bank">Bank Statement</option>
<option value = "cash">Cash Book</option>
</select>
<div id = "sheet"></div>
<script>
$(document).ready(function(){
$("#ddl").change(function(){
if($(this).val() === "bank")
$("#sheet").load("bank.php");
else
$("#sheet").load("cash.php");
});
});
</script>

Categories