I've got two select option. I want to change the second select options value based on the first option value. I'm using thymleaf as template engine.
When the first select is being selected, I make an ajax call to the controller and get the value as a list. I'm getting the value from ajax call but couldn't able to append the value to the second select option. console.log() shows the option value correctly but it didn't update HTML code.
First Select option:
<select id="brand" th:onchange="changeBrand()" class="form-control">
<option th:selected="true" th:disabled="true"
th:text="'Please Select A Brand'"></option>
<option th:each="brand : ${Calculator}"
th:value="${brand}"
th:text="${brand}">Choose Brand</option>
</select>
Second Select:
<div class="input-group">
<select id="model" class="form-control">
<option th:selected="true" th:disabled="true"
th:text="'Please Select A Model'"></option>
</select>
</div>
Ajax:
<script th:inline="javascript">
/*<![CDATA[*/
function changeBrand() {
var selectedBrand = $( "#brand option:selected" ).text();
$.ajax({
url:"duty/getAllModel",
data:{brand:selectedBrand},
type:"POST",
success:function(data){
// Resetting select option
var select = document.getElementById("model");
select.options.length = 0;
options = data.options;
for (var i = 0; i < data.length; i++) {
select.options[select.options.length] = new Option(data[i],i);
}
for (var i = 0; i < select.childElementCount; i++) {
console.log(select.options[i]);
}
},error:function (error) {
console.log(error);
}
});
}
/*]]>*/
Console.log() value:`
Nokia
Samsung`
Related
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.
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>
I'm having a popup that currently shows one dropdownlist with options 1 to 4 and upon selecting an option I'd like using an ajax call to display that many additional dropdownlists (they are all displayed inside a popup window) .
Is such a thing possible?
So far I've created 4 divs for each of the selects and I hid them, is it possible to unhide them using a loop in JQM, after extracting the selected option?
<!--IceCream popup -->
<div data-role="popup" id="puIceCream">
<div ><center>Select Number of Flavors:</center>
<select id="ddlNumFlavorsIC">
<option value="" disabled selected hidden>Please Choose...</option>
<!--Number of flavors is added here-->
</select>
</div>
<div id="1FlavorIC" hidden>
<center>Select 1st Flavor:</center>
<select id="ddlFlavorsIC1">
<option value="" disabled selected hidden>Please Choose...</option>
<!--Flavors are added here-->
</select>
</div>
<div id="2FlavorIC" hidden>
<center>Select 2nd Flavor:</center>
<select id="ddlFlavorsIC2" >
<option value="" disabled selected hidden>Please Choose...</option>
<!--Flavors are added here-->
</select>
</div>...
JS Code:
$("#puIceCream").on("popupafteropen", function (event) {
var NumofFlavorsSelected, Flag=0;
if ($("#ddlNumFlavorsIC option").length < 2) {
WebServiceURL = "IceWS.asmx";
$.support.cors = true;
$.ajax({
url: WebServiceURL + "/GetNumofFlavors",
dataType: "json",
type: "post",
data: "{ }",
contentType: "application/json; charset=utf-8",
error: function (err) {
alert("error: " + JSON.stringify(err));
},
success: function (data) {
var size = data["d"].length;
for (var i = 0 ; i < size; i++) {
$("#ddlNumFlavorsIC").append("<option>" + ((String)(data["d"][i].value)) + "</option>");
}
Flag = 1;
}
});
}
if (Flag) {
NumofFlavorsSelected = $("#ddlNumFlavorsIC option:selected").text();
for (var i = 1 ; i <= NumofFlavorsSelected ; i++) {
$("#"+i+"FlavorIC").show();
}
}
This doesn't seem to work though. Is it because the ajax call is asynchronous?
Any solution to this problem? perhaps a different approach?
Thank you!
Use the change event of the first dropdown to catch when a change is made:
$("#ddlNumFlavorsIC ").on("change", function(e){
NumofFlavorsSelected = parseInt($("#ddlNumFlavorsIC option:selected").text());
for (var i = 1 ; i <= NumofFlavorsSelected ; i++) {
$("#"+i+"FlavorIC").show();
}
});
DEMO
Your code with flag fails becuase it runs before the AJAX call returns
<script>
$(document).ready(function() {
$('#state').change(function(event) {
var $c=$("#state").val();
$.get('getCities',{id:$c},function(responseJson) {
var $select = $("#city");
$select.find('option').remove();
$.each(responseJson, function(key, value) {
$('<option ></option>').val(key).text(value).appendTo($select);
});
});
});
});
</script>
<form action="postingRequirementSaving" th:object="${PostRequirementCommand}">
<label>State:</label>
<select th:field="*{stateid}" id="state">
<option value="0" selected="selected">– Select an option –</option>
<option th:each="var :${state}" th:value="${var.stateid}" th:text="${var.statename}"></option>
</select> <span class="error"></span>
<label>City:</label>
<select th:field="*{city}">
<option value="0">Select City</option>
</select>
</form>
Json response is not supporting multiple select jquery plugin.
please can any one help me to resolve it.
i'm using spring hibernate frame work.
when i'm using static data it works fine, but when it comes dynamic it doesn't working.
If you are using a plugin you have to initialize the select field after your response loaded.
For example if you use this plugin :
<script src="jquery.multiple.select.js"></script>
you will have to initialize your city selector after receiving the jsonResponse. And also in above code you have to add a id to the selector.
<script>
$(document).ready(function() {
$('#state').change(function(event) {
var $c=$("#state").val();
$.get('getCities',{id:$c},function(responseJson) {
var $select = $("#city");
$select.find('option').remove();
$.each(responseJson, function(key, value) {
$('<option ></option>').val(key).text(value).appendTo($select);
});
$select.multipleSelect();
});
});
});
</script>
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);
});