Using DIV like dependent dropdown lists [PHP + JS] - javascript

I have a DIV element as drop-down in PHP as below:
<div id="files" value="fileselect" selected="selected">Choose Folder1
<input type="hidden" name="test" id="hiddenfield" />
</div>
<div id="files2" value="fileselect2" selected="selected">Choose Folder2
<input type="hidden" name="test2" id="hiddenfield2" />
</div>
Now I try to get the value of selected option as follows:
<?php $content = ?>
<script type = text/javscript>
document.getElementById("files").value;
</script>
<?php echo $content; ?>
but I get unknown variable $content error.
And, I tried to create 'change' event handling in DIV element as follows:
$(document).ready(function()
{
//Bind a change event to the folder selector
$("#files").change(function()
{
var dir = $(this).val();
// Get file names in directory dir and pass it to the next drop-down DIV
$.get("listfiles.php", {"dir":dir}, function(response){
//Show the files
$("#files2").html(response);
//alert($('#files2 option:selected').val());
alert(response);
$(response).appendTo('#hiddenfield2');
});
});
});
But this doesn't help passing the 'response' to the second DIV "files2".
I need to use the two DIVs like dependent drop-down lists. I make the dropdown-list "selection1" interact with DIV "selection2" like dependent dropdowns as follows:
<select name="field1" id="selection1">
<option selected="selected" name ="selection1">Folder 1</option>
<?php
$selections = array('Folder A', 'Folder B', 'Folder C');
foreach($selection as $selections){
?>
<option value="<?php echo strtolower($selection); ?>"><?php echo
$selection; ?></option>
<?php
}
?>
</select>
$("#selection1").change(function()
{
var dir = $(this).val();
$.get("listdirs1.php", {"dir":dir}, function(response){
//Show the files
$("#files").html(response);
// alert($('#selection2 option:selected').val());
//alert(response);
$(response).appendTo('#selection2');
});
});
But this doesn't work in case both "selection1" and "selection2" are DIVs.
I already referred to how to submit a div value in a form stackoverflow answer
I am all new to PHP and JavaScript. Please help. Thanks in advance.

Related

How i get the values in select option using javascript

I am fetching acno from table when i select a party name in option.I have so far tired i get the acno from the table but it is not place in the option box.
My controller code:
public function get_states2()
{
$name = $this->input->post('name');
$result = $this->db->query("SELECT TAcNo FROM tipup_payment LEFT OUTER JOIN parmaster on parmaster.pcode = tipup_payment.TName WHERE PName='$name' ")->result_array();
echo json_encode($result);
}
My View page code:
<div class="col-md-6">
<div class="form-group form-group-xs">
<div class="col-lg-9">
Party Name:
<select class="form-control countries" name="City">
<option></option>
<?php foreach ($PName as $row ): ?>
<option value="<?php echo trim($row['PName']); ?>"><?php echo trim($row['PName']); ?></option><?php endforeach ?>
</select>
</div>
</div>
<div class="form-group form-group-xs">
<div class="col-lg-9">
AcNo:
<select multiple="multiple" style="height: 85px;" id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?>
</div>
</div>
<div id="item">
<input type="checkbox" name="item">With Details</center></div>
</div>
</div>
My Script Code:
<script type="text/javascript">
$(document).ready(function(){
$('.countries').change(function(){
var name = $('.countries').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>Tieup/get_states2",
data:{name:name},
datatype: 'json',
success: function (data) {
/*get response as json */
alert(data);
var result = jQuery.parseJSON(data);
var no = result.TAcNo;
$("#Name").val(no);
/*ends */
}
});
});
});
</script>
This is my view page when i select a party name it should display the acno in acno option box( it down the party name).
give a class or id to ur dropdown
ur html
<select class="product">
</select>
ur jquery code
loop through all ur value and set it in ur option value one by one and at the end inject all ur html to ur select option using .html()
var value = [{"TAcNo":"341"}]
var options = '<option value="">Select</option>';
$(value).each((index, item) => { //loop through your elements
console.log(item)
options += '<option value="'+item.TAcNo+'">'+item.TAcNo+'</option>';
});
$('.product').html(options);
Hope it helps
Solution
you need to trigger change like this to update select value
$("#Name").val(no).change();

