I have a problem updating <select> with ng-init.
HTML:
<form data-ng-init="showStudent()">
<select id="studbranch" data-ng-model="student.branch"
data-ng-options="obj.name for obj in branches track by obj.id" required>
<option value="">-- Select Branch --</option>
</select>
</form>
Outputs:
<option value="">-- Select Branch --</option>
<option value="1">Branch 1</option>
<option value="2">Branch 2</option>
<option value="3">Branch 3</option>
In JS file:
$scope.branches = [{"id":"1","name":"Branch 1"},{"id":"2","name":"Branch 2"},{"id":"3","name":"Branch 3"}];
$scope.showStudent = function() {
$.getJSON('student.php', function(data) {
$scope.student = data[0]; $scope.$apply();
alert($scope.student.branch);
});
}
On page load (init), it alerts 3. That means student.branch is set to 3. But the select is not updated. It stays at default value. What could be wrong? Are the select values set after init?
If I add $('#studbranch').val($scope.student.branch); after the alert() it works fine.
Please try do that in angular way not jQuery
app.controller(function($scope, $http){
...
$scope.student = [];
$scope.showStudent = function() {
$http.get('student.php').then( function(data) {
angular.copy(data[0], $scope.student);
alert($scope.student.branch);
});
};
...
}
Your ng-options should be formatted like so:
data-ng-options="obj.id as obj.name for obj in branches track by obj.id"
Assigning the ng-model of the select to the right id will now update the select.
Related
I have an issue with the return value in js. I need to return it because I wanna use it in
var rusiavimas = selectedServices();
So, my function looks like this.
function selectedServices()
{
var selectedServices = [];
$('.common_change').change(function(){
selectedServices = $(this).val();
alert(selectedServices);
});
return selectedServices;
}
My HTML code
<select name="rusiavimas" class="common_change" id="cars">
<option value="none" selected disabled hidden>
Pasirinkite variantą
</option>
<option value="naujausi">Naujausi viršuje</option>
<option value="pigiausi" >Pigiausi viršuje</option>
<option value="brangiausi">Brangiausi viršuje</option>
</select>
Then I select the option, in the alert function I get the correct value, but in my return, it's not returning it.
Your code contains a lot of problem, I try to fix them below
Your JS script is always return an empty array, because when you call the function var rusiavimas = selectedServices(); the inner .change function is not runs and not change the value of the array
var selectedServices = [];
$('.common_change').change(function(){
selectedServices.push($(this).val());
if(selectedServices.length > 0){
alert("selected service: " + selectedServices.toString());
}
console.log(selectedServices);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="rusiavimas" class="common_change" id="cars">
<option value="none" selected disabled hidden>
Pasirinkite variantą
</option>
<option value="naujausi">Naujausi viršuje</option>
<option value="pigiausi" >Pigiausi viršuje</option>
<option value="brangiausi">Brangiausi viršuje</option>
</select>
Each time after changing your array it gives to your array the last common value.
The best way as was said an comments use selectedSerices.push($(this).val());
You can also use deep copy, which is less recommended in your case selectedSerices = [...selectedSerices, $(this).val()]. I guess it will help you!
I require a bit of jQuery to do the following:
A user can currently select Program and/or a region.
If a user selects Program AND a Region I require the option values of the region dropdown to change to "?region=1" and "?region=2"
<select class="program" id="program">
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Greatly appreciate the assist.
My attempt at JQuery:
$('#program').on('change', function () { if($(this).val() !="0") { } else { // no option is selected } })
You need to further extend the change event for #program and include a similar one for #region.
var programSelected = null;
var regionSelected = null;
$('#program').on('change', function(element) {
programSelected = $('#program option:selected').text();
updateRegionOptions();
});
$('#region').on('change', function(element) {
regionSelected = $('#region option:selected').text();
updateRegionOptions();
});
function updateRegionOptions() {
if(programSelected != null && regionSelected != null) {
$('#region option').each(function() {
var modifiedString = '?';
modifiedString += $(this).val().replace(/\d+/,'');
modifiedString = modifiedString.replace('.html','');
modifiedString += '=';
modifiedString += $(this).val().match(/\d+/);
$(this).val(modifiedString);
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="program" id="program">
<option value="" selected disabled>Select Program</option>
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="" selected disabled>Select Region</option>
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Explanation of the logic above:
on('change' event for both #region and #program
Set the relevant variable programSelected or regionSelected depending on the change event
Run function updateRegionOptions();
If the variables programSelected and regionSelected both have a value
For each of the options in #region
Mutate the existing value to be of the form "?region=1" and "?region=2"
Update the value section of each of the option elements to have this value
The relevant JSFiddle for review.
If this solved your issue, please accept this answer :)
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);
})
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
I have a dynamic number of dropdowns. When a value is selected in the first dropdown, the value of the second and so on dropdowns will be the same with the first dropdown. But the user has the option to change the value of the second and so on dropdowns, but not changing the first and other dropdown's value.
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
How can I achieve this using javascript or jquery libraries?
You can attach a listener to the first select element:
var selects = document.querySelectorAll('select[name="dropdown[]"]');
selects[0].addEventListener('change', function () {
for (var i = 0; i < selects.length; i++) {
selects[i].value = selects[0].value;
}
});
When the value of only the first select changes, it updates the values of the other selects. This way does not rely on any 3rd-party libraries.
Demo: http://jsfiddle.net/cuefb9ag/
Use a change event and then alter the other dropdowns:
$("select[name=dropdown\\[\\]]").change(function() {
var value = this.value;
$("select[name=dropdown\\[\\]]").not(this).val(value);
});
Demo: http://jsfiddle.net/awv14f6r/1/
If you want to change them in order (first alters the second, etc) - use next along with this
$(this).next("select").val(value);
var id = $('#DropDownID1 option:selected').val();
var textValue = $('#DropDownID1 option:selected').text();
$('#DropDownID2').prop('selectedIndex', 0);
$('#DropDownID2').select2('data', {
val: id,
text: textValue
});
$('#DropDownID2 option:selected').val(id);
}