How to store radio button value as variable - javascript

I tried to make a multilanguage site with html and javascript.
For selecting the language I created three radio boxes (values: en, de, fr).
The words which should be displayed are stored in a javascript object.
Here is the code:
$('#lang-setting').on('change', function () {
var lang = $('input:checked', '#lang-setting').val();
console.log(lang);
alert(lang);
$('#latitude-n').html(lang.latitude);
$('#longitude-n').html(lang.longitude);
$('#accuracy-n').html(lang.accuracy);
$('#words-n').html(lang.words);
$('#map-n').html(lang.map);
$('#test').html(de.test);
});
alert(lang) and console.log give the right language every time I select a language.
But: the other words don't change. They do if I replace the 'lang' with f.e. 'de' (see last code line).

Your variable named lang is a string because you're setting it to the value of the radio input, so lang.latitude, lang.longitude, lang.accuracy, lang.words, and lang.map are all undefined.
I'm assuming you have global variables such as de set since you said de.test works.
It would probably be easiest to put all of those languages into a single object that you can then reference by the key, or the value of the radio input. I've also added a variable that allows you to select the default language and the function that will be performing the actual html change.
var translate = {
default: 'en',
en: {
latitude: 'latitude',
longitude: 'longitude',
accuracy: 'accuracy',
words: 'words',
map: 'map',
},
de: {
latitude: '',
longitude: '',
accuracy: '',
words: '',
map: '',
},
fr: {
latitude: '',
longitude: '',
accuracy: '',
words: '',
map: '',
},
changeText: function(lang) {
$('#latitude-n').html(translate[lang].latitude);
$('#longitude-n').html(translate[lang].longitude);
$('#accuracy-n').html(translate[lang].accuracy);
$('#words-n').html(translate[lang].words);
$('#map-n').html(translate[lang].map);
}
}
Since you didn't post the HTML of your three radio buttons, I'm going to instead give them name attributes instead of id's of with the value "lang-settings" because having duplicate id's is invalid HTML. Below is the minimal HTML for these radio buttons.
<input name="lang-setting" value="en" type="radio" />
<input name="lang-setting" value="de" type="radio" />
<input name="lang-setting" value="fr" type="radio" />
Then for your listener, I've switched it to listen for "clicks" instead of changing, because the values of the radio button isn't actually changing, they're staying as "en", "de", and "fr". I've also added the function call in document ready to run your default language selection on page load.
$('input[name="lang-setting"]').on('click', function(e){
var lang = $(this).val();
translate.changeText(lang);
});
$(document).ready(function(){
translate.changeText(translate.default);
});
Here's a working demo of it on JSFiddle

It doesn't work that way, you need brackets notation.
var words = {
de: {
lat: "Breitengrad",
lon: "Längengrad"
},
en: {
lat: "Latitude",
lon: "Longitude"
},
fr: {}
};
function changeLanguage() {
var lang = $('#lang-setting input:checked').val();
$('#latitude-n').html(words[lang].lat);
}
$('#lang-setting input').click(changeLanguage);
changeLanguage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lang-setting">
<input type="radio" value="en" name="lang" checked>En</option>
<input type="radio" value="de" name="lang">De</option>
<input type="radio" value="fr" name="lang">Fr</option>
</div>
<p>
<span id="latitude-n"></span>: <input />
</p>

Related

How to change the method within a class dynamically?

I want to change the method changeThis dynamically by replacing the method with the value of an radio element. So if I select event1, the method needs to be changed to Class.event1()
<input
type="radio"
class="radio-input"
id="1"
value="event1"
ng-model="$ctrl.eventType"
ng-change="$ctrl.updateEvent()" />
JS:
updateEvent() {
const getEvent = Class.changeThis({
title: 'Happy Time',
location: 'New York, NY',
description: 'Let\'s go!'
});
}
I tried:
const getEvent = Class + '.'+ this.eventType({
title: 'Happy Time',
location: 'New York, NY',
description: 'Let\'s go!'
});
}
but get the error eventType is not a function. When I change it to a function it still doesn't work.
You can access objects property (or method) dynamically like this:
myObj["my" + "property"]
So, in your case it would be:
Class[this.eventType]({ ... });

