How to call AngularJS function from select > option - html

I need to call an AngularJS function from selection:
<select ng-model="selection" >
<option onselect="angular.element(this).scope().functionCall('one')">one</option>
<option onselect="angular.element(this).scope().functionCall('two')">two</option>
<option onselect="angular.element(this).scope().functionCall('three')">three</option>
<option onselect="angular.element(this).scope().functionCall('four')">four</option>
</select>
However, the function never gets called.
In the controller,
$scope.functionCall = function(value){
// do stuff with value
}
How can I call the function.

It's recommended that you use ng-change for that matter, the result may be the same as Cyril's, but the code is more readable and testable, also it is considered a better practice:
Here is a plunker demonstrating it in action:
http://plnkr.co/edit/7GgwN9gr9qPDgAUs7XVx?p=preview
app.controller('MainCtrl', function($scope) {
$scope.listOfOptions = ['One', 'Two', 'Three'];
$scope.selectedItemChanged = function(){
$scope.calculatedValue = 'You selected number ' + $scope.selectedItem;
}
});
And the HTML:
<select ng-options="option for option in listOfOptions"
ng-model="selectedItem"
ng-change="selectedItemChanged()">
</select>
Hope that helps. Thanks.

A Little bit to add on Cyril's and Fedaykin answers:
HTML code
<select ng-options="option for option in listOfOptions"
ng-model="selectedItem"
ng-change="selectedItemChanged()">
Controller Code
app.controller('MainCtrl', function($scope) {
$scope.listOfOptions = ['One', 'Two', 'Three'];
$scope.selectedItemChanged = function(){
console.log($scope.selectedItem);
}
});
You will notice that when the select option is changed, a function gets called which will give the you the value of the current selected value.

