How to keep the selected value after selecting from options? - javascript

I'm quite new at AngularJS programming, just a few weeks with it and I would like to understand why, in the select box I use, when reloading the page or switching between pages and returning to this one, the option selected does not stay as the main option to be shown, and the option <option value="" selected>No assignat</option> is the one that always stays there?
<select ng-model="selected" ng-options="poblacio.title for poblacio in poblacions" ng-change="canviarPoblacio(selected)">
<option value="" selected>No assignat</option>
</select>
-CONTROLLER
.controller('ConfigCtrl', function($scope, noms, fPoblacions){
$scope.poblacions = fPoblacions.getPoblacionsConfig();
$scope.selected = localStorage.getItem('nomPobleConfig');
$scope.canviarPoblacio = function(objPobla){
localStorage.setItem('nomPobleConfig', objPobla.title);
localStorage.setItem('idPobleConfig', objPobla.id);
window.location.reload();
}
})
$scope.poblacions receives a list of names from a factory and the name that the user selects is storaged at the localstorage and would have to remain selected in the Select box, I hope you can help me :)
Excuse me if my english's not good at all, thanks for your future answers and I hope I find in them what I have not by searching and researching here in stackoverflow and everywhere..
-EDITED
I would like to add that, when I run it to see how it works, that's what appears in the Chrome console:
<select class="selectBox ng-pristine ng-untouched ng-valid" ng-model="selected" ng-options="poblacio.title for poblacio in poblacions" ng-change="canviarPoblacio(selected)">
<option value="" selected="selected">No assignat</option>
<option value="object:9" label="name1">name1</option>
<option value="object:10" label="name2">name2</option>
<option value="object:11" label="name3">name3</option>
<option value="object:12" label="name4">name4</option>
<option value="object:13" label="name5">name5</option>
<option value="object:14" label="name6">name6</option>
<option value="object:15" label="name7">name7</option>
<option value="object:16" label="name8">name8</option>
<option value="object:17" label="name9">name9</option>
<option value="object:18" label="name10">name10</option>
<option value="object:19" label="name11">name11</option>
<option value="object:20" label="name11">name11</option>
<option value="object:21" label="name12">nam12</option>
<option value="object:22" label="name13">name13</option>
<option value="object:23" label="name14">name14</option>
<option value="object:24" label="name15">name15</option>
</select>
I mean, the values assigned automatically are object:xx, and I suppose that it would be better to be the id's of every name, which in the factory are 1,2,3,4,5... respectively, same ID as the nameXX number.. if this can be solved too, it would be good :)

Since you are using ng-model='selected' You have to initialize $scope.selected like:
$scope.selected = localStorage.getItem('nomPobleConfig');

When you set $scope.selected, you are only setting it to the "title", not the actual selected object.
localStorage.setItem('nomPobleConfig', objPobla.title);
You'll need to set the full object into localStorage like this:
localStorage.setItem('nomPobleConfig', objPobla);

Related

Change "value" of combobox option JS

So, as the title says I want to change the value of a certain option using JS. I have already looked for it but every answer refers to changing the selected option not the value of a specifical option.
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
I want to change "Ver" option value from 0 to 1. I don´t know if it is possible but thanks in advance.
Have you tried assigning it an id and then changing it in your js file?
Something like this:
<option value='0' id='opt1' selected>Ver</option>
and in javascript:
document.getElementById("opt1").value = "1";
You can select the option with value 0 using
let opt = document.querySelector('select.form-control option[value="0"]')
You can then change the value by reassigning it
opt.setAttribute('value', '1')
If you have more than one select with class form-control this could be a problem, and you might want to give it/them a unique id — then the selector would be
let opt = document.querySelector('select#your-id option[value="0"]')
Here is a stack snippet doing this, where I've combined the select and the assignment into a single statement. I've also added a change event listener to show the value in the console, so if you switch to 20 then switch to Ver again it would print 20 and then 1 to the console, showing you that the value is indeed 1, not 0
document.querySelector('select.form-control')
.addEventListener('change', function(e) {
console.log(this.value);
});
document.querySelector('select.form-control option[value="0"]')
.setAttribute('value', '1');
select {
min-width: 10em;
}
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
Hello you can assign the value with the following instruction
$("#SelectID").val("value option");
document.getElementById("SelectID").value = "value option";
reference in this url Set value of combobox or select

JavaScript - output value from dropdown menu more than once?

