Chosen select not calling a function on ng-click - html

I'm working with a chosen select, i added a function call when the event ng-click happens, but it's not doing anything, when i make the call to the same function in a button it works, why is this?
ng-change doesn't work either, even worse, it eats my options and leaves only the first one.
my select code:
<select ng-model="ind_oferta" multiple class="control-group chosen-select" chosen >
<optgroup label="Oferta">
<option value=""> </option>
<option ng-click="aplicarFiltro()" ng-repeat="menuOpcion in menu[0].opciones.oferta" value={{menuOpcion.id}}>
{{menuOpcion.tipo}}</option>
</optgroup>
</select>
the function is very simple, it's just a javascript alert
$scope.aplicarFiltro = function(){
alert("hello");
}
and i think is not worth put the button code, that one works so...
EDIT: i changed the select code to this, still not making the call to the function, help!
<select multiple class="control-group chosen-select" chosen style="width:250px;"
ng-model="ind_oferta" ng-click="aplicarFiltro();"
ng-options="menuOpcion.id as menuOpcion.tipo for menuOpcion in menu[0].opciones.oferta">
<option>--</option>
</select>

You should use the ng-options directive together with ng-model (you can still add a single <option> as the default value). It would probably look something like this:
<select ng-options="menuOpcion.tipo for menuOpcion in menu[0].opciones.oferta"
ng-model="selected"
ng-change="aplicarFiltro()" chosen multiple>
<option value=""></option>
</select>
There is a lot of customization options, so it is best if you check out the documentation.
To get the option which was removed by the user you could do something like this in your controller:
var previousSelection = [];
$scope.changedSelection = function () {
// Check if the current selection contains every element of the previous selection
for (var i = 0; i < previousSelection.length; i++) {
if ($scope.selectModel.indexOf(previousSelection[i]) == -1) {
// previousSelection[i] was deselected
}
}
// Set the previous selection to the current selection
previousSelection = $scope.selectModel;
}

Related

How do I reset select and ng-select to first option dynamically

