JavaScript - Pass selected drop down list value to method - javascript

This may be a simple thing, but I am trying to capture the selected value from a drop down list on an JSP page and use the selected value as an argument to a method. I am able to use the onchange event in the select tag to call a java script function and capture the value but I am not sure how to send the value to the method. I think there is a way to do this via an ajax based call but I am not sure how to accomplish this. Here is a sample of the test code I am using. Thank you.
function getSelected()
{
var selectedSource = document.getElementById("myselect").value;
console.log(selectedSource);
}
<select name="myselect" id="myselect" onchange="getSelected();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>

I edited the answer to include the post to the server using jQuery.
There are two errors in your javascript function:
First, you call getselected(), but the function name is getSelectedSource();
Second, you try to find sourceSystem, but your id is myselect.
Make a HTTP Post using jQuery and send a parameter myselect, for example, with value selectedSource.
In your servlet, you can get this parameter using request.getParameter("myselect")
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script>
function getSelected()
{
var selectedSource = $("#myselect").val();
console.log(selectedSource);
$.post("test", { myselect : selectedSource},
function(data) {
alert("Data Loaded: " + data);
});
}
</script>
<select name="myselect" id="myselect" onchange="getSelected();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>

Related

How to call onchange event when dropdown values are same

I am using Jquery chosen plugin and it's working fine. I have used this plugin in my one of the module. My dropdown values are something like that:
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
It's working fine. But problem is that when user select first option and then try to change third option onchange event does not fire because both options values are same. Is there any way to call onchange event every time if values are same or differ ?
Options values is a unique key of item so it's repeated in dropdown. Dropdown value is duplicate we have allowed to use same item in others module
I saw your implementation and it is working fine in code pen here is the link no need to change anything
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
var get_data =function(){
alert("saas")
}
http://codepen.io/vkvicky-vasudev/pen/dXXVzN
Try this
$('#itemcode').click(function() {
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="itemcode">
<option value="1">ITEM001-A</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001-B</option>
<option value="3">ITEM003</option>
</select>
Edit: This doesn't work. Sorry!
You could add a data attribute that differs for each element, for example:
<select id="itemcode" onchange="get_data()">
<option value="1" data-id="1">ITEM001</option>
<option value="2" data-id="2">ITEM002</option>
<option value="1" data-id="3">ITEM001</option>
<option value="3" data-id="4">ITEM003</option>
</select>
If you're using Rails or another framework to generate the <option> tags, it should be easy to add an incremental id to each element.
There is no way to fire get_data() with your current data.
The solution below is more of a hack. When you populate the options, prepend the value with something unique.
Eg.
<select id="itemcode" onchange="get_data()">
<option value="1_1">ITEM001</option>
<option value="2_2">ITEM002</option>
<option value="3_1">ITEM001</option>
<option value="4_3">ITEM003</option>
</select>
Thus your get_data() method will be called everytime. And in your get_data() method, split the value using underscore _ and you can get the actual value there.
function get_data(){
var actualValue=$(this).val().split("_")[1];
//do other processing
...
}
You can use other characters like $, or anything you like, instead of _
Ideally you want to change the data coming from the backend so that you don't get duplicate data. However if this is not possible, another approach would be to sanitise the data before putting it in the select. E.g
https://jsfiddle.net/vuks2bpt/
var dataFromBackend = [
{key:1,
value: "ITEM0001"
},
{key:2,
value: "ITEM0002"
},
{key:1,
value: "ITEM0001"
},
{key:3,
value: "ITEM0003"
}
];
function removeDuplicates(array){
var o = {};
array.forEach(function(item){
o[item.key] = item.value;
});
return o;
}
function get_data(){
console.log('get_data');
}
var sanitised = removeDuplicates(dataFromBackend);
var select = document.createElement('select');
select.id = "itemcode";
select.addEventListener('change', get_data);
Object.keys(sanitised).forEach(function(key){
var option = document.createElement('option');
option.value = key;
option.textContent = sanitised[key];
select.appendChild(option);
})
document.getElementById('container').appendChild(select);
i am using jquery instead of java script
<select id="itemcode">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
jquery
$('#itemcode:option').on("click",function(){
alert(saaas);
})

ASP.NET MVC4 with Razor - Filtering dropdownlist by value selected from another dropdownlist

I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});