I'm in the middle of the process to create a very simple tool that allows my group to select a conference place. I'm getting some issues and hope I can receive some suggestions and help from you.
I have a dropdown menu, it allows user to select the conference location and it will display in text. For example:
HTML
<select onchange="changed('list_1')" id="list_1" class="travel" />
<option selected disabled>Select Place</option>
<option value="New York">New York</option>
<option value="Pennsylvania"> Pennsylvania</option>
<option value="Boston">Boston</option>
<option value="Washigton DC">Washigton DC</option>
</select>
JavaScript
function changed(listId) {
var list = document.getElementById(listId);
document.getElementById("val_"+listId).innerHTML = list.value;
}
document.getElementById("val_list_1").innerHTML = document.getElementById("list_1").value;
Below is the output I am looking for:
You select New York as the conference location. Please make sure you confirm with supervisor before you attend the conference in New York.
When selecting "New York", the value is successfully displayed between You select "Value" as the conference location. Unfortunately because document.getElementById can only be used once, so I'm unable to get the same value "New York" to output in the second sentence.
I was wondering if any of you can show me an example or give me some ideas of how I can select the value only once from dropdown but the value will display in multiple areas?
Any help would be greatly appreciated
You don't have a limit of using the value of an element, here is a simple solution to your problem :
Use a simple template for the text you want to display :
var textTemplate = 'You select {CITY} as the conference location. Please make sure you confirm with supervisor before you attend the conference in {CITY}.';
function changed(list_id){
var cityName = document.getElementById(list_id).value;
document.getElementById('outputTest').innerHTML = textTemplate.split('{CITY}').join(cityName);
}
this suppose you have an html code like :
<select onchange="changed('list_1')" id="list_1" class="travel" />
<option selected disabled>Select Place</option>
<option value="New York">New York</option>
<option value="Pennsylvania"> Pennsylvania</option>
<option value="Boston">Boston</option>
<option value="Washigton DC">Washigton DC</option>
</select>
<p id="outputTest"></p>
Well, first off you are mistaken about only being able to use document.getElementById once, there is no such restrictions and I have no idea why you would think there was.
That said, the way to get the value and then use it more than once is to store it in a variable.
Fix the opening tag so it is not self closing. Also change the onchange function to take this as an argument, referring to itself.
<select onchange="changed(this)" id="list_1" class="travel">
Rewrite the changed function to include any select as a parameter. You may refer to the value of the select element with its value property. This property is reusable as many times as you desire. Store it in a variable if you prefer. Example:
function changed(select) {
console.log('Visiting ' + select.value + '? Enjoy your trip to ' + select.value + '.');
}
<select onchange="changed(this)" id="list_1" class="travel" >
<option selected disabled>Select Place</option>
<option value="New York">New York</option>
<option value="Pennsylvania"> Pennsylvania</option>
<option value="Boston">Boston</option>
<option value="Washigton DC">Washigton DC</option>
</select>

Angular 2 form set selected of STATIC select menu

I've got a Angular 2 form with a static select menu
<select formControlName="type" name="type">
<option value="reference">Referentie</option>
<option value="name">Aanhef</option>
<option value="street">Street</option>
<option value="postcode">Postcode</option>
</select>
How can I set the first as the selected value. What ever I do it turns up blank.
I've tried:
<option selected...
<option selected="selected"...
<option [selected]="selected"...
<option [selected]="reference"...
this.searchform.value.type = 'reference';
Hope someone can help.
this.searchform.controls['type'].setValue('reference')
<option value="name" selected>Aanhef</option>
works. You can refer
Plunkr

Get Checked Only in <Select multiple>

I am trying to get only the checked names in a list of names. Here is my code model:
<select ng-model="selectTopic" ng-change="changedTopic(selectTopic)" ng-options="option as option for option in topics">>
<option value="" disabled>Select a Subject</option>
</select>
<select ng-model="selectDept" ng-change="changedDepartment(selectDept)" ng-options="option as option for option in department">
<option value="" disabled>Select a Department</option>
</select>
<select ng-model="selectUser" ng-options="option as option for option in users" multiple="multiple">
<option value="" disabled>Select a User</option>
</select>
I want to get the selected topic, department, and users. I am currently using: console.log($scope.topics + $scope.departments + $scope.users) but it returns everything. I just want to return the selected items.
Can anyone help me out?
You have to print the ng-models , not the arrays:
console.log($scope.selectTopic);
console.log($scope.selectDept);
console.log($scope.selectUser);
Hope it helps =)
use one object for the model in your form , then you have all the user input in that one object which makes it simple to send to server or to reset form
$scope.userInput={}
<select ng-model="userInput.selectTopic" ng-change="changedTopic(userInput.selectTopic)" ng-options='...'>
<select ng-model="userInput.selectDept" ng-change="changedDepartment(userInput.selectDept)" ng-options='...'>
to see this working put the following in your view temporarily
<pre>{{userInput|json}}</pre>

