How to get the selected text from form_dropdown? - javascript

I can't get the text in form_dropdown it always return the option value. Please help.
view
<?php echo form_open_multipart('upload/do_upload');?>
<?php
$cont ='';
$dept='';
foreach($level->result() as $row) {
$cont = $row->userlevel;
$dept = $row->department;
}
if(strtoupper($cont)=="USER") {
echo "<strong>".$dept." </strong>";
}
else {
echo form_dropdown('department_name', $dept_name,'','id="department_name"');
}
?>
<br/><br/>
<div class="btn-group">
<span id="status2"><?php echo form_dropdown('document_name', $document_name, '', 'id="document_name"'); ?></span>
</div>
<br/><br/>
<label for="file">Select File To Upload:</label>
<input type="file" name="userfile" multiple class="btn btn-file"/>
</br></br>
<input type="submit" value="Upload File" class="btn btn-primary"/>
<?php echo form_close(); ?>
<script>
window.onload = function() {
var form_data = {
dept_name: "<?php echo $dept; ?>",
ajax: 1
};
$.ajax({
url:"<?php echo site_url("document/document_dept_received"); ?>",
data:form_data,
type:'POST',
success: function(msg){
document.getElementById("status2").innerHTML = msg;
}
});
};
$("#department_name").change(function() {
var form_data = {
dept_name: $("#department_name option:selected").text(),
ajax: 1
};
$.ajax({
url:"<?php echo site_url("document/document_dept_received"); ?>",
data:form_data,
type:'POST',
success: function(msg){
document.getElementById("status2").innerHTML = msg;
}
});
});
</script>
controller
$upload_data = $this->upload->data();
$data['thumbnail_name'] = $upload_data['raw_name']. '_thumb' .$upload_data['file_ext'];
$file_array = array(
'image' => $data['thumbnail_name'],
'image_name' => $upload_data['file_name'],
//'description' => "",
'date_created' => date('Y-m-d H:i:s', now()),
'date_modified' => date('Y-m-d H:i:s', now()),
'author' => $this->session->userdata('username'),
'size' => $upload_data['file_size'],
'type' => $upload_data['image_type'],
'width' => $upload_data['image_width'],
'height' => $upload_data['image_height'],
'document_name' => $this->input->post("document_name"),
'department' => $this->input->post("department_name"),
//'notes' => "",
);
when I try this...
print_r($this->input->post("document_name"));
print_r($this->input->post("department_name"));
it shows 1 and 1...
what I want is the text not the id or value of options.
Example: I selected the IT Department and Folder 1, it will display/record IT Department and Folder 1 to database.

Check this: http://jsfiddle.net/Lev0sjjx/2/
Note: The jquery code is just for demonstration purposes
HTML
<select id="test">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Javascript / jQuery
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
$(function() {
$('#test').change(function() {
var text = getSelectedText('test');
alert(text);
});
});

Exchange array values and keys:
$dept_name = array_flip($dept_name);
form_dropdown('department_name', $dept_name,'','id="department_name"');
Same for $document_name.
This switches from <option value="id">name</option> to <option value="name">id</option>.
If you need <option value="name">name</option>, rebuild the array to get a name 2 name relationship.
$dept_names2 = array();
foreach($dept_name as $item_id => $item_name)
{
$dept_names2[$item_name] = $item_name; // name as key and value
}
form_dropdown('department_name', $dept_names2,'','id="department_name"');
An array with structure "name=>name" will work with your ajax requests, too - because you are using $("#department_name option:selected").text(). so you are already working with the names, not the ids. no adjustment needed.

Related

Ajax approach, PHP Post and JSON array CURL

