put selected values from textbox and dropdown to a basket like amazon - php

I have a PHP survey form in which there is a question "Which are your favourite movies?". for this question, I put a dropdown which enable users to select movies by title or by actor. If user select "by title", a textbox (auto-complete) will be shown where he can insert a movie name. If user select "by actor", a new window will be opened containing a textbox where user should insert an actor name, then a dynamic dropdown is populated showing list of movies by that actor.
Question:
How can I get the selected movies (from textbox and also dropdown in new window) and put them in a basket like amazon shopping cart? I searched a lot, but I really could not find the solution.. I can put the selected values in a new dropdown, but my professor asked me to use the same method like amazon and put them in a basket!!
UPDATE:
Here is what I have tried:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
</head>
<body>
<div class="movienames">
<select id="selectType" name="source" style="size=5px; width:100px; height:30px;">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
<option value="byDirector">byDirector</option>
</select>
<div id="m_scents">
<p>
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" style="display:none;" placeholder="Enter movie titles here" />
<!--Add more movies-->
<input type="button" value=">> Add to selected list >>" id="btnMove" style="display:none;"/>
<input name="s" value="all" type="hidden"/>
<label style="margin-bottom:10px;" for="m_scnts"></label>
</p>
</div>
<select id="selectedItems" name="selectedItems[]" multiple="multiple" style="width:200px; size:10px;">
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#selectType").change(function () {
if ($(this).val() == "byTitle") {
$("#q").show();
$("#btnMove").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay:5,
source: "mona.php",
focus: function( event, ui ){
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function( event, ui ) {
$(this).val( ui.item.movieName );
return false;
}
}).data("uiAutocomplete")._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<a>" + (item.posterLink?"<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />":"") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>" )
.appendTo( ul );
};
} else
if ($(this).val() == "byActor"){
window.open("target.html","_blank","height=400,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
});
});
$('#btnMove').on('click', function (d) {
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
}
$('#selectedItems').append(new Option(selected));
var title = new Option(selected);
$("#q").val("");
d.preventDefault();
});
</script>
</body>
</html>
and this is target.html:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"type="text/javascript"type="text/javascript"></script>
</head>
<body>
<form>
<p>
<input type="textbox" name= "tag" id="tags" placeholder="Enter an actor/actress name here" />
</p>
<p>
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style="display:none;">
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
focus: function( event, ui ){
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function (event, ui){
var selectedVal = ui.item.value;
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}
});
});
</script>
</form>
</body>
</html>
Could someone kindly inform me if there is any tutorial or sample that I can use for this purpose?
All ideas are highly appreciated,
Thanks

ok for the first part I would do the following:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<style>
#basket{
padding: 10px;
border:1px solid #ccc;
}
#basket h3{
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div class="movienames">
<select id="selectType" name="source" style="font-size:15px; width:100px; height:30px;">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
<option value="byDirector">byDirector</option>
</select>
<div id="m_scents">
<p>
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" style="display:none;" placeholder="Enter movie titles here" />
<!--Add more movies-->
<input type="button" value=">> Add to selected list >>" id="btnMove" style="display:none;"/>
<input name="s" value="all" type="hidden"/>
<label style="margin-bottom:10px;" for="m_scnts"></label>
</p>
</div>
<div id="basket">
<h3>Basket</h3>
<div id="basket_content">
</div>
</div>
JS:
var master_basket = new Array();
$(document).ready(function() {
$("#selectType").change(function() {
if ($(this).val() == "byTitle") {
$("#q").show();
$("#btnMove").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay: 5,
source: "mona.php",
focus: function(event, ui) {
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function(event, ui) {
$(this).val(ui.item.movieName);
return false;
}
}).data("uiAutocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + (item.posterLink ? "<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />" : "") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>")
.appendTo(ul);
};
} else
if ($(this).val() == "byActor") {
window.open("target.html", "_blank", "height=400,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
});
});
$('#btnMove').on('click', function(d) {
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
addToBasket(selected);
}
$("#q").val("");
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div>" + v + "</div>");
});
}

Related

Fetch the id of the country dynamically in the URL after click on submit button or search button