JQuery - how to select dropdown item based on value

I want set a dropdown(select) to be change based on the value of the entries.
I have
<select id="mySelect">
<option value="ps">Please Select</option>
<option value="ab">Fred</option>
<option value="fg">George</option>
<option value="ac">Dave</option>
</select>
And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?
You should use
$('#dropdownid').val('selectedvalue');
Here's an example:
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3 is the index of the option you want.
Live Demo
$('#mySelect').val('fg');...........
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
You can use this jQuery code which I find it eaiser to use:
$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="your_id" name="name" class="form-control input-md">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
<option value="3">Option #3</option>
<option value="4">Option #4</option>
<option value="5">Option #5</option>
<option value="6">Option #6</option>
<option value="7">Option #7</option>
</select>
You can simply use:
$('#select_id').val('fg')
In your case $("#mySelect").val("fg") :)
May be too late to answer, but at least some one will get help.
You can try two options:
This is the result when you want to assign based on index value, where '0' is Index.
$('#mySelect').prop('selectedIndex', 0);
don't use 'attr' since it is deprecated with latest jquery.
When you want to select based on option value then choose this :
$('#mySelect').val('fg');
where 'fg' is the option value
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
This code worked for me:
$(function() {
$('[id=mycolors] option').filter(function() {
return ($(this).text() == 'Green'); //To select Green
}).prop('selected', true);
});
With this HTML select list:
<select id="mycolors">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.
The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.
So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:
$('#project-locationSearch-dist-input').val('1');
<label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
<select id="project-locationSearch-dist" data-tabindex="1">
<option id="optDistrictOne" value="01">1</option>
<option id="optDistrictTwo" value="02">2</option>
<option id="optDistrictThree" value="03">3</option>
<option id="optDistrictFour" value="04">4</option>
<option id="optDistrictFive" value="05">5</option>
<option id="optDistrictSix" value="06">6</option>
<option id="optDistrictSeven" value="07">7</option>
<option id="optDistrictEight" value="08">8</option>
<option id="optDistrictNine" value="09">9</option>
<option id="optDistrictTen" value="10">10</option>
<option id="optDistrictEleven" value="11">11</option>
<option id="optDistrictTwelve" value="12">12</option>
</select>
Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:
//SPN
spnDDL.combobox({
select: function (event, ui) {
var spnVal = spnDDL.val();
//fire search event
$('#project-locationSearch-pid-input').val('');
$('#project-locationSearch-pid-input').prop('disabled', true);
pidDDL.empty(); //empty the pid list
}
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();
//PID
pidDDL.combobox({
select: function (event, ui) {
var pidVal = pidDDL.val();
//fire search event
$('#project-locationSearch-spn-input').val('');
$('#project-locationSearch-spn-input').prop('disabled', true);
spnDDL.empty(); //empty the spn list
}
});
Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.
Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)
The only other thing to note, much in addition to the post, is:
/*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked. Thus, it's created at that point in time
and its value must be picked fresh. Can't be put into a var and re-used
like the drop down list part of the UI control. So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL); But you can't
do this with the input part of the control. Winded explanation, yes. That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :)
*/
//district
$('#project-locationSearch-dist').combobox({
select: function (event, ui) {
//enable spn and pid drop downs
$('#project-locationSearch-pid-input').prop('disabled', false);
$('#project-locationSearch-spn-input').prop('disabled', false);
//clear them of old values
pidDDL.empty();
spnDDL.empty();
//get new values
GetSPNsByDistrict(districtDDL.val());
GetPIDsByDistrict(districtDDL.val());
}
});
All shared because it took too long to learn these things on the fly. Hope this is helpful.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
$('select#myselect option[value="ab"]')
either can be used to get the selected option value
$('#dropdownID').on('change', function () {
var dropdownselected=$("#dropdownID option:selected").val();
});
or
$('#dropdownID').on('change', function () {
var dropdownselected=this.selectedOptions[0].value;
});

Categories

Resources