JQuery/Javascript -- show div based on select but NOT value

I am using PHP to dynamically populate a select box (a list of equipment). The value is set with the ID of the item selected so I can use it later in my programming.
What I need help with...
Based on the item selected I need to show/hide one of two form fields but I can't use the value as this is the id.
What I need to be able to do is read the text in the select box which will contain the item name with either (Service: Set by dates) or (Service: Set by hours) and show either the form field for the date or the form field for the hours?
Is this possible? I can find loads great resources based on the value but not on the text in the select.
I think something like this should work but not sure how to use the text in the select rather than the value.
$(function() {
$('#system').change(function(){
$('.system').hide();
$('#' + $(this).val()).show();
});
});
Any help would be greatly appreciated!!!!
Regards
Matt
(N.B this is what I'm working with at the mo based on the answers so far, thank you all so much for the help (and for your example Louys Patrice Bessette) - not quite there yet... I was getting an error and managed to track it back to the script not getting the result from the select box. See below now working code! Thanks all!!!
<div class="col">
<div class="form-group">
<label for="system_select">Equipment or System to be serviced</label>
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name; ?></option> <?php
}
?>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$("#due_dates").hide(); // Hide both divs
$("#due_hours").hide(); // Hide both divs
$('#system_select').change(function(){
var dataType = $(this).find(':selected').attr('data-type') // should be "Set by dates" or "Set by hours"
if (dataType == 'Set by dates') {
$("#due_hours").hide();
$("#due_dates").show();
} else if (dataType == 'Set by hours') {
$("#due_dates").hide();
$("#due_hours").show();
}
});
});
</script>
<div class="row">
<div class="col-md-3" id="due_date">
<div class="form-group">
<label for="service_date">Next Service (Set by dates)</label>
<input type="date" class="form-control" name="service_date" id="service_date" value="<?php echo escape(Input::get('service_date')); ?>" autocomplete="off">
</div>
</div>
<div class="col-md-3" id="due_hour">
<div class="form-group">
<label for="service_hours">Next Service (Set by hours)</label>
<input type="number" class="form-control" name="service_hours" id="service_hours" value="<?php echo escape(Input::get('service_hours')); ?>" autocomplete="off">
</div>
</div>
</div>
I think that you PHP $system->service_type; is echoing either "Set by dates" or "Set by hours".
If you echo that in a data attribute like this:
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type; ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name . ' (Service: '. $system->service_type .')'; ?></option> <?php
}
?>
</select>
Then, in jQuery, you could use it like this to decide to show <div id="due_hours" class="col-md-3"> or <div id="due_hours" class="col-md-3">.
$(function() {
$('#system').change(function(){
$('.system').hide(); // I don't know what this is for...
$("div[id=^'due']").hide(); // Hide both divs
var dataType = $(this).data("type"); // should be "Set by dates" or "Set by hours"
var type = dataType.split(" by ")[1]; // should be "dates" ot "hours"
$("#due_"+type).show();
});
});
Now be carefull with the s on dates...
Try this out... Console.log the values to make sure you have the correct one to match the id to show.
;)
If $(".classname").text() is not working you could try to add that info that you need in a "data" attribute.
Something like this ->
<option data-service="service name" class="myClass">15</option>
Using data attributes can give you a lot of freedom on what you can add. You could add lots of information that a normal user cant read (without inspecting element).
Then you would simply do something like this ->
$(".myClass").on("click", function() {
var serviceData = $(this).attr("data-service");
})
You can then do if checks, compare and whatever you need.
EDIT: Or you can use your approach with on.change and get the selected data attr, it would probably be better
If you change your select into something like this:
<select class="form-control" name="system_select" id="system_select">
<option data-hide='#due_date' data-show='#due_hours'>Show Hours</option>
<option data-hide='#due_hours' data-show='#due_date' value="B">Show Dates</option>
</select>
And your jquery like this:
$('#system_select').change(function () {
$($(this).children("option:selected").attr("data-hide")).hide();
$($(this).children("option:selected").attr("data-show")).show();
});
It could work.