I tried everything but I can not figure it out.
This is old discussion: PHP Group By value - JSON
In this other thread I was told that the ajax approach is different. I tried to run their advice but when I write the code Javascript in ajaxData.php file seems not to work.
I need to populate reservationTime dropdown with time array (splitted in ajaxData) and dependent by reservationDate (grouped Date Array).
The code below works and fills reservationDate dropdown with date(splitted). Now I would like populate second dropdown.
Dropdown Image
reservationDate Dropdown Image
I have index.php with:
<form id="my-form" method="post" autocomplete="off">
<div class="a-row">
<div id="input-parent">
<select name="company" required="" id="company">
<option value="">Select company</option>
<option value="1">Rome</option>
<option value="2">New York</option>
<option value="3">Madrid</option>
<option value="4">Tokyo</option>
</select>
</div>
<div id="input-parent">
<select name="productCode" required="" id="product">
<option value="">Select product</option>
<option value="IPAD">iPad</option>
<option value="GALAXY">Samsung Galaxy</option>
<option value="LGTV">LG TV</option>
</select>
</div>
<div id="input-parent">
<select name="reservationDate" required="" id="date">
<option>Select date</option>
</select>
</div>
<div id="input-parent">
<select name="reservationTime" required="" id="time">
<option>Select time</option>
</select>
</div>
</div>
<div class="a-row">
<div>
<input type="submit">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // serializzo
})
.done(function(data){
})
.fail(function(){
alert('Error');
});
});
// Company change
$('#company').on('change', function(e) {
e.preventDefault(); // Prevent Default Submission
var productID = $("select#product option:checked" ).val();
var companyID = $(this).val();
if(companyID && productID != ""){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{company:companyID,productCode:productID},
success:function(html){
$('#firstSelect').html(html);
}
});
}else{
console.log("Nothing");
}
});
// Product change
$('#product').on('change', function(e) {
e.preventDefault(); // Prevent Default Submission
var companyID = $("select#company option:checked" ).val();
var productID = $(this).val();
if(companyID && productID != ""){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{company:companyID,productCode:productID},
success:function(html){
$('#firstSelect').html(html);
}
});
}else{
console.log("Nothing");
}
});
});
</script>
And ajaxData.php where I split date and time and insert loop date values into date dropdown of index.php:
<?php
if(isset($_POST["company"]) && isset($_POST["productCode"]))
{
// Token ID
$authToken = 'XXXXXXXXXXXXXXXXX';
// To send API
$companyData = $_POST["company"];
$productData = $_POST["productCode"];
// Setup cURL
$ch = curl_init('https://.../'.$companyData.'/'.$productData.'' );
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Aythorization: '.$authToken,
'Content-Type: application/json'
),
));
// Send Request
$response = curl_exec($ch);
// Response
$responseData = json_decode($response, TRUE);
$responseData = json_decode($response);
// Setup Var
$availableSlots = $responseData->availableSlots;
$slots_start = $responseData->availableSlots->slots;
// Check if errors
if($response === FALSE){
die;
}
$times = array();
foreach($slots_start as $option){
list($date, $time) = explode(" ", $option->start);
if (!array_key_exists($date, $times)){
$times[$date] = array();
}
if (!in_array($time, $times[$date])){
$times[$date][] = $time;
}
}
foreach ($slots_start as $option){
echo '
<option value="' . $option->start. '">' . $option->start . '</option>';
}
}
?>
My JSON data:
{
"response": {
"storeTimeZone": "Europe/Paris",
"slots": [
{
"start": "2017-01-23T08:00:00Z"
},
{
"start": "2017-01-23T08:20:00Z"
},
{
"start": "2017-01-23T08:40:00Z"
},
{
"start": "2017-01-16T08:00:00Z"
},
{
"start": "2017-01-16T08:20:00Z"
},
{
"start": "2017-01-16T08:40:00Z"
}
...

Search in Input text And then search results will be dropdown list using Ajax PHP

There Should be an Input textbox, If user writes any text it should display dropdown list of customer names
<script>
function custlist() {
$.ajax({
url: "custlist.php",
success: function(result) {
$("#customerlist").html(result);
}
});
}
function showCustomers(str) {
$.ajax({
type: "GET",
url: "customerlist.php",
data:'q='+str,
success: function(result) {
$("#customerlist").html(result);
}
});
}
</script>
<input type="text" oninput="showCustomers(this.value)" placeholder="Search here" name="CustomerNo" />
<select name="Cno" id="customerlist" onfocus="custlist()">
<option value="">Customer Name</option>
</select>
custlist.php
<?php
$sql2 = 'SELECT Customer_Name as Cname,No from customers order by Customer_Name';
$result2 = mysqli_query($connection, $sql2);
if (mysqli_num_rows($result2) > 0) { ?>
<option value="">Customer Names</option>
<?php // output data of each row
while($row2 = mysqli_fetch_assoc($result2)) { ?>
<option value="<?php echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?>
</option>
<?php } ?>
<?php } ?>
customerlist.php
<?php
$q = $_REQUEST["q"];
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$sql2 = "SELECT Customer_Name as Cname,No from customers where Customer_Name like '".$q."%s' order by Customer_Name";
$result2 = mysqli_query($connection, $sql2);
if (mysqli_num_rows($result2) > 0) { ?>
<option value="">Customer Names</option>
<?php // output data of each row
while($row2 = mysqli_fetch_assoc($result2)) { ?>
<option value="<?php echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?>
</option>
<?php } ?>
<?php } ?>
<?php } ?>
I am getting the data in my dropdown, but I want that if I write something in text box then automatically it shows dropdown with matching that characters.
And one more issue I have...
2nd Issue:- When I type "abd" first it shows customer names starting with "abd" but automatically it shows next names starting with "ab" then "a" then empty..
Why is that?
Thanks in advance.
Instead of
Javascript:
$.ajax({
type: "GET",
url: "customerlist.php",
data:'q='+str,
success: function(result){
$("#customerlist").html(result);
}
});
And php:
<?php
$q = $_REQUEST["q"];
Try doing this Javascript:
$.ajax({
type: "POST",
url: "customerlist.php",
data: {q: str},
success: function(result){
$("#customerlist").html(result);
}
});
And php:
<?php
$q = $_POST['q'];
Hope this helps!

Dynamically created select list makes mutilple calls to javascript function

I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.
HTML CODE:
<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];
if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->
<?php } ?>
</SELECT>
</td>
Javascipt code:
function get_type()
{
$(".channelname").live("change", function() {
var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
}
remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript
put this
<SELECT name="channel_name[]" required class='channelname'>
and javascript
$(".channelname").change(function() {
var channel_id = $('.channelname').find("option:selected").attr("value");
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});

Choosing an option from select and then show data on another select box using Codeigniter

I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
And, another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my view.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.

Bind on change event to a <select> populated by ajax request

I have in my projects two elements, the first one have a change listener that populates the second one like this.
<select id="user_id" style="width: 100%;">
<option value=""></option>
<?php foreach ($clients as $client) : ?>
<option value="<?php echo $client['Client']['id'] ?>"><?php echo $client['Client']['name'] ?></option>
<?php endforeach; ?>
</select>
<select id="pet_id" style="width: 100%;" disabled>
<option value=""></option>
</select>
--
$('#user_id').change(function() {
var client = {
client_id: $(this).val()
};
$.ajax({
type: "POST",
url: "<?php echo Router::url(array ('controller' => 'grooming', 'action' => 'getClientById')); ?>",
data: client,
success: function(data)
{
var json = JSON.parse(data);
if (json.result === "success") {
$('#pet_id').select2('data', null);
$('#pet_id').empty();
$.each(json.list, function()
{
$('#pet_id').append($("<option/>").val(this.breed_id).text(this.name));
});
if(!$('#pet_id').is(':enabled')){
$('#pet_id').removeAttr('disabled');
}
}
else
{
$('#pet_id').attr('disabled', 'disabled');
$('#pet_id').select2('data', null);
$('#pet_id').empty();
}
}
});
});
Now I have to add another change listener to the second selector (#pet_id) but it is not working any of these alternatives.
$('#pet_id').on('change',function (){
alert('finally worked :)');
});
$('#pet_id').bind('change',function (){
alert('finally worked :)');
});
¿What I'm doing wrong?
Thanks in advance.

Categories

Resources