Setting the selected item in a selectlist after ajax callback - asp.net-mvc-3

I am updating a selectlist element using a jquery ajax callback in a mvc application when another selectlist is changed.
The ajax callback calls an action that returns a partialview.
The partialview is then set as the content of a div.
The problem is that when the partialview is returned it has the wrong item set as selected so i need a way to set the selected item following the callback.
$(document).ready(function () {
$("#DependentDropDownValue").change(function () {
var selected = $("#DropDownValue").val();
var data = {data: $("#DependentDropDownValue").val()};
$.ajax({
url: "#Url.Action("IndexPartial","DropDown")",
data: data,
success: function (x) {
$("#partialDiv").html(x);
$("#DropDownSelectList").val(selected);
}
});
});
});
x has the content:
"<select id="DropDownValue" name="DropDownValue">
<option value="1">Emne11</option>
<option value="2">Emne12</option>
<option value="3">Emne13</option>
<option value="4">Emne14</option>
<option value="5">Emne15</option>
<option selected="selected" value="0">-------</option>
<option value="6">Emne21</option>
<option value="7">Emne22</option>
<option value="8">Emne23</option>
<option value="9">Emne24</option>
<option value="10">Emne25</option>
</select>"
The variable "selected" contains the value of the selected option before the callback.. that item has to be set as selected again.
I have tried using
$("#DropDownSelectList").val(selected);
but that doesnt seem to work

The id of the select list that you have shown is DropDownValue and not DropDownSelectList, so make sure that you are using the correct id in your script:
$('#DropDownValue').val(selected);

Related

pass certain value dynamically to computed function in Vue.js

Im trying to pass an id with the v-model so i can pass that to my computed function. The purpose of my function is to dynamically filter a table without hardcoding the names in the function. The function has to be able to filter both select boxes.
my data is called guides, it has an title/active/language_id/group.
this is my html dropdown:
<select v-model="filterResult" :id="language.id" class="select2-selection custom-select">
<option value="">All</option>
<option v-for="language in languages" v-bind:key="language.id" v-bind:value="language.id">{{ language.name }}</option>
</select>
<select v-model="filterResult" :id="active" class="select2-selection custom-select">
<option value="">All</option>
<option :value=1>Active</option>
<option :value=2>Archived</option>
</select>
Here is my computed function now, but as u can see the "language.id" is hard coded in but i want the function to read it out of <select>. what i tried is putting it in the :id="" but i have no idea to forward it to the function besides the v-model. Purpose of all this is so i can reuse the component without changing anything. So it has to be applied to both select boxes or even more in the future.
filterCertainValue: function (evt) {
if (!this.filterResult) return this.guides;
return this.guides.filter(guide => {
if (guide.language.id == this.filterResult) {
return guide.language.id;
}
})
},
You could create a dynamic filter key that changes based on the last selected <select>:
Create a data property (named "filterKey"):
export default {
data() {
return {
filterKey: null
}
}
}
Add a change-event handler to each <select> to set filterKey to the desired key to use in the computed prop's filtering (e.g., language_id or active):
<select #change="filterKey = 'language_id'">
<!-- language_id options -->
</select>
<select #change="filterKey = 'active'">
<!-- active options -->
</select>
Update the computed prop's filter to use the filterKey:
computed: {
filterCertainValue() {
if (!this.filterResult) return this.guides
👇
return this.guides.filter(guide => guide[this.filterKey] === this.filterResult)
}
},
demo

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);
});

ajax- pass dropdown option values as a list

i have a drop down list which allows multiple select like this:
<select id="myId" >
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
</select>
now on change the option i need to make an ajax call (to my controller) which sends the value of selected options
$("#myId").change(function(){
var myId= $("#myId").val();
$.ajax({
url:"${createLink(controller:'clientTrip',action:'fillData')}",
data: ({myId:myId}), // i want myid to be sent as list
dataType: "html",
success: function(data) {
}
});
});
i want to get value of myId as a list (list of selected option values) in my controller..
how can i do it? what changes i should make ?
You should most likely use the selected selector. Something like the following should work
$("#myId").change(function(){
var myIds = new Array();
$("#myId option:selected").each(function(){
myIDS.push($(this).val());
})
$.ajax({
url:"${createLink(controller:'clientTrip',action:'fillData')}",
data: ({myId:myIds}), // i want myid to be sent as list
dataType: "html",
success: function(data) {
}
});
});

Resources