add an event listener to multiple elements that are not yet available on the dom - events

I have multiple selects in a table and I want to be able to change the options of al the selects on a column when I change the option of the select on the first row. The problem is that the selects are added dynamically. I managed to do this by targeting the first select of each column by it's ID, but I'm looking for a way to do this for all elements at once.
This is the code I have for each column:
$('id-of-the-table-that-already-exists-on-page').on('change','id-of-the-first-select-on-each-column', function() {
var _value = $(this).val();
var selectId = $(this).attr("id").slice(0, -1);
$('*[id^="' + selectId + '"]').val(_value);
});
Is there a way to add a each function to target all first row selects, instead of targeting each select by it's id?

jQuery's .on() will take a looser selector string as a parameter there. You could target all select elements in the first tr…
$( 'id-of-the-table-that-already-exists-on-page' ).on( 'change', 'tr:first-child select', function () {
// do stuff
} );
var $table = $('#foo');
function add_selects() {
$table.find('tr:first-child').html(`<select name="bar" id="bar">
<option value="1">Dynamic Option 1</option>
<option value="2">Dynamic Option 2</option>
</select>`);
}
// set listener
$table.on('change', 'tr:first-child select', function(event) {
console.log('Change! Value is: ' + $(event.target).val());
});
// modify DOM
add_selects();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="foo">
<tr>
<td>[select goes here]</td>
</tr>
<tr>
<td>
<select name="baz" id="baz">
<option value="a">Option A</option>
<option value="b">Option B</option>
</select>
</td>
</tr>
</table>
You might have to modify that to accommodate for any thead,tbody, or tfoot elements.

Related

How to get auto response value by using Two Drop-Down List in PHP & Ajax?