Angular: dynamic value issue

I am trying to show different data from a large data object based on selections made in view via a select box. I am populating the data like this
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
And I have ng-model on my select options.
<select ng-model="networkType">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
I initialize both of these variables
$scope.selectedType = 'individual';
$scope.networkType = 'inNetwork';
And the $scope.displayData is initially correct. However when I change the drop downs, the displayData does not change its values to access the new data. I am not sure what step I am missing here.
I think you should update the display data using ng-change event.
Add a update function in your controller
$scope.updateDisplay = function() {
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
};
Add ng-change for your <select> element
<select ng-model="networkType" ng-change="updateDisplay()">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType" ng-change="updateDisplay()">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
Or do it with $scope.$watch.
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
A value function
A listener function
The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed.
In my example, we are setting up a watch on both networkType and selectedType models. And instead of it being a funtion we simply put the $scope model name.
$scope.$watch('[networkType,selectedType]', function(newValues, oldValues) {
$scope.displayData = $scope.dataObj[newValues.selectedType][newValues.networkType];
});
Add this method to your controller
$scope.onChnage = function () {
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
}
Html
<select ng-model="networkType" ng-change="onChnage ()">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType" ng-change="onChnage ()">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
Beside $watch and ng-change, if you just want to display the data in displayData variable, another option is to convert it to a function display():
$scope.display = function () {
return $scope.dataObj[$scope.selectedType][$scope.networkType];
};
and in the view:
{{display()}}
this function will be called again whenever selectedType or networkType change

Selected option Not Setting in new browser Window Tab

<select id="country_name" onchange="changeCounty();">
<option value="IND"> IND</option>
<option value="US">US</option>
<option value="JP">JP</option>
<option value="UK">UK</option>
</select>
i have the above code.
when i select one option it will do some changes to the page.but when i open the page in new tab of browser the already selected option reset. and default selected option set.How do i cop with this?
You need something to pass the value from one page to another, as tabs are by default totally separate pages.
One workaround could be something like this (using LocalStorage) :
// Save value when it is changed by user
function changeCounty(){
if(window.localStorage){
var inputValue = document.getElementById('country_name').value
window.localStorage.set('mySavedValueName',inputValue )
}
//..your original code
}
// Load value if it exists
window.addEventListener('load', function getContryFromLS(){
if(window.localStorage){
var lsvalue = window.localStorage.get('mySavedValueName')
if(lsvalue)
document.getElementById('country_name').value=lsvalue
}
}
Your Html code
<select id="country_name" onchange="changeCounty(this);">
<option value="IND"> IND</option>
<option value="US">US</option>
<option value="JP">JP</option>
<option value="UK">UK</option>
</select>
JQuery Code
$(function(){
var d=localStorage.getItem("selectval");
if(d!=null){
console.log(d);
$("#country_name").val(d);
}
$("#country_name").change(function(){
localStorage.setItem("selectval",$(this).val());
});
});
Demo Here

How to select default select option based on option value not index while using AngularJS?

I have options arriving in AJAX request. I had no success with setting
$("#environment").val("SWTEST 051t:8083");
in success callback function in $http.get. Can I select default option by VALUE not index after it was loaded by get?
ng-init="environment.name = environment.name || options[0].value" ng-model="environment.name"
Since you have environment.name model, try to set its value in success callback:
$scope.environment.name = "SWTEST 051t:8083";
If you prefer a JQuery solution:
thevalue="SWTEST 051t:8083";
$('#environment option').filter(
function(i, e)
{
return $(e).val() ==thevalue}
).attr('selected', 'selected');
If you had this code it would work:
<select id="environment">
<option>select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Example working:
http://jsfiddle.net/wteopnv6/1/
I think you should watch options change by $watch method
$scope.$watch("options", function (){
$scope.environment.name = $scope.options[0].value;
});

Categories