Here's what you could do :
HTML
<div ng-controller="YourController">
<select ng-model="selection" ng-options="choice for choice in choices"></select>
</div>
YourController :
$scope.choices = ["first choice", "second choice",...]
$scope.$watch('selection', function(newVal, oldVal){
switch(newVal){
case 'first choice':
[do Some Stuff]
break;
case 'second choice':
[do Some Stuff]
break;
default:
[well, do some stuff]
break;
}
}
BTW: I decided to put the options in the javascript, but what you did also works.
EDIT : ng-change VS $watch, see this question

First, onselect is not a angular keyword, It's a normal javascript keyword
You should use ng-change param in select or use like below..,
In HTML code you have to use like this.,
<select ng-model="selection" >
<option onselect="functionCall('one')">one</option>
<option onselect="functionCall('two')">two</option>
<option onselect="functionCall('three')">three</option>
<option onselect="functionCall('four')">four</option>
</select>
and in the controller
function functionCall(value){
//do stuff with value
}

Related

Alert on change of select option using jQuery in console [duplicate]

is there anyway i could trigger a change event on select box on page load and select a particular option.
Also the function executed by adding the trigger after binding the function to the event.
I was trying to output something like this
<select class="check">
<option value="one">one</option>
<option value="two">two</option>
</select>
$(function(){
$('.check').trigger('change'); //This event will fire the change event.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
});
http://jsfiddle.net/v7QWd/1/
Use val() to change to the value (not the text) and trigger() to manually fire the event.
The change event handler must be declared before the trigger.
Here's a sample
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');
To select an option, use .val('value-of-the-option') on the select element. To trigger the change element, use .change() or .trigger('change').
The problems in your code are the comma instead of the dot in $('.check'),trigger('change'); and the fact that you call it before binding the event handler.
Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :
var sortBySelect = document.querySelector("select.your-class");
sortBySelect.value = "new value";
sortBySelect.dispatchEvent(new Event("change"));
$('#edit_user_details').find('select').trigger('change');
It would change the select html tag drop-down item with id="edit_user_details".
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
If you want to do some checks then use this way
<select size="1" name="links" onchange="functionToTriggerClick(this.value)">
<option value="">Select a Search Engine</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
<script>
function functionToTriggerClick(link) {
if(link != ''){
window.location.href=link;
}
}
</script>
Based on Mohamed23gharbi's answer:
function change(selector, value) {
var sortBySelect = document.querySelector(selector);
sortBySelect.value = value;
sortBySelect.dispatchEvent(new Event("change"));
}
function click(selector) {
var sortBySelect = document.querySelector(selector);
sortBySelect.dispatchEvent(new Event("click"));
}
function test() {
change("select#MySelect", 19);
click("button#MyButton");
click("a#MyLink");
}
In my case, where the elements were created by vue, this is the only way that works.
You can try below code to solve your problem.
By default, first option select:
jQuery('.select').find('option')[0].selected=true;

Trying to populate html select with ng-repeat in angularjs

I am trying to populate my select in html using ng-repeat, but it does not work. I observed that my ng-repeat appears to be commented when i inspect my browser.
My html:
<select ng-model="transportcompanies" ng-options="TransportCompany in transportcompanies" value="{{TransportCompany.denumire}}">
<option>{{ TransportCompany.denumire }}</option>
</select>
My get service from server.js:
app.get('/#!/races/insert', (req, res) => {
TransportCompany.findAll({
attributes: ['id_firma', 'denumire']
})
.then((transportcompanies) => {
res.status(200).send(transportcompanies)
})
.catch((error) => {
console.warn(error)
res.status(500).send('error')
})
})
My controller:
angular.module('raceModule').controller('racesInsertController', ['$scope', '$http', '$state', function($scope, $http, $state) {
const SERVER = 'https://proiectweb-sebastianburchi.c9users.io/#!'
let $constuctor = () => {
$http.get(SERVER + '/races/insert')
.then((response) => {
$scope.race=response.data
})
.catch((error) => console.log(error))
}
$constuctor()
$scope.open = function($event,opened) {
$event.preventDefault();
$event.stopPropagation();
$scope[opened] = true;
};
$scope.getTemplate = (TransportCompany) => {
return 'display'
}
}])
i have edit my post trying to work with ng-options.Ng-repeat is not working. Now it displays me, but i have TransportCompany.denumire as option..not it's value
TRY This
<option ng-repeat="TransportCompany in transportcompanies"> {{TransportCompany.denumire}}</option>
You have written the same name for both ng-repeat iterator object and options. So, when you select an option from select list, the value over writes. So, change the names to some other as:
<select ng-model="transportcompanies">
<option ng-repeat="TransportCompany in transportcompanies" value="{{TransportCompany.denumire}}">TransportCompany.denumire</option>
</select>
to:
<select ng-model="someothername">
<option ng-repeat="TransportCompany in transportcompanies" value="{{TransportCompany.denumire}}">TransportCompany.denumire</option>
</select>
<select>
<option ng-repeat="option in options" ng-value="option.html">
{{option.display}}
</option>
</select>
Please refer to the plunker https://plnkr.co/edit/EgOJaWCjQtv7jDB5RS39?p=preview
First of all, please maintain the naming conventions. Apart of that, below should be working fine:
<select ng-model="transportcompanies">
<option ng-repeat="TransportCompany in transportcompanies" value="{{TransportCompany.denumire}}">{{TransportCompany.denumire}}</option>
</select>
For your reference : Plunkr link
Your response data if assigned to $scope.race, so try to iterate on race.
<select ng-model="transportcompanies" ng-options="TransportCompany in race" value="{{TransportCompany.denumire}}">
<option>{{ TransportCompany.denumire }}</option>
</select>

How can I display option text on the dropdown menu that is different than the selected text?

Using a simple select, I want to display one text on the dropdown list and another text in the select control after the option was selected. It's pretty similar to option's label attribute in its concept.
I'm not sure if it's even possible. Here's a not-working example:
<select>
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>
Update: I didn't mention that I need to incorporate this solution in a generated HTML (ng-table filters), so any solution that is not pure HTML will be very hard to use. I even consider to look for another table control as a simpler solution, which is pretty basic - placeholder text in select filter.
I've created a question more specific to my problem:How can I put a placeholder text on ng-table select filter?
Here's a relatively simple solution that relies on the standard value attribute and a custom data-* attribute:
function showDisplayValue(e) {
var options = e.target.options,
option = e.target.selectedOptions[0],
i;
// reset options
for (i = 0; i < options.length; ++i) {
options[i].innerText = options[i].value;
}
// change the selected option's text to its `data-display` attribute value
option.innerText = option.getAttribute('data-display');
}
document.getElementById('foo').addEventListener('change', showDisplayValue, false);
<select id="foo">
<option data-display="*** BAR ***" value="Bar">Bar</option>
<option data-display="*** BAZ ***" value="Baz">Baz</option>
<option data-display="*** QUX ***" value="Qux">Qux</option>
</select>
Found something similar to what you're asking for here:
https://stackoverflow.com/a/19184179/6555780
It basically needs to be organised in javascript, so that the selected option shows immediately on the screen, the below code was taken from David's answer and can be viewed here: http://jsfiddle.net/aCb73/
<select name="ref_rubrique" id="ref_rubrique">
<option value="-- EMPTY --" selected> </option>
<option value="YES!!!">Yes</option>
</select>
<div id="ref_output"></div>
<script type="text/javascript">
var selectElement = document.getElementById('ref_rubrique');
var divElement = document.getElementById('ref_output');
selectElement.onchange = function () {
var selectedValue = selectElement.options[selectElement.selectedIndex].value;
if (selectedValue == '-- EMPTY --') {
divElement.innerHTML = '<p>No</p>';
} else if (selectedValue == 'YES!!!') {
divElement.innerHTML = '<p>Yes</p>';
}
};
</script>
This basically targets the ref_rubique select tag and displays the code in the Javascript based on the selection (defaults as --EMPTY--)
Following our comments below, the following code could possibly help with ng-table:
self.initialSorting = [
{ label: "Id ASC", value: { id: "asc"} },
{ label: "Id DESC", value: { id: "desc"} },
{ label: "Name ASC", value: { name: "asc"} },
{ label: "Name DESC", value: { name: "desc"} }
];
What I understand is you want to print the text in select-text attribute.
I've found this example if this is what you are looking for.
<select id="mySelect">
<option select-text="-- EMPTY --"> </option>
<option select-text="YES!!!">Yes</option>
<option>No</option>
</select>
$("#mySelect").change(function(){
$("#mySelect option:selected").text($("#mySelect").val());
});
This is where I found something similar.
HTML select shows value instead of text

change the value of a select tag using jquery

I am working on a wordpress site. I have an html with select tag and some options. When the form is submitted, I want to replace the value of option 'Other' with this value 'Rosemont' if option 'Other' is selected. Below is my html.
<select class="expand" name="field_19" id="field_19">
<option value="Bryn Mawr">Bryn Mawr</option>
<option value="Devon">Devon</option>
<option value="Gladwyne">Gladwyne</option>
<option value="Haverford">Haverford</option>
<option value="Other">Other</option>
</select>
Now I want that if the option 'Other' is selected then the selected value should be changed to text 'Rosemont'. So that the value 'Rosemont' should be saved into the database instead of 'Other'. I have written some jquery code but its not working.
Here is my code
jQuery(function(){
jQuery('#signup_submit').click(function(){
var city_name = jQuery('select[name="field_19"]').val();
alert(city_name)// this alerts 'Other'
if(city_name=='Other'){
valr = 'Rosemont';
jQuery('select[name="field_19"]').val(valr);
var vals = jQuery('select[name="field_19"]').val();
alert(vals);// again this alerts 'Other'. this should alert Rosemont
}
});
Something like this? jsBin demo
jQuery(function($) {
$('#signup_submit').click(function(e){
e.preventDefault();
var $f19 = $('select[name="field_19"]');
var f19Val = $f19.val();
if(f19Val=='Other'){
var $oth = $('[value=Other]',$f19);
var newVal = "Rosemont";
$oth.val(newVal).text(newVal);
}
});
});

getting the NAME of a select tag with javascript

I haven't found this question anywhere so I'm posting it here.
I have a bunch of select tags that are partially named using VBScript. I want to be able to get the name of a select tag that was called from the onchange event in javascript.
here is the code.
<select name="optWeeks_<%=intLineCnt%>" id = "name" onchange="changeWeek()">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<SCRIPT LANGUAGE = "JavaScript">
function changeWeek(){
var chosenoption = document.getElementsByTagName("select").name
}
</SCRIPT>
The select name - "optWeeks_<%=intLineCnt%>" is optWeeks prefixed with a number
I would like to know if I can get each name of the select tag that is called? Ex. optWeeks_1, optWeeks_2 etc.
Change the call to:
... onchange="changeWeek(this);">
Then you can simply;
function changeWeek(caller) {
var chosenoption = caller.name;
}
You need to get a reference to the element. this will be one in your event handler function. You can pass it to the function you are calling from there:
onchange="var element = this; changeWeek(element)">
I included the variable assignment above for clarity, you don't need it:
onchange="changeWeek(this)">
You can then get the name from the name property on that object:
function changeWeek(element) {
var name = element.name;
I'd generally recommend binding your event handlers with JS rather than HTML, not using HTML 3.2 though:
<select name="optWeeks_<%=intLineCnt%>" id="name">
<!-- … -->
</select>
<script>
var select = document.getElementById('name');
select.addEventListener('change', changeWeek);
function changeWeek(evt) {
var name = this.name;
}
</script>
Or you can use:
onchange="changeWeek(this.name)"
Or: (keep in mind that the changeWeek function will have to already have been defined)
<script>
var select = document.getElementById('name');
select.onchange = changeWeek;
</script>
addEventListener vs onclick -- for information between adding event listeners and the method I provided above.
An alternative JavaScript way:
var selects = document.getElementsByTagName('select');
for(var i in selects)
{
selects[i].onchange = function changeWeek(e) {console.log(e.target.name);}
}
HTML:
<select name="test">
<option>One</option>
<option>Two</option>
</select>
<select name="test2">
<option>One</option>
<option>Two</option>
</select>
Fiddle:
http://jsfiddle.net/bddwW/