How to get the final value in AJAX using two drop-down value,
Koluextension.php
<html>
<head>
<title> Upgrade Cost</title>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select onchange="getvalue()" id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select onchange="getvalue()" id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
</html>
upgratedcost.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));
}
else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
calculatecost.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){
echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));
}
else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
Expected Output:
If customer choose: I have -> one and I want -> two the cost should
be $10 as an Auto response to show to the customer. [Every combination has its own cost]
I have done some changes to your code. And add some Ajax to this and also created separate PHP code, you can get basic idea using this code example.
Html page -
<html>
<head>
<title> Upgrade Cost</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
<button id="btn_check_value">Check for value</button>
<script>
$(document).ready(function(){
$('#btn_check_value').on('click',function(){
var old_val = $("#old option:selected").val();
var new_val = $("#new option:selected").val();
$.ajax({
method: "POST",
url: "value_calculate.php",
data: { old: old_val, new: new_val }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
})
})
</script>
</html>
PHP page code -
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
if($old=='one'&&$new=='two'){echo json_encode(array('sucess'=>'sucess','msg'=>'10$'));}else{echo json_encode(array('sucess'=>'sucess','msg'=>'0'));}
} ?>
Here what happen is, once user do the selections user have to click the "Check for value" button and once user click on that button it'll make Ajax request to PHP page "value_calculate.php" and php code return value according to user selection.
This is not complete solution but you can get basic idea and improve this code according to you.
Thanks,
Tharanga.
You can try this solution:
1) Modify Your HTML like this:
<html>
<head>
<title> Upgrade Cost</title>
</head>
<form method='POST' action='upgradecost.php'>
Name : <input type="text" name="name"/><br/><br/>
Email Id : <input type="text" name="email_id"/><br/><br/>
Contact Number : <input type="text" name="contact_number"/><br/><br/>
I have :
<select onchange="getvalue()" id="old">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select><br/><br/>
I want :
<select onchange="getvalue()" id="new">
<option value = "select_option">Select Option</option>
<option value = "one">One</option>
<option value = "two">Two</option>
<option value = "three">Three</option>
<option value = "four">Four</option>
<option value = "five">Five</option>
</select>
</form>
</html>
2) Add this JavaScript function to your page:
function getValue() {
var cost1=$('#old').val();
var cost2=$('#new').val();
$.ajax({
url: '{{ url("calculateCost.php") }}',
type: 'get',
//async:true,
data: {
oldId: cost1,
NewId: cost2,
},
dataType: 'json',
success: function(json) {
//you can calculate total cost on server and show updated cost using
//jquery anywhere on your form
//do whatever you wanted to do
//you can easily manipulate DOM using jQuery
},
error : function(xhr, textStatus, errorThrown ) {
//in case ajax call error
}
});
}
}
}
Haven't tested this code. Please make necessary changes. If you still don't know what is going on then I would recommend you to go through a detailed tutorial in order to understand the concepts first and then code. e.g. https://www.w3schools.com/php/php_ajax_intro.asp
Issues (based from your post in daniweb website):
There is no input field with an id of est_shi_val
Looking at your code, you want to use both the old and new select fields, when changed will put the result to a hidden input field. But the result will only return if both the old and new have selected options. Is this what you want? Or at least one of them should be selected, and the result will return?
Use a database to look-up for conditions instead of manually creating if-else conditions
Instructions:
You may remove first your onchange attribute/call in your old and new select fields.
AJAX Call:
$("#old, #new").change(function(){ /* WHEN YOU CHANGE THE VALUE OF THE OLD OR NEW INPUT FIELD */
var old = $("#old").val(),
newval = $("#new").val();
$.ajax({ /* TRIGGER THE AJAX CALL */
type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
url: "ajax_ship_data.php", /* PAGE WHERE WE WILL PASS THE DATA */
data: {'old':old, 'new':newval}, /* THE DATA WE WILL BE PASSING */
dataType: 'json',
success: function(result){ /* GET THE RETURNED DATA */
$("#results").html(result.message); /* THE RETURNED MESSAGE WILL BE SHOWN IN THIS DIV, PROVIDED THAT YOU HAVE A DIV WITH AN ID OF "results" */
$('#shipping_weight').val(result.weight); /* ASSUMING THAT YOU HAVE A HIDDEN INPUT FIELD WITH AN ID OF "shipping_weight" */
}
});
});
Then at your ajax_ship_data.php:
$shipping_weight = 0;
$message = 'Please select an option from both fields.';
if(isset($_POST['old']) && isset($_POST['new'])){
$old = $_POST['old'];
$new = $_POST['new'];
//part 1
if($old == 'three_compact' && $new == 'five_compact'){
$shipping_weight = 10;
$message = 'Shipping weight is 10.';
}
/** REST OF IF-ELSE CONDITIONS **/
}
echo json_encode(array('message' => $message, 'weight' => $shipping_weight));
Other Option: No AJAX
You may also do this without using AJAX since you're manually creating conditions:
$("#old, #new").change(function(){
var old = $("#old").val(),
newval = $("#new").val();
if(old=='three_compact' && newval=='five_compact'){
$("#results").text('10');
}
/* REST OF IF-ELSE CONDITIONS */
});
Take a look at this fiddle.

Laravel Ajax dropdown example

can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>

how to show content as default in ajax

I have ajax code that when I choose AREA (first select box) I get all the cities in this area.
The issue is when I first enter the page - I want that the second select box (the cities select box) to be fill with the area default (the first choice)
This is what I already have:
Client side:
<script>
$(document).ready(function(){
$('#areaID').change(function(){
var areaID=$('#areaID').val();
$('#cityID').load('scripts/ajax/getCities.php?areaID=' + areaID);
return false;
});
});
</script>
<form method="post" action="page.php">
<select id="first" name="areaID">
<option value="1">center</option>
<option value="2">north</option>
<option value="3">south</option>
</select>
<select id="cityID" name="cityID"> </select>
</form>
$(function () {
function updateCitySelectBox() {
var areaID = $('#areaID').val();
$('#cityID').load('scripts/ajax/getCities.php?areaID=' + areaID);
return false;
}
updateCitySelectBox();
$('#areaID').change(updateCitySelectBox);
});