This is controller.php
<?php
class Autocomplete extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('datacomplete');
}
public function index($id)
{
echo $id;
$this->load->view('view_demo', $data);
}
public function GetCountryName()
{
$keyword = $this->input->post('keyword');
$data = $this->datacomplete->GetRow($keyword);
echo json_encode($data);
}
}
?>
This is a model
<?php
class Datacomplete extends CI_Model
{
public function GetRow($keyword)
{
$this->db->order_by('id', 'DESC');
$this->db->like("name", $keyword);
return $this->db->get('autocomplete')->result_array();
}
}
this is view.php
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js">
</script>
<script src="<?php echo base_url(); ?>assets/custom.js">
</script>
</link>
</head>
<body style="background-color: #000000;">
<?php echo $id= 1; ?>
<form action="<?php echo base_url('autocomplete/index/' .$id); ?>" method="post">
<div class="row">
<center>
<h2 style="color: #fff;">
AUTOCOMPLETE FORM FROM DATABASE USING CODEIGNITER AND AJAX
</h2>
</center>
<div class="col-md-4 col-md-offset-4" style="margin-top: 200px;">
<label class="control-lable" style="color: #fff;">
Country Name
</label>
<input autocomplete="off" class="form-control" id="country" name="country" placeholder="Type to get an Ajax call of Countries" style="height:70px" type="text">
<ul aria-labelledby="dropdownMenu" class="dropdown-menu txtcountry" id="DropdownCountry" role="menu" style="margin-left:15px;margin-right:0px;">
</ul>
<input type="submit">
</input>
</input>
</div>
</div>
</form>
</body>
</html>
This is custom.js file
$(document).ready(function() {
$("#country").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/codeajax/autocomplete/GetCountryName",
data: {
keyword: $("#country").val()
},
dataType: "json",
success: function(data) {
if (data.length > 0) {
$('#DropdownCountry').empty();
$('#country').attr("data-toggle", "dropdown");
$('#DropdownCountry').dropdown('toggle');
} else if (data.length == 0) {
$('#country').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">' + value['name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#country').val($(this).text());
});
});
I want to fetch the id of the country dynamically in the URL after clicking the submit button.
Now I have this using static passing id as 1.
the table has two column id and name of the country.
how to pass the id dynamically to url when I click the submit button.
I m failing to fetch the id dynamically from database ie when I click on submit should redirect to the new page with country id or echo $id in the new page as well as to the URL it should show me id of the country
You could achieve it using javascript.
First change the form :
<form action="<?php echo base_url('autocomplete/index/' .$id); ?>" method="post">
To :
<form method="post" id="countryForm">
Then change the submit button :
<input type="submit">
To :
<input type="submit" id="submitForm" disabled>
And then apply the following javascript codes :
$(document).ready(function() {
$("#country").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/codeajax/autocomplete/GetCountryName",
data: {
keyword: $("#country").val()
},
dataType: "json",
success: function(data) {
if (data.length > 0) {
$('#DropdownCountry').empty();
$('#country').attr("data-toggle", "dropdown");
$('#DropdownCountry').dropdown('toggle');
} else if (data.length == 0) {
$('#country').attr("data-toggle", "");
}
// Assign each country id into each country list `data-` element
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" data-countryid="' + value['id'] + '" class="dropdownlivalue">' + value['name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#country').val($(this).text());
$('#countryForm').attr('action', '<?php echo base_url('autocomplete/index/'); ?>' + $(this).data('countryid'); // set new form action which contain country id
$('#submitForm').removeAttr('disabled'); // enable the submit button after one country is selected
});
});

select box validation

below is the code for selectbox validation but it is not working..can anybody help please..
<?php include('../config.php'); ?>
<style>
#errorMessage {
color:red;
font-size:12px;
margin-left:10px;
}
</style>
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"> </script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"> </script>
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#agentlist" ).validate({
rules: {
field: {
required: true
}
}
});
</script>
<div id="distanceform" style="width:100%; height:auto;border:0.1em solid #CCC;float:left;">
<div id="distanceformtitle" style="border-bottom:0.1em solid #CCC;width:98%;height:25px;text-align:left;font-size:13px;padding-left:2%;padding-top:11px;background-color:#FAFAFA;color:#1D89CE;">Distance Report</div>
<div id="errorMessage"></div>
<span>
<select name="agentlist" id="agentlist" class="selectclass">
<option value="">--Select Agent--</option>
<?php
$x=mysqli_query($con,"select * from accounts where gid='0' and companyid='".$_SESSION['newforcecid']."' and publishstatus='1'");
while($data=mysqli_fetch_assoc($x)){
?>
<option value="<?php echo($data['imeino']); ?>">
<?php echo($data['firstname']); ?></option><?php
}
?>
</select>
</span>
<span><input type="text" class="textclass" name="fromdate" id="fromdate" placeholder="From Date" value="<?php echo(date('d-m-Y')); ?>"></span>
<span><input type="text" class="textclass" name="todate" id="todate" placeholder="To Date" value="<?php echo(date('d-m-Y')); ?>"></span>
<input type="button" id="search" name="search" value="Search" class="btnclass">
</div>
<br>
<div id="distanceresult" >
</div>
validation is not working..when i click on submit data is not gettng displayed and at same time error msg is also not gettng displayed
Just you need to add the dateFormat: 'dd-mm-yy', after number of months
Check Demo here
<script>
$(function () {
$("#txtFrom").datepicker({
numberOfMonths: 1,
dateFormat: 'dd-mm-yy',
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() + 1);
$("#txtTo").datepicker("option", "minDate", dt);
}
});
$("#txtTo").datepicker({
numberOfMonths: 1,
dateFormat: 'dd-mm-yy',
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() - 1);
$("#txtFrom").datepicker("option", "maxDate", dt);
}
});
});
</script>
You can use dateFormat:"dd-mm-yy" in the options. Please do check out all the possible dateFormats Here
Assuming that you are using jQuery-ui:
var date=$.datepicker.formatDate( "dd-mm-yy", new Date( 2015, 2 - 1, 25 ) );
Value of date will be: 2015-02-25