UPDATE ::
https://stackblitz.com/edit/angular-ivy-tggo2e?file=src%2Fapp%2Fapp.component.ts
This stack is basically a TLDR of this post.
UPDATE 2::
Ok basically in that blitz, example 2 works. haha. in my code I was resetting that arr2 in my subscribe after the API call but doing it before the API call fixed it. Now I just have to figure out how to give it that first option (Pick something..) on initial load instead of a blank box.
///////////////////
So basically I have a cascade of select dropdowns. Lets call them form1, form2, form3.
When I select form1, it will call an API using that selection and dynamically give me an array to use for form2 options. same for form3,4,5,etc.
Now this is no problem up to here. But when I have selected form1,2,3 and then I select form1 again, I want form 2 and 3 to reset to my disabled option 1 but I can't seem to be able to get that to happen.
Component.ts
dropdownForm() {
this.dropdownForm = new FormGroup({
form1: new FormControl(),
form2: new FormControl(),
form3: new FormControl(),
form4: new FormControl()
)}
callAPI(query) {
// API CALL
}
changeONE(e) {
// this.arr2 = [];
// reset this.dropdownForm.form2 back to the first option 1('Pick something..) to be 'selected' and 'disabled'
// this.callAPI(e)
}
changeTWO(e) {
// this.arr3 = []
// reset this.dropdownForm.form3
this.callAPI(e)
}
changeTHREE(e) {
// this.arr4 = []
// reset this.dropdownForm.form4 -- this one is ng-select so it is way different than the others.
// this.callAPI(e)
}
HTML
<form [formGroup]="dropdownForm">
<div>
<div>
<label for="form1">Form1</label>
<select id="form1"
(change)="changeONE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr">{{item}}</option>
</select>
</div>
<div>
<label for="form2">Form2</label>
<select id="form2"
(change)="changeTWO($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr2">{{item}}</option>
</select>
</div>
<div>
<label for="form3">Form3</label>
<select id="form3"
(change)="changeTHREE($event)">
<option [value]="" selected disabled>Pick something..</option>
<option [value]="item" *ngFor="let item of arr3">{{item}}</option>
</select>
</div>
<div>
<label for="form4">Form4:</label>
<ng-select [multiple]="true" placeholder="Pick something" (change)="changeFOUR($event)" >
<ng-option *ngFor="let item of arr4">{{item}}</ng-option>
</ng-select>
</div>
I've tried adding formControlname in my selects but that makes the select act weird for some reason... maybe its because my 'new FormControl('')' is wrong? But it makes my form1,2,3 just preselect something random in my optionsArr.
And even then, if i do this.dropdownForm.controls.form1.reset() or something like that, it doesn't do anything. it will just reset the value instead of the resetting the dropdown box(which I'm not even using anyways.. haha. I should be but I'm using using that changeONE() and $event to get the value)
Thank you
EDIT::
I just tried
component.ts
this.dropdownForm.get('form2').reset()
HTML
<select id="form1"
(change)="changeONE($event)" formControlName='form1'>
And basically when I have form1 and form2 selected and I go back and select form1 with that this.dropdownForm.get('form2').reset(), it won't reset form2. Instead, it will select the first item in the new updated arr2 (after i get arr2 from that API call) on the second option of that select instead of going to that disabled option one.

How to use form select value to action method (without query)

I'm using pug to render some pages for my nodeJS server. In this case I'm trying to use the value captured in the form select in order to change the action method.
So, the idea is use the group name selected to go to that page:
form.w3-container(action="http://localhost:5004/groups/" + (option selected down below) method="GET")
select.form-control(data-toggle='select' class="form-control" data-placeholder='Disabled results')
option group1
option group2
option group3
button.btn.btn-success(type='submit') Go
Any suggestion on how can I do this, if possible without jquery (if it is not possible without I, an explanation on how to "use" it would be very much appreciated).
From what Shoaib said in this post, it should be possible, but I dint't quit understand his suggestion, poor context :/
HTML code:
<form id="myForm" class="w3-container" action="" method="POST">
<select id="mySelector" data-toggle='select' class="form-control" data-placeholder='Disabled results'>
<option value="">Select</option>
<option value="group1">group1</option>
<option value="group2">group2</option>
<option value="group3">group3</option>
</select>
</form>
ECMAscript code:
var selector = document.getElementById("mySelector");
selector.addEventListener("change", function() {
changeAction();
});
function changeAction() {
var finalAction = document.getElementById("myForm").action = "http://localhost:5004/groups/" + selector.value;
}
JSFiddle: https://jsfiddle.net/ytvhqrs0/1/

Angular deselect all options in multiple select

Goal is that, when I call myMethod(), I want to have all options unselected.
Currently when I call myMethod() it will deselect only the last option, but the other remain selected if they have been selected.
Solutions:
Not using reactive forms - do it like in the accepted answer
Using reactive forms - this.formName.get('formControlName').setValue([]);
HTML
<select multiple>
<option *ngFor="let user of users"
value="{{user.id}}"
[selected]="usersSelected">{{user.name}}
</option>
</select>
Component
usersSelected: boolean = false;
myMethod(): void {
this.usersSelected = false;
}
Thanks for any help.
You should use [(ngModel)] so you can control the value. Note that its multiple select, so you should use array, not just scalar value.
usersSelected = [];
myMethod(): void {
this.usersSelected = [];
}
And in your template:
<select multiple [(ngModel)]="usersSelected">
<option *ngFor="let user of users" [ngValue]="user.id">{{user.name}}</option>
</select>
Working example: https://stackblitz.com/edit/angular-c9y1jm

How do I get the text and not the value of an Option?

I have a form, which is generated by a ticket system, but I have to customize it.
In this form there is a select part with different options, each option got a value with a number and a text (between the tags). I can't change the value because the ticket system need it when you send the form to it. Now I have a function which collects some inputs and place it into a text field (which is also in the form) but, I need the text from the option tag not the value:
<select id="selectfield" bla bla bla>
<option value="1"> something </option>
<option value="2"> something different </option>
<option value="3"> complete other text </option>
</select>
so when I try it with selectfield.value I get the value parameter, but I need the text. Is there any way I can get this text and let the value be still a number?
I think you might be looking for innerHTML have a look at, http://www.w3schools.com/jsref/prop_html_innerhtml.asp
You would need to assign an id to each option like:
<option id="option-1" value="1">Inner text</option>
...
<script>
var innerText = document.getElementById('option-1').innerHTML;
</script>
That answer above it a little tricky, so here's what i did:
<script>
function test() {
var x = document.getElementById('selectfield').selectedIndex;
alert(x);
}
</script>
and the HTML:
<select id="selectfield" onChange="test()">
<option value="0"></option>
<option value="1"> something </option>
<option value="2"> something different </option>
<option value="3"> complete other text </option>
</select>
Notice a few differences here. First, in the javascript, a DOM command called '.selectedIndex' which gets the option selected in the box.
Now for what I did to the HTML, Notice a couple of things. First, you have an event Handler called onChange which calls the function i created called test(). I also added a blank option so that if someone wanted to choose the first one they could, and not have to click the second option and then the first to get that particular choice. Honestly, those value="" attributes are not necessary now.
If you run the code, you might notice that instead of returning text, it returns a number. "A number?" you might ask, "I wanted the text!". Here is a solution I have for you:
var option_Array = [];
option_Array[0] = "";
option_Array[1] = "something";
option_Array[2] = "something different";
option_Array[3] = "complete other text";
Suppose you had an array of the options, now all you would have to do is use the variable x as the index number of the array like so:
option = option_Array[x];
Now the new variable option is equal to whatever item you clicked!
I hope this fully answers your question. I would appreciate any feedback on this answer, as it is 1:10 AM and I'm not perfect.
Just as a side note, it might be a good idea to put a parseInt() around
var x = parseInt(document.getElementById('selectfield').selectedIndex); just in case it returns x as a string instead of a real integer.

Local Storage multiple fields with one field overwriting the second

I am creating a Chrome extension that restricts off-limits TV content. I have two roll-down menu forms that store values to Local Storage.
Javascript (external files):
ratings.js
window.onload=function (){
document.getElementById('saveRatings').onsubmit=saveRatings;
}
function saveRatings() {
var selectedRatings = document.forms["ratings_form"]["ratings"].value;
// store selectedRatings to local storage
localStorage.storedRatings = selectedRatings;
}
age.js
window.onload=function (){
document.getElementById('saveAge').onsubmit=saveAge;
}
function saveAge() {
var selectedAge = document.forms["age_form"]["age"].value;
// store selectedAge to local storage
localStorage.storedAge = selectedAge;
}
HTML
<summary>Select Content to Allow</summary><br>
<form name = "ratings_form" id="saveRatings">
<select name="ratings" multiple="multiple">
<option value="G">G only</option>
<option value="G/PG">G/PG only</option>
<option value="G/PG/PG13">G/PG/PG-13 only</option>
<option value="G/PG/PG13/R">G/PG/PG-13/R</option>
</select>
<div></div>
<input type="submit" value="Save"> </form>
<summary>Select Age Group to Deter</summary><br>
<form name = "age_form" id="saveAge">
<select name="age" multiple="multiple">
<option value="e">Everyone</option>
<option value="ct">Children & Teens;</option>
<option value="c">Children</option>
<option value="0">Turn off</option>
</select>
<div></div>
<input type="submit" value="Save">
</form>
The key-value pair for age_form stores correctly. However, ratings_form always gives me undefined. If I switch up the order (age first and ratings next), then the key-value pair for ratings_form would give me the correct value whereas age_value would give me undefined. It seems like the second form values are overwriting the first form values. How can I prevent this overwriting from occurring.
Thanks for your help.
Of course, your problem is that you're overwriting the window.onload function with whichever code runs last! All you need is a simple console.log(); in each function to see that the first one is not being called. You can remedy this with addEventListener() or by using jQuery's $(document).ready().
window.addEventListener('load', function() {
console.log('1');
});
window.addEventListener('load', function() {
console.log('2');
});
Just remember onload is a property of window and acts just like any variable/property would. Consider this:
var foo = 'bar';
foo = 'baz';
console.log(foo); // displays 'baz', of course! You changed the value!
That is just what you did with the onload function. You changed it to something else.