codeigniter - display database query result on same form using input data

I have trawled the net for sometime now trying to find a solution which cold assist me, but have had no luck.
I have a simple sales form in which the user selects a product from a drop down list. on selecting a value, I want the input box value to get passed to a database query, and the query result (price) be displayed on the form. if possible I want the result to populate an input box so the salesman can adjust as needed.
I am using codeigniter which makes finding a good example quite difficult.
Controller
function new_blank_order_lines()
{
$this->load->view('sales/new_blank_order_lines');
}
Model
function get_sku_price($q){
$this->db->select('ProductPrice');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductPrice'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
View
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr>
<td><select name="product">
<option="sku1">product 1</option>
<option="sku2">product 2</option>
<option="sku3">product 3</option>
<select></td>
<td><input type="text" id="price" name="price" /></td>
</tr>
</table>
I have loaded the jquery library, 1.9.1.
I have got autocomplete working but the sytax is just not the same.
So what I am wanting, is that when I select a product code from the product drop down list, the value is passed to the model, the query result(price) is then displayed in the input box price.
Can anyone provide some insight on how to do this, or a good working example?
Thanks a million, this community is awesome!
Fabio
Controller:
function new_blank_order_lines()
{
$this->load->view('sales/new_order');
}
The view:
<script>
$("#product").change(function () {
//get the value of the select when it changes
var value = $("#product").val()
//make an ajax request posting it to your controller
$.post('<?=base_url("sales/get_sku_prices")?>', {data:value},function(result) {
//change the input price with the returned value
$('#price').value(result);
});
});
</script>
<table>
<tr><td>Product</td><td>Price</td></tr>
<tr>
<td><select name="product" id="product">
<option value="sku1">product 1</option>
<option value="sku2">product 2</option>
<option value="sku3">product 3</option>
</select></td>
<td><input type="text" id="price" name="price" /></td>
</tr>
</table>
Controller to fetch database data:
function get_sku_prices(){
//check if is an ajax request
if($this->input->is_ajax_request()){
//checks if the variable data exists on the posted data
if($this->input->post('data')){
$this->load->model('Sales_model');
//query in your model you should verify if the data passed is legit before querying
$price = $this->your_model->get_sku_price($this->input->post('data', TRUE));
echo $price;
}
}
}
Model:
function get_sku_price($q){
$this->db->select('ProductPrice');
$this->db->where('ProductCode', $q);
$query = $this->db->get('ProductList');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlentities(stripslashes($row['ProductPrice'])); //build an array
}
$this->output->set_content_type('application/json')->set_output(json_encode($row_set));
}
}
Your View:
<table>
<tr>
<td>Product</td>
<td>Price</td>
</tr>
<tr>
<td>
<select name="product" id="product">
<option value="sku1">product 1</option>
<option value="sku2">product 2</option>
<option value="sku3">product 3</option>
</select>
</td>
<td>
<input type="text" id="price" name="price" />
</td>
</tr>
</table>
The javascript
<script>
$("#product").change(function () {
//get the value of the select when it changes
var value = $("#product").val()
//make an ajax request posting it to your controller
$.post('<?=site_url("controller/function")?>', {data:value},function(result) {
//change the input price with the returned value
$('#price').value(result);
});
});
</script>
The controller:
public function your_funtion(){
//check if is an ajax request
if($this->input->is_ajax_request()){
//checks if the variable data exists on the posted data
if($this->input->post('data')){
$this->load_model('your_model')
//query in your model you should verify if the data passed is legit before querying
$price = $this->your_model->get_price($this->input->post('data', TRUE));
echo $price;
}
}
}
use jquery's ajax,post or get and change event..using post here
example..
$('select[name="product"]').change(function(){
var val=$(this).val();
$.post('path/to/controller',{data:val},function(result){
$('#price').val(result.price);
}, "json");
});
conroller funciton
$product=$this->input->post('data'); //this will give you the selected value of select
//make query to db in model..get price and
$price = ..//price that you got from db
echo json_encode(array('price'=> $price));

