Cant get Select Box to update dynamically with angular.js - javascript
I am currently learning angularJS and so far so good, but I'm having a problem that I cant seem to figure out.
I have 2 select boxes, one with top level categories in it, and a second one for sub-categories which is supposed to dynamically update when a change is made to the first select.
The first select box is populating fine, but despite the values being set for the second binding array by the event function I developed, the view never updates the second select box with the new values. I'm not sure what I'm doing wrong, and have tried a bunch of things but with no luck.
Here is what I've got:
var themebucketApp = angular.module('themebucketApp',[]);
//category list controller
themebucketApp.controller('CategoriesOptions',function($scope) {
$scope.thememap = {"wordpress":[{"category":"Activism"},{"category":"Art"},{"category":"Blog \/ Magazine"},{"category":"BuddyPress"},{"category":"Business"},{"category":"Cart66"},{"category":"Charity"},{"category":"Children"},{"category":"Churches"},{"category":"Computer"},{"category":"Corporate"},{"category":"Creative"},{"category":"eCommerce"},{"category":"Entertainment"},{"category":"Environmental"},{"category":"Events"},{"category":"Experimental"},{"category":"Fashion"},{"category":"Film & TV"},{"category":"Food"},{"category":"Government"},{"category":"Health & Beauty"},{"category":"Hosting"},{"category":"Jigoshop"},{"category":"Marketing"},{"category":"Miscellaneous"},{"category":"Mobile"},{"category":"Music and Bands"},{"category":"News \/ Editorial"},{"category":"Nightlife"},{"category":"Nonprofit"},{"category":"Personal"},{"category":"Photography"},{"category":"Political"},{"category":"Portfolio"},{"category":"Restaurants & Cafes"},{"category":"Retail"},{"category":"Shopping"},{"category":"Software"},{"category":"Technology"},{"category":"Travel"},{"category":"Wedding"},{"category":"WooCommerce"},{"category":"WordPress"},{"category":"WP e-Commerce"}],"magento":[{"category":"Entertainment"},{"category":"Fashion"},{"category":"Health & Beauty"},{"category":"Magento"},{"category":"Miscellaneous"},{"category":"Shopping"},{"category":"Technology"}],"designs":[{"category":"404 Pages"},{"category":"Activism"},{"category":"Admin Templates"},{"category":"Art"},{"category":"Business"},{"category":"Charity"},{"category":"Children"},{"category":"Churches"},{"category":"Computer"},{"category":"Corporate"},{"category":"Creative"},{"category":"Electronics"},{"category":"Entertainment"},{"category":"Environmental"},{"category":"Events"},{"category":"Experimental"},{"category":"Fashion"},{"category":"Film & TV"},{"category":"Food"},{"category":"Government"},{"category":"Health & Beauty"},{"category":"Hosting"},{"category":"Marketing"},{"category":"Miscellaneous"},{"category":"Mobile"},{"category":"Music and Bands"},{"category":"Nightlife"},{"category":"Nonprofit"},{"category":"Personal"},{"category":"Photo Gallery"},{"category":"Photography"},{"category":"Political"},{"category":"Portfolio"},{"category":"Restaurants & Cafes"},{"category":"Resume \/ CV"},{"category":"Retail"},{"category":"Shopping"},{"category":"Site Templates"},{"category":"Social Media Home"},{"category":"Software"},{"category":"Specialty Pages"},{"category":"Technology"},{"category":"Travel"},{"category":"Under Construction"},{"category":"Virtual Business Card"},{"category":"Wedding"}],"opencart":[{"category":"Entertainment"},{"category":"Fashion"},{"category":"Miscellaneous"},{"category":"OpenCart"},{"category":"Shopping"},{"category":"Technology"}]};
$scope.categories = [{'name' : 'WordPress', 'value' : 'wordpress'},{'name' : 'Magento', 'value' : 'magento'},{'name' : 'OpenCart', 'value' : 'opencart'},{'name' : 'Designs', 'value' : 'designs'}];
$scope.subcategories = [];
$scope.loadSubcategories = function(){
$scope.subcategories = $scope.thememap[$('#theme-type').val()];
};
});
...
<div class="navbar-text pull-right" style="margin-top:10px;">
<select id="theme-type" name="themetype" ng-controller="CategoriesOptions" ng-click="loadSubcategories();">
<option value="">Theme Type</option>
<option ng-repeat='category in categories' value="{{category.value}}">{{category.name}}</option>
</select>
<select id="theme-cat" name="themecat" ng-controller='CategoriesOptions'>
<option value="All">All</option>
<option ng-repeat='subcategory in subcategories' value='{{subcategory.category}}'>{{subcategory.category}}</option>
</select>
</div>
Can anyone show me what I'm doing wrong or what I'm missing?
There are several issues:
One: ng-controller="CategoriesOptions" should be declared only once and not one per control Like this:
<div class="navbar-text pull-right" style="margin-top:10px;" ng-controller="CategoriesOptions">
<select id="theme-type" name="themetype" ng-click="loadSubcategories();">
<option value="">Theme Type</option>
<option ng-repeat='category in categories' value="{{category.value}}">{{category.name}}</option>
</select>
<select id="theme-cat" name="themecat" >
<option value="All">All</option>
<option ng-repeat='subcategory in subcategories' value='{{subcategory.category}}'>{{subcategory.category}}</option>
</select>
Two for selects it better to use ng-options and ng-model:
http://docs.angularjs.org/api/ng.directive:select
About:
ng-model="{string}"
It is what associates the selected value of the control with your model.
About:
[ng-options="{comprehension_expression}"]
it works something like this:
<select ng-model="mySelectedValue" ng-options="c.name for c in categories"></select>
Related
Can Select options have Multiple Values?
I'm wondering if it's possible to have code where the Select option has 2 different value (which effect 2 different things) Basically, I'm trying to create an option where depending on the select choice, it changes the price and also changes the link that pressing the button will go to. I found this code on one of the posts here and it works perfectly, but I'm looking to add a Price in between the select menu and the button which is also effected by the select choice. Eg. 1 Year Only - $50 [Button links to correct purchase link] Subscription (Billed Annually) - $45/pa [Button links to correct purchase link] Sorry if i'm not explaining it very well. <select id="menu"> <option selected="selected" disabled="">Please choose an option</option> <option value="https://checkout-1-year">1 Year</option> <option value="https://checkout-subscription">Subscription (Billed Annually)</option> </select> <input type="button" id="goBtn" value="Purchase"> <script type="text/javascript"> var goBtn = document.getElementById("goBtn"); var menu = document.getElementById("menu"); goBtn.onclick = function() { window.location = menu.value; } </script>
They can't have two values, but what you can do is set the value and a data- attribute, which can store any string you like and then be retrieved using the data-* Attribute API. Here's an example: const list = document.getElementById("menu"); console.log(list.options[1].value, list.options[1].dataset.value); console.log(list.options[2].value, list.options[2].dataset.value); <select id="menu"> <option selected="selected" disabled="">Please choose an option</option> <option value="https://checkout-1-year" data-value="something">1 Year</option> <option value="https://checkout-subscription" data-value="something else">Subscription (Billed Annually)</option> </select>
Dynamically suffix a "selected" value from another list to previous "selected" list without reloading
Please see this image before reading The requirement is to dynamically alter a multi-select list, and add a suffix to the selected options. These "Suffix Values" are selected options from another individual select lists. I am saving these selections in my Session Variables, in an ordered manner P94_DYNAMIC_ML ==> "Habib" : "Aiman" P94_DYNAMIC_SL ==> "FAST 1" : "AL SAFEER 1" Expecting this could be done at client side itself. PS: I work on Databases,SQL & PLSQL mainly. Had a recent chance to work on Web Development. So very naive in Javascript & jquery, and unable to write any appropriate code in my HTML. Seeking help here, so that I can get an idea where to at-least begin with. Thereafter, I will do my best
Here is something : $("#x1-suffix").on("change", function () { $("#x1").text("x1 - " + $(this).val()); }); $("#x2-suffix").on("change", function () { $("#x2").text("x2 - " + $(this).val()); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li id="x1">x1</li> <li id="x2">x2</li> </ul> <div> <label for="x1-suffix">x1 suffix : </label> <select name="x1_suffix" id="x1-suffix"> <option value="empty">pick one</option> <option value="s1">s1</option> <option value="s2">s2</option> <option value="s3">s3</option> </select> </div> <div> <label for="x2-suffix">x2 suffix : </label> <select name="x2_suffix" id="x2-suffix"> <option value="empty">pick one</option> <option value="s1">s1</option> <option value="s2">s2</option> <option value="s3">s3</option> </select> </div>
Select option from selectbox
How can I select an option with javascript (/console in google chrome)? This is a part of the html code: <nobr> Element<br> <span class="absatz"> <br> </span> <select name="element" class="selectbox" style="width:114" size="12" onchange="doDisplayTimetable(NavBar, topDir);"> <option value="0">- All -</option> <option value="1">A</option> <option value="2">B</option> <option value="3">X</option> <option value="4">C</option> <option value="5">D</option> <option value="6">E</option> <option value="7">F</option> <option value="8">G</option> <option value="9">H</option> <option value="10">I</option> <option value="11">J</option> <option value="12">K</option> <option value="13">L</option> <option value="14">M</option> <option value="15">N</option> <option value="16">O</option> <option value="17">P</option> <option value="18">Q</option> <option value="19">R</option> </select> </nobr> Or http://pastebin.com/JSaKg4HB I already tried this: document.getElementsByName("element")[0].value = 1; But it gives me this error: Uncaught TypeError: Cannot set property 'value' of undefined at :2:48 at Object.InjectedScript._evaluateOn (:875:140) at Object.InjectedScript._evaluateAndWrap (:808:34) at Object.InjectedScript.evaluate (:664:21) EDIT: I I tried it but it don't works on for the full website. Maybe because there is another html tag inside the first html tag(if I download the website, there is another html file called welcome.html where the selectbox is.) I thinks it's in an iFrame, because chrome gives me the Option "show Frame". EDIT 2: I can access the frame where the selectbox is but I still won't find the selectbox. Here is the code of the frame(not the full code): pastebin.com/iVUeDbYV
Try this: document.querySelectorAll('[name="element"]')[0].value; Although it is very weird that getElementsByName is not working for you. Are you sure the element is in the same document, and not in an iFrame?
The simple answer: document.getElementById("select_element").selectedIndex = "option index"; Where option index is the index of the option in the dropdown that you'd like to activate. You can get the index of an option by using this: var selected = document.querySelector( '#'+div+' > option[value="'+val+'"]' ); Where div is the ID of the <select> tag. how this helps!
This will do what you want. document.querySelector('[name="element"]').value = 4 // The value you want to select and this will retrieve the value var value = document.querySelector('[name="element"]').value; // 4 this explains what's going on var option = document.querySelector('[name="element"]');//option element option.value; // 4 option.selectedIndex; // 4 option.selectedOptions; // [<option value="4">C</option>] option.selectedOptions[0].innerText; // C option.selectedOptions[0].value; // 4 Remember that selectedOptions is an array because more than one option may be selected, in those cases, you will have to loop through the array to get each value. As per Hanlet EscaƱo's comment, make sure your code is set to execute after the DOM has loaded. window.onload = function() { document.querySelector('[name="element"]').value = 0; // sets a default value }
Angular ng-option custom filter multiple dropdowns
I have a project requiring that I build an angular menu with multiple drop down filters. As the end user selects one filter the other two filters update accordingly. I already learned the hard way not to use the ng-repeat with options and now for the life of me cannot figure out how to get my select fields in the view to reflect changes that will be caused by events in the view. Here is my html: <div class="large-8 columns" ng-controller="democontroller" > <label> Demographic <select ng-options = "x.demo as x.demo for x in groups | filteredDemo" ng-model = "demoValue"> <option value="">Please Select A Group</option> </select> </label> <label> Location <select ng-model = "locationValue" ng-options = "x.location as x.location for x in groups "> <option value="">Please Select A Location</option> </select> </label> <label> Days <select ng-model = "dayValue" ng-options = "x.days as x.days for x in groups " > <option value="">Please Select A Meeting Day</option> </select> </label> </div> <div class="large-8 columns"> <p> </p> </div> </div> and here is my current javascript: var app=angular.module('selectapp',[]); app.controller('democontroller',['$scope','$http',function($scope,$http){ $http.get("jsoninfo.php").success(function(response){$scope.groups=response;}); $scope.currentValues = ['1','0','0']; app.filter('filteredDemo', function(){ return function(e){ if(e == 1){ return e; } } }); }]); any help would be greatly appreciated.
I'll try to explain the howto with two levels (group and location). Adding levels should be obvious after that. ng-model value of the first select list will hold the selectedGroup ng-model value of the second select list will hold the selectedLocation In ng-options, We must select the full object, but we will diplay only the name. Thus we will have ng-options="group as group.name for group in groups". We select the full object because in the dependent dropdown, we will iterate over the nested collection, here selectedGroup.locations <label>Demographic <select ng-model="selectedGroup" ng-options="group as group.name for group in groups"> <option value="">Please Select A Group</option> </select> </label> <label>Location <select ng-model="selectedLocation" ng-options="location as location.name for location in selectedGroup.locations"> <option value="">Please Select A Location</option> </select> </label> Here is a demo fiddle I've made with dummy data.
Add/Removing Options with JQuery
I'd like to add and remove options from one drop down menu using JQuery given a selected option in another. HTML: <form action='quickLook.py' method = 'post'> First DropDown Menu Specify Channel: <select id='bolometer'> <option selected id='Dual' value = 'Dual' >Dual <option id='Top' value = 'Top' >Top <option id='Bottom' value = 'Bottom' >Bottom </select> Second DropDown Menu <br>Specify Data to Display: <select id='target'> <option selected id='Spectrum' value = 'Spectrum'>Spectrum <option id='Interferogram' value = 'Interferogram'>Interferogram <option id='SNR' value = 'SNR'>SNR <option id='Diff_Band' value = 'Diff_Band'> Diff_Band </select> <input type='submit' value= 'Query Images'> </form> I'd like to do something like this is JQuery: $("#Dual").click(function() { $("#target").append("#Diff_Band"); $("#target").remove("#Interferogram"); $("#target").remove("#SNR"); }); $("#Top").click(function() { $("#target").append("#Interferogram"); $("#target").append("#SNR"); $("#Diff_Band").remove(); }); I want to append or remove the already written html. What is the best way to do this? Thank you for your time!
This is a similar problem I've encountered before working with Safari. A solution is to use .detach() instead of remove() as it keeps all jQuery data associated with the removed elements. Check this jsfiddle: http://jsfiddle.net/Ueu62/