How to save the text box data in mysql table

I am using a map to obtain the co ordinates of the location, and get it on my text box named "add". When I try to insert the data obtained from the text box into the table it shows error.
This is my code below:
<html>
<head>
<link href="modal.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="POST">
<table>
<tr><td>
</br>GIS Stamp</td>
<td><br><input type="text" name="add" id="add" size="31" value="" disabled="disabled"/><a href="#login_form" id="login_pop">
Select From MAP</a>
<div class="popup">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
add.value=[
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(12.941320125683307, 74.86030859375);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#mapCanvas {
width: 500px;
height: 400px;
float: left;
}
#infoPanel {
display:none;
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
</html>
<a class="close" href="#close"></a>
</div><br></td>
</tr>
<!-- panel with buttons -->
<tr><td>
<input type="submit" name="submit" value="Insert"></td></tr></table>
</body>
</form>
</html>
<?php
if(isset($_POST['submit']))
{
$add=$_POST['add'];
$c=mysql_connect("localhost","root","");
mysql_select_db("hudadb");
$ins=mysql_query("INSERT INTO `death`
(GIS)
VALUES ('$add')",$c) or die(mysql_error());
}
?>
The error I'm getting is:
Notice: Undefined index: add in D:\XAMPP\htdocs\hudaf\mainproj\s\s.php
Elements with Disabled attribute are not submitted or you can say their values are not posted.
Replace this line of code
<input type="text" name="add" id="add" size="31" value="" disabled="disabled"/>
with
<input type="text" name="add" id="add" size="31" value="" readonly/>
NOTE: Remember disabled field is not submitted with form submit, you need to use readonly for that.

How do I make this program add two boxes rather than one?

I am having trouble with this code. I don't understand how to add another box apart from the one that it already adds with ajax within the code when I press the link Add more. I want to be able to add two text boxes when I press the add more link, one for hobby and another one for age but I only get one. What I tried was on the on click function I tried to add another var html_box2 but it did not work out.
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form role="form" method="post">
<p class="text-box">
<label for="box1">Box <span class="box-number">1</span></label>
<input type="text" name="boxes[]" value="" id="box1" />
<a class="add-box" href="#">Add More</a>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('.my-form .add-box').click(function(){
var n = $('.text-box').length + 1;
if( 5 < n ) {
alert('Stop it!');
return false;
}
var box_html = $('<p class="text-box"><label for="box' + n + '">Box <span class="box-number">' + n + '</span></label> <input type="text" name="boxes[]" value="" id="box' + n + '" /> Remove</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
These lines of code add one box
var box_html = $('<p class="text-box">whatever goes here</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
You can copy and modify them to create another box like
var box_html = $('<p class="text-box">whatever goes here</p>');
box_html.hide();
$('.my-form p.text-box:last').after(box_html);
box_html.fadeIn('slow');
var box_html2 = $('<p class="text-box">whatever has to go here</p>');
box_html2.hide();
$('.my-form p.text-box:last').after(box_html2);
box_html2.fadeIn('slow');

Ajax+PHP to implement cascading select

I have a demo.html page, which contains two selections, the first one is "Type", and the second one is "Config", when I choose a certain type in the first selection, I want to use ajax to update the values in the second selection.
For example, Type may have values: VM, Server, DCA
and VM only has config "singe node", but DCA has Config "d0"-"d48". so if I select DCA in the first selection, I should have 49 options in the second one.
I searched online and did find some solutions, then I wrote some code by myself. The problem now is that whatever I select in the first selection, the second one will not be updated, it always return null.
Not sure where the prob is, the code looks fine :( Thanks for any help.
demo page
<html>
<head>
<meta charset="utf-8">
<title>Reservation System</title>
<link href="jquery/ui/css/sunny/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/mrbs-page.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/mrbs-table.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/ColReorder.css" rel="stylesheet" type="text/css">
<link href="jquery/datatables/css/ColVis.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="css/mrbs.css.php" type="text/css">
<link rel="stylesheet" media="print" href="css/mrbs-print.css.php" type="text/css">
<meta name="robots" content="noindex">
<script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-1.8.22.custom.min.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-i18n.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-datepicker-en.js"></script>
<script type="text/javascript" src="jquery/ui/jquery-ui-datepicker-en-US.js"></script>
<script type="text/javascript" src="jquery/datatables/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="jquery/datatables/js/ColReorder.min.js"></script>
<script type="text/javascript">
var xmlhttp;
var url;
function createXMLHttpRequest() {
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function showConfig(str) {
url = "getOptions.php?type="+str;
createXMLHttpRequest();
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {handleStateChange()};
}
function handleStateChange() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var str = xmlhttp.responseText;
alert (url);
createConfig(str);
}
}
function createConfig(str) {
var configs = str;
var config = configs.split(",");
while (document.getElementById("config").options.lengt>0)
document.getElementById("config").options.remove(0);
for (var i=0; i<config.length; i++)
{
var ooption = document.createElement("option");
ooption.value = config[i];
ooption.text = config[i];
document.getElementById("config").add(ooption);
}
}
</script>
<form id="add_room" class="form_admin" action="add.php" method="post">
<fieldset>
<legend>Add DCA</legend>
<input type="hidden" name="type" value="room">
<input type="hidden" name="area" value="2">
<div>
<label for="room_name">Name:</label>
<input type="text" id="room_name" name="name" maxlength="50">
</div>
<div>
<label for="room_description">Description:</label>
<input type="text" id="room_description" name="description" maxlength="100">
</div>
<div>
<label for="room_type">Type:</label>
<select class="room_area_select" id="type_select" name="area" onchange="showConfig(this.value)"><option value="VM">VM</option><option value="Server">Server</option><option value="DCA-V1">DCA-V1</option><option value="DCA-V2">DCA-V2</option></select>
</div>
<div>
<label for = "config">config:</label>
<select id="config" ></select>
</div>
</fieldset>
</form>
getOptions.php file
<?php
$type = $_GET['type'];
echo $type;
$result = "";
if ($type == "DCA-V1") {
for ($i=0;$i<47;$++)
$result .= $i.",";
$result .= "48";
}
else if ($type == "Server")
$result .= "single node";
else if ($type == "VM") {
$result .= "single host";
}
echo $result;
?>
As you are already using jQuery in your page, I suggest jQuery's ajax option.
Following should work. Update it accordingly.
getOptions.php
<?php
$type = $_GET['type'];
$result = "";
if ($type == "DCA-V1") {
for ($i=0;$i<47;$i++)
$result .= $i.",";
$result .= "48";
} else if ($type == "Server") {
$result .= "single node";
} else if ($type == "VM") {
$result .= "single host";
}
echo $result;
?>
Demo Page
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#type_select').change(function() {
//Get current item's value
var type = $(this).val();
$.ajax({
url : "getOptions.php?type=" + type,
success : function(data) {
var result, opts = "";
//We get comma separated data
result = data.split(',');
//Prepare options
for(var i = 0; i < result.length; i++) {
opts += "<option value='" + result[i] + "'>" + result[i] + "</option>";
}
//Populate second select
$('#config').html(opts);
},
error : function() {
alert("Error");
}
});
});
//By default populate options for currently selected item
$('#type_select').trigger('change');
});
</script>
</head>
<body>
<form id="add_room" class="form_admin" action="add.php" method="post">
<fieldset>
<legend>Add DCA</legend>
<input type="hidden" name="type" value="room">
<input type="hidden" name="area" value="2">
<div>
<label for="room_name">Name:</label>
<input type="text" id="room_name" name="name" maxlength="50">
</div>
<div>
<label for="room_description">Description:</label>
<input type="text" id="room_description" name="description" maxlength="100">
</div>
<div>
<label for="room_type">Type:</label>
<select class="room_area_select" id="type_select" name="area">
<option value="VM">VM</option>
<option value="Server">Server</option>
<option value="DCA-V1">DCA-V1</option>
<option value="DCA-V2">DCA-V2</option>
</select>
</div>
<div>
<label for = "config">config:</label>
<select id="config" ></select>
</div>
</fieldset>
</form>
</body>
</html>
Tried providing some comments.
Let us know if you need any help.

Categories