AngularJS + post the entire $scope for Controller in ASP.NET MVC

guys.
I'm trying to call some AJAX Post trhu AngularJS, and I want to send all properties from my $scope variable. I have this form:
<div ng-controller="DiscountPrintsCtrl">
<div>
Choose the year:
<select ng-model="selectedYear" ng-change="searchCourses()">
<option ng-repeat="year in years" value="{{year.ID}}">{{year.Name}}</option>
</select>
</div>
<div>
Choose the course:
<select ng-model="selectedCourse" ng-change="searchStudents()">
<option ng-repeat="course in courses" value="{{course.ID}}">{{course.Nome}}</option>
</select>
</div>
<div>
Choose the student:
<select ng-model="selectedStudent" ng-change="searchStudentDetails()">
<option ng-repeat="student in students" value="{{student.ID}}">{{student.Name}}</option>
</select>
</div>
<div ng-model="studentDetails">
Details about the student:<br /><br />
<label>Name: {{studentDetails.Name}}</label><br />
<label>Number: {{studentDetails.Number}}</label><br />
<label>Print quote: {{studentDetails.PrintQuote}}</label><br />
</div>
<div>
<table>
<thead><tr>
<td></td>
<td>Title</td>
<td>Grade</td>
<td>Summary</td>
<td>Author</td>
<td>Number of pages</td>
</tr></thead>
<tbody>
<tr ng-repeat="publication in publications">
<td><input type="checkbox" ng-model="publication.Selected" /></td>
<td>{{publication.Title}}</td>
<td>{{publication.Grade}}</td>
<td>{{publication.Comments}}</td>
<td>{{publication.Author}}</td>
<td>{{publication.NumberOfPages}}</td>
</tr>
</tbody>
</table>
</div>
<button ng-click="submitForm()" value="Confirm discounts" />
And I have this JS:
<script type="text/javascript">
function DiscountPrintsCtrl($scope, $http) {
$http.get(url).success(function (years) {
$scope.years = years;
$scope.selectedYear = '';
});
$scope.searchCourses = function() {
var url = '/json/GetCoursesFromYear?' +
'selectedYear=' + $scope.selectedYear;
$http.get(url).success(function (courses) {
$scope.course = courses;
$scope.selectedCourse= '';
});
}
$scope.searchAlunosAnoSemestre = function() {
var url = '/json/GetStudentsFromCouse?' +
'selectedCourse=' + $scope.selectedCourse;
$http.get(url).success(function(students) {
$scope.students = students;
$scope.selectedStudent = '';
});
}
$scope.searchStudentDetails = function() {
var url = '';
url = '/json/GetStudentDetails?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(studentDetails) {
$scope.studentDetails= studentDetails;
});
url = '/json/GetPublicationsForStudent?' +
'selectedStudent=' + $scope.selectedStudent;
$http.get(url).success(function(publications) {
$scope.publications = publications;
});
}
$scope.submitForm = function () {
// How to submit the entire $scope???
}
}
Any idea? Any considerations about my JS code??
Thanks all!!!
You have typos to fix, friend:
In the .js:
$scope.course = courses;
Should be $scope.courses!
In the html:
{{course.Nome}}
Shouldn't it be:
{{course.Name}}
?
I see some Spanish (?) above there but everywhere else you say .Name so it's best to be consistent, right?
That said, it seems fine to load an object into your $scope from the external json data store as you seem do be doing in each function, loading from the json URLs. The commenters on your post didn't seem to recognize this? I think they believe you're trying to permanently store this data in $scope? Maybe I'm not seeing something that they are... but if you don't add your data model object sometime into $scope.something then {{something}} simply won't work, and neither will {{something.else}}.
Am I way off base here?

Resources