Add second SELECT on change of first SELECT (PHP/AJAX) Not working as it should

firstly, let me express that I have tried four methods (All slightly different) that all seem to produce the same issue, which is no data being outputted, even simple echo 'test' to rule out a DB issue (and also trying TEST in html on the called page, no result.
Here is a snapshot of the HTML and Javascript:
(document).on('change','category_id',function(){
var id = $(this).val();
$.ajax({
method: 'POST',
url: 'supportgetsubcats.php',
data: {'subcatid' : id},
success: function(data){
$('#subcatresponse').hide().html(data).fadeIn(); // update the DIV
}
});
});
<div class="form-group">
<label class="col-sm-2 control-label">Category *</label>
<div class="col-sm-4">
<select class="form-control" class="category_id" name="category_id" id="category_id">
<option value="" selected="selected">-- Select --</option>
<?php
$query="select * from support_categories where hide = '0' or hide is NULL order by name ASC";
$rs=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($rs))
{
extract($row);
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php
}
?>
</select>
</div>
</div><!-- form-group -->
<div class="form-group">
<div id="subcatresponse" name="subcatresponse" class="col-sm-4">
</div>
</div><!-- form-group -->
Here is the PHP that is called:
<?php require_once("includes/header.php");
error_reporting(E_ALL);
echo 'TEST';
if(isset($_POST["subcatid"])){
// Capture selected country
$category = $_POST["subcatid"];
$query="select * from support_subcategories where parent_category = '" . $category . "' order by name ASC";
$rsp=sqlsrv_query($conn,$query);
$subCatArr = array();
while($row=sqlsrv_fetch_array($rsp))
{
$subcat = $row['name'];
array_push($subCatArr, $category, $subcat);
}
// Display city dropdown based on country name
if($category == '-- Select --'){
} else {
echo '<label class="col-sm-2 control-label">Sub Category</label>';
echo '<select class="form-control" name="subcategory_id" id="subcategory_id">';
foreach($subCatArr[$category] as $value){
echo '<option value="'. $value .'">'. $value .'</option>';
}
echo "</select>";
}
}
?>
I get no response, not even basic text back, so I am not entirely sure what is wrong with the AJAX call, jQuery is included and proven to be working as the menu system on this interface won't display without jQuery so I am confident that is not the issue.
It looks like for whatever reason, the data from the HTML Select is not being passed to the AJAX call for POST.
Any thoughts greatly appreciated, TIA.
Try changing
(document).on('change', 'category_id', function() {
to
$(document).on('change', '#category_id', function() {
The second parameter to the on call takes a selector, but you seem to be passing in the name of the element instead. The name of the element is used when trying to access the element in PHP, and you use the selector (id, class, element) in JavaScript.
Alternatively, you could also use
$('#category_id').on('change', function()
You haven't posted it in your question, but in case you don't have it, it is always a good idea to only execute your jQuery code after the page has finished loading, otherwise your code may be trying to access an element that hasn't been loaded yet.
Surround your jQuery code with
$(document).ready(function() {
// Run jQuery code
}
add type='POST' to your ajax call
Also change this
(document).on('change','category_id',function(){
to
$(document).on('change','category_id',function(){

Populate directory hirerachy on server to multiple html Dropdown list using jquery or Ajax

I am a beginner in using jQuery and Ajax.
I have the following hierarchy of directories on a server.
I would like to get the file hierarchy dynamically into dropdown like this
OnClick of "Search" Button, a download URL (as shown below) with the selected drop down values should appear
"http://abc.def.com/ProductName1/Series1.1/FileName1.1.zip"
I understand the best way to accomplish this is using jQuery and Ajax.
How do I make the directory hierarchy of "Product Name" on server to appear dynamically ? And the the respective "Product Series" and "File" change whenever new Product Name is selected?
Here is just a real basic layout. This particular solution calls itself but you can split it into two pages. To make multiple calls to build your dropdowns, you probably could use a function since the logic will likely repeat itself as you drill down the folders:
index.php
<?php
error_reporting(E_ALL);
if(isset($_POST['scan']) && !empty($_POST['scan'])) {
// For your convenience, you can see what returns
print_r($_POST);
$filter[] = '.';
$filter[] = '..';
// Decode directory string from form
$dir = base64_decode(urldecode($_POST['dir']));
// Add root (you may have defined a root, but I am
// using the server document root key/value
$current = str_replace("//","/",$_SERVER['DOCUMENT_ROOT'].$dir);
// Check that the directory exists
if(is_dir($current)) {
// Scan this directory
$files = scandir($current);
// If there are folders/files
if(!empty($files)) { ?>
<label>Series</label>
<select name="series">
<?php
foreach($files as $infolder) {
// If just return directories
if(is_dir($current.$infolder) && !in_array($infolder,$filter)) { ?>
<option name="<?php echo urlencode(base64_encode($infolder)); ?>"><?php echo substr($infolder,0,20); ?></option>
<?php
}
} ?>
</select>
<?php
}
}
// Exit so you don't continue to print the bottom stuff
// Which is what you would load in the first place
exit;
}
// These are just fake, obviously. You can populate the
// first dropdown however you want
$dir = "/root/";
$dir2 = "/root/folder1/";
?>
<form id="get_files" method="post">
<input type="hidden" name="scan" value="true" />
<select name="dir">
<!-- This encoding just makes it easier to transport this data -->
<!-- base64 is probably itself sufficient -->
<option value="<?php echo urlencode(base64_encode($dir)); ?>"><?php echo substr($dir,0,10); ?></option>
<option value="<?php echo urlencode(base64_encode($dir2)); ?>"><?php echo substr($dir2,0,10); ?></option>
</select>
<div id="form_load"></div>
<input type="submit" value="submit" />
</form>
<!-- jQUERY LIBRARIES -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<!-- jQUERY AJAX -->
<script>
$("#get_files").submit(function() {
$.ajax({
url: 'index.php',
data: $(this).serialize(),
type: 'POST',
success: function(response) {
$("#form_load").html(response);
}
});
return false;
});
</script>

How can I change the ids of my cloned dropdown list with jquery

I have the following Drop Down List in php:
<select id="choice" name="choice" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select><input TYPE = "button" id="addbt" Name = "addbt" VALUE = "Add Pizza">
and I am using the following Jquery:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().insertAfter("#choice");
});
</script>
I am trying to clone the Drop Down List which is attached to an xml file (I managed till here) and add the Jquery necessary so each new drop down list clone has a new id (a single number difference would be enough. Something like choices_00 then choices_01 and so on).
Since I am totally new to Jquery and php I am asking for any advice or help.
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'newid')
.attr('name', 'newname')
.insertAfter("#choice");
});
To ensure you get a new name and id each time, consider adding a class name to the select so you can count how many exist.
HTML:
<select id="choice" name="choice" class="ddl" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select>
JS:
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'choice' + $('.ddl').length)
.attr('name', 'choice' + $('.ddl').length)
.insertAfter(".ddl:last");
});
Otherwise, track how many times the button has been clicked with a global variable (ugh) or data attribute.
I think you are after this: http://jsfiddle.net/ehQan/
$("#addbt").click(function () {
$('#choice').clone().attr( 'id', 'choices_' +$(this).index()).insertAfter("#choice");
});
You can change the id using the jQuery attr() method before you insert it:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().attr('id','Your new id').insertAfter("#choice");
});
</script>
With this code you can push the button as many times as you want:
<script type="text/javascript">
var times = 0;
$("#addbt").click(function () {
times++;
$('#choice').clone().attr( 'id', 'choices_' + times ).insertAfter("#choice");
});
</script>

Categories