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

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.

Related

I have a problem while fetching date in "class in C:\xampp\htdocs\ERP\std.php on line 4" from ajax code

I am new in ajax. i have a problem. i'm selecting value from select tag and sending it into ajax code that give me record at realtime but it display nothing in next select tag. if i tried to open second php file. it diplay error like, "Notice: Undefined index: class in C:\xampp\htdocs\ERP\std.php on line 4". i don't know what to do. help me.
Here is my code of ajax
<script>
function myfunction(datavalue) {
$.ajax({
type: 'POST',
url: 'std.php',
data: { class : datavalue},
success: function(response){
$('#stdName').html(response);
}
});
}
</script>
option from where i am getting value
<select name="std-class" onchange="myfunction(this.value)" id="stdClass">
<?php if(isset($_GET['fee_id'])){?>
<option value="<?php echo $row['std_class']; ?>"><?php echo $row['std_class'];?></option>
<?php }else {?>
<option>Select Class</option>
<?php }
$std=mysqli_query($con, "SELECT class_name FROM classes");
while($row1=mysqli_fetch_array($std)){
?>
<option value="<?php echo $row1['class_name'];?>"><?php echo $row1['class_name'];?></option>
<?php }?>
</select>
And this is the php file code
<?php
$con=mysqli_connect("localhost","root","","sms_db");
$class=$_POST['class'];
$result=mysqli_query($con, "SELECT * FROM students WHERE class='$class' ORDER BY id ASC");
while($rows=mysqli_fetch_assoc($result)){ ?>
<option value="<?php echo $rows['username'];?>"><?php echo ucwords($rows['name']);?></option>
<?php }
?>
I also tried this code but it also not working
<script>
function myfun() {
var select = document.getElementById('stdClass').value;
console.log(select);
$.post("std.php", {
class: select
},
function(response) {
$('#stdName').html(response);
});
}
</script>
<script>
function myfunction(datavalue) {
$.ajax({
type: 'POST',
url: 'std.php',
data: { "class" : datavalue},
success: function(response){
$('#stdName').html(response);
}
});
}
</script>

dynamic select option in codeigniter

I am creating dependable select option in codeigniter. To populate first option was easy but i am bit troubling in displaying the second option and third option. Need help on this
My database contain:
In head table:
h_id, head fields,
subhead table
h_id, sh_id, subhead fields and
points table
sh_id, points_name fields
controller
class Mobile extends App_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper(array('url','language','form'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
$this->lang->load('auth');
$this->load->model('mobiles_model');
}
function index()
{
if (!$this->data['logged_in'])
{
redirect('auth/login','refresh');
}
$rows = $this->mobiles_model->get_users_devices();
if ($rows)
{
$this->data['devices_list'] = $rows;
}
$this->_render_page('trackall', $this->data);
}
function _render_page($view, $data=null, $render=false)
{
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $render);
if (!$render) return $view_html;
}
}
modal
public function get_users_devices()
{
$this->db->select('A.h_id as id,A.head');
$this->db->from($this->table_head.' as A');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
return FALSE;
}
view
<select id="head" name="head" class="form-control input-sm" onchange = "calljavascriptfunction();">
<option value="default">--Select--</option>
<?php if(isset($devices_list))
foreach ($devices_list as $value) { ?>
<option value="<?php echo $value['h_id'] ?>"><?php echo $value['head'] ?></option>
<?php } ?>
</select>
<select id="subhead" name="subhead" class="form-control input-sm">
<option value="default">--Select--</option>
</select>
<select id="points" name="points" class="form-control input-sm">
<option value="default">--Select--</option>
</select>
I have to populate the other depending on what i select. i tried several methods but none of them worked.
Thanks for help i am really stuck in this.
Suppose your you had following views loaded in HTML and you need to fetch value depending on first dropdown #head.
view code :
<select id="head">
<option id="1"> Mobile </option>
<option id="2"> Tabs </option>
<option id="3"> Laptops </option>
</select>
<select id="subhead">
</select>
jquery ajax
$("#head").change(function(){
var post_url = '<?php echo base_url() ?>mobile/getByDeviceId'
$.ajax({
type: "POST",
url: post_url,
data : { "hid" : $(this).val() },
success: function(response){
$.each(response, function(value, key) {
$("#subhead").append("<option id="+value.modelId+">"+value.modelName+"</option>");
})
}
});
});
controller function :
function getByDeviceId(){
$hid = $this->input->post("hid");
$modelList = $this->mobile_model->getByDeviceId($hid);
echo(json_encode($modelList));
}
model function :
function getByDeviceId($hid){
$this->db->select("modelId, modelName");
$this->db->from("models");
$this->db->where("hid", $hid);
$query = $this->db->get();
return $query->result();
}
Use jquery ajax() to do this, as ajax() do not disturb the current state of page and get the data from server and you can append it to the dropdown.
ajax() syntax:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
var1 :val1,
var2 :val2
},
success: function(response){ // response from process
// do your stuff here
}
});

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.

Changing value of selectbox on change event of another select box from database in codeigniter

I have a view file as
<select name="tournaments" id ="tournaments" class="form-control">
<?php foreach ($tournaments as $tournament): ?>
<option value="<?php echo $tournament->TournamentID ?>"><?php echo $tournament->TournamentName ?></option>
<?php endforeach ?>
</select>
A script
<script type="text/javascript">
$(document).ready(function(){
var initial_target_html = '<option value="">Please select a Tournament...</option>'; //Initial prompt for target select
$('#matches').html(initial_target_html);
$("#tournaments").change(function(e){
e.preventDefault();
var data = ($("#tournaments").val());
$('#matches').html('<option value="">Loading...</option>');
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('admin/dashboard/update_match_box') ?>",
data: {tournament:data},
success: function(data) {
}
});
});
});
</script>
Controller function is
public function update_match_box()
{
$sql = "Some query"
$query = $this->db->query($sql);
$json= $query->result();
$this->output->set_content_type('application/json')
->set_output(json_encode($json));
}
Controller file is going to return multiple rows, which I need to capture in success event of ajax and update second select box accordingly, how am I suppose to do that?
You should take a look at form_helper file, there is a lot of useful functions in it for building form inputs, all you have to do is load this helper :
In application/config/autoload.php go to "helper" and add the helper name as follow :
$autoload['helper'] = array('form');
Next, go to your view file and change this :
<select name="tournaments" id ="tournaments" class="form-control">
<?php foreach ($tournaments as $tournament): ?>
<option value="<?php echo $tournament->TournamentID ?>"><?php echo $tournament->TournamentName ?></option>
<?php endforeach ?>
</select>
to this :
<?php
// $tournaments must me an array, use ->result_array() instead of ->result_object()
$tournaments = array_column($tournaments, 'TournamentName', 'TournamentID');
echo form_dropdown('tournaments', $tournaments, '', 'id="tournaments" class="form-control")
?>
For your success callback function, you can use $.each or just for loop to extract each element and create options for the select input:
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('admin/dashboard/update_match_box') ?>",
data: {tournament:data},
success: function(data) {
$('select#secondSelect').html('');
$.each(data, function(item) {
$("<option />").val(item.id)
.text(item.name)
.appendTo($('select#secondSelect'));
});
}
});

How to get the selected text from form_dropdown?

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.

Categories

Resources