AngularJS: View is updated properly but not the model

I have a problem when implementing a nested list in Angular: the view gets updated properly but, on the other side, the code is not updated on change.
I think it will be much clearer with the code:
_this.categories = injections.map(function (category) {
return {
title: category.get('title'),
object: category,
criteria: category._criteria.map(function (oneCriteria) {
return {
object: oneCriteria,
type: oneCriteria.get("type"),
min: _this.range(oneCriteria.get("range")).min,
max: _this.range(oneCriteria.get("range")).max,
key: oneCriteria.get("key"),
value: _this.range(oneCriteria.get("range")).min,
defaultValue: _this.range(oneCriteria.get("range")).min,
selected: false
}
})
}
});
_this.category = _this.categories[0];
_this.job = {
title: '',
description: '',
salaryAmount: 0,
salaryTimeUnit: _this.salaryTimeUnits[0],
category: _this.category.object,
criteria: _this.category.criteria,
location: {latitude: 48.137004, longitude: 11.575928}
};
So and, very quick here is my HTML:
<div ng-repeat="category in controller.categories">
<input type="radio" name="group" ng-value="category.object.get('title')" id="{{category.object.get('title')}}"
ng-checked="controller.category == category" ng-click="controller.category = category">
{{category.title}}
</div>
<br>
Criteria:
<div ng-repeat="criterium in controller.category.criteria">
<div class="row vertical-align">
<div class="col-xs-9">
<span ng-click="criterium.selected = !criterium.selected"
ng-class="['list-group-item', {active:criterium.selected == true}]">{{criterium.key}}</span>
</div>
</div>
</div>
The problem is the following: the value are getting updated in the view (when you click on a radio button on the category, you see the corresponding criteria(s)). But the job is for one reason that I ignore not updated although it has the same reference as the HTML (a reference to this category.criteria).
Did I miss something?
controller.job.criteria is still just a reference to controller.categories[0]. Your code should successfully update controller.category to point at whichever category you clicked on, but that does not also update the reference in your job data structure.
What you want to do is make your ngClick event a bit more robust, i.e.:
<input type="radio" ng-click="controller.updateCategory(category)" />
and then in your js:
_this.updateCategory = function (category) {
_this.category = category;
_this.updateJob(category);
};
_this.updateJob = function (category) {
_this.job.category = category.object;
_this.job.criteria = category.criteria;
};
This will update the references in your job to match the new jazz.
I would, however, recommend leveraging ngModel and ngChange in your radios instead. Like:
<input type="radio" ng-model="controller.category" ng-value="category" ng-change="updateJob(category)" /> {{category.title}}

In AngularJS how to uncheck a radio button to make all objects become false

I have an array with many "contact" objects inside. Only one contact can be the primary contact (primary: true).
I also have a radio button to select which contact is the primary.
Q: How can I make one contact primary and deactivate all of the others (primary: false)? so only one object have the property (primary: true) and the rest false?
My example: http://plnkr.co/edit/Y3as4SXv2ZGQSF39W8O6?p=preview
.controller('ExampleController', ['$scope',
function($scope) {
$scope.addContList = [
{
email: "q#q.com",
jobTitle: "clerk",
name: "nico2",
phone: "1",
primary: true
},
{
email: "a#a.com",
jobTitle: "director",
name: "david",
phone: "1",
primary: false
}
];
$scope.$watch('addContList', function() {
console.log('changed', JSON.stringify($scope.addContList, null, 2))
}, true)
}
]);
Here is the view
<tr ng-repeat="contact in addContList">
<td>
<label class="radio-inline">
<input type="radio" value="" name="ui_cont" ng-model="contact.primary" ng-value="true">
</label>
</td>
<td>{{ contact.name }} value = {{contact.primary}} </td>
<td>Edit</td>
<td>Delete</td>
</tr>
You would want to add an ngChange event to your input and change all other inputs to false when one gets set to true. I have updated your Plnkr here: http://plnkr.co/edit/7gxI7if9nC7hAMQES1eu?p=preview
<input type="radio" value="" name="ui_cont" ng-change='changeOnPrimary(contact)' ng-model="contact.primary" ng-value="true">
Then in your controller:
$scope.changeOnPrimary = function(selectedContact) {
// iterate over your whole list
angular.forEach($scope.addContList, function(contact) {
// set primary to false for all contacts excepts selected
if (selectedContact.name !== contact.name) {
contact.primary = false;
}
});
}
Please note: the only reason I'm comparing the name field of the object is because there is no unique identifier to compare with. In real code, you would want to compare against an ID rather than a name field.
You can define a new scope property
$scope.primary = null
Then you can define a listener
$scope.$watch("primary", function(value) {
$scope.addContList.forEach(function(contact) {
contact.primary = angular.equals(value, contact);
})
})
and you can define a default value after defining the list
$scope.primary = $scope.addContList[0];
and in the html you change the input line in
<input type="radio" value="" name="ui_cont" ng-model="$parent.primary" ng-value="contact">
You need to use $parent.primary instead of primary, because ng-repeat defines a new child scope.
see http://plnkr.co/edit/5pvatBNwnrJhGzKhOIys?p=preview

AngularJS - Binding radio button selection to model inside ng-repeat

I have a data model persons which takes the following form:
personsInfo = {
name: Adam
dob: 31-FEB-1985
docs: [
{
docType: Drivers License,
number: 121212,
selected: false
id: 1
},
{
selected: true,
docType: None
},
{
docType: State ID,
number: 132345,
selected: false,
id: 2
}
]
}
In my markup I have defined the following to dynamically generate radio buttons.
<div ng-repeat="personDoc in personsInfo.docs">
<input type="radio" name="personDocs" ng-model="personDoc.selected" value=""/>
{{personDoc.docType}} <span ng-hide="personDoc.docType === 'None'">Number: {{personDoc.number}}</span>
</div>
I want to be able to check the documents which have selected as true on page load, and then depending on what the user selects save the selected flag in my personsInfo model.
My intent here is to send the personsInfo model back to another page.
If somebody could point me to a working fiddle it would be greatly appreciated!
Thanks!
You're almost there just missing the binding to show which document is selected. We'll add an object to the scope to represent the selected item, then bind the forms to that model.
JS
app.controller('...', function($scope) {
$scope.personInfo = { ... };
$scope.selectedDoc = {};
$scope.$watch('personInfo',function() {
$scope.selectedDoc = $scope.personInfo.docs[0];
});
});
HTML
<div ng-repeat='doc in personInfo.docs'>
<input type='radio' ng-model='selectedDoc' value='doc' /> {{doc.docType}}
</div>
<form>
<input type='text' ng-model='selectedDoc.number' />
...
</form>

KnockoutJs: Getting value from dropdownlist

I'm having hard time getting the selected value of dropdown list using Knockout JS
jsFiddle
HTML
<select id="l" data-bind="options: locations, value=selectedLocation"></select>
<select id="j" data-bind="options: jobTypes, value=selectedJobType"></select>
<button data-bind="click: myFunction"> Display </button>
Script
var viewModel = {
locations: ko.observableArray(['All Locations', 'Sydney', 'Melbourne', 'Brisbane', 'Darwin', 'Perth', 'Adelaide']),
selectedLocation: ko.observable(),
jobTypes: ko.observableArray(['All Vacancies', 'Administration', 'Engineering', 'Legal', 'Sales', 'Accounting']),
selectedJobType: ko.observable(),
myFunction: function() {
alert(selectedJobType + ' ' +selectedLocation );
}
};
// ... then later ...
//viewModel.availableCountries.push('China');
// Adds another option
ko.applyBindings(viewModel);
That should be
value:selectedLocation
and:
value:selectedJobType
in you bindings. Bindings use the same syntax as an object literal.
Also, in your alert, you need viewModel.selectedJobType(), because (a) it's a property of viewModel not of global and (b) it's an observable so you need to call it to get the value. Same for selectedLocation.
Here's a working fiddle

Categories

Resources