Angular JS Bind radio buttons to variable to use as a flip - html

What I am trying to do is use the radio button value chosen by the user to update the variable in the controller. That variable depending on the value will do an http call for the specific answer.
Example:
Chose cars -> variable temp = cards -> http calls cars method
Chose house -> variable temp = house -> http calls house method
In the view I have something like this:
<input id ="inputOne" type="radio" ng-value="cars" ng-model="controller.selection">
<input id ="inputTwo" type="radio" ng-value="house" ng-model="controller.selection">
<input id="mySubmit" type="button" ng-click="controller.selectionChosen">
In my Controller I have something like this:
var vm=this;
vm.selection;
function selectionChosen(){
alert(vm.selection);
// If selection == cars do this
// If selection == house do this
}
You might wonder why it is 'controllerName.variableName', I am following best practices (found here) `so the way it is set up requires controller name then the variable.
My problem I am having is for some reason the value is not binding. When the alert happens it alerts 'undefined' and I am not sure why. I have looked at many tutorials and examples online and this looks like it should work.
Update
So I am pretty sure it is binding or at least trying to. When I set the variable initialized to "test" the first alert shows "test". After clicking a button then it goes to 'undefined".

The problem is coming from the ng-value="cars"
since you are using Mycontroler as controller it should be ng-value='controller.cars' if you declare cars in your controller
If you just want to use cars as a string in ng-value without declare it, you need to add ' ', angular will undestand it like a string instead of a variable
ng-value="'cars'"

Related

How do I build a simple HTML form to construct a link from two form fields?

At work, one of the systems I use outputs voyage schedules. The URL for each voyage is constructed as the form address followed by ?voyageCode= followed by the voyage number, which is a two-letter route prefix and a three-digit voyage number.
Rather than use the standard form, which has a whole bunch of fields I never need to use, I want to build a simple page where I can just select the route and enter a voyage number.
In practical terms, I'm trying to build a form with the following:
A drop-down menu or set of radio buttons to select the two-letter route code;
A text field to enter the three-digit route code;
A button or link to combine those inputs into a link in the format [LINK]?voyageCode=[ROUTE CODE][VOYAGE NUMBER]
My HTML knowledge is pretty outdated, and I've never worked much with forms. Can anyone advise on how I can construct this?
Why don't you use a select tag for the dropdown and a classic input text for the route coude ?
Then for the link part, you should capture the click event on your button through onClick and then call a small function that'll basically do that :
function concatRouteCode(){
var select= document.getElementById("routeCodeLetters");
var routeCodeLetters = select.options[select.selectedIndex].value;
var routeCodeNumber = document.getElementById('routeCode').value;
return routeCodeLettres+routeCodeNumber;
}
If you really want to combine the codes into a single query parameter, you'll have to use Javascript to fetch the values of the two fields and change the location. You don't need Javascript if you put the values into separate parameters, as in ?routeCode=xx&voyageNumber=123. In that case you would just give the select element the attribute name=routeCode and the input field the attribute name=voyageNumber.
In case you want to go with the first approach, you'd have something like
document.getElementById("idOfSubmitButton").addEventListener("load", function() {
const routeCode = document.getElementById("idOfSelectElement").value;
const voyageNumber = document.getElementById("idOfInputField").value;
location.href = "base URL here" + "?voyageCode=" + routeCode + voyageNumber;
});

Getting a string instead of expected number from Angular template and input native element's value

I have an event that fires on key up like this.
value: number;
onKeyUp(event: KeyboardEvent) {
this.value = this.input.nativeElement.value;
console.log("typo", typeof (this.value));
}
For some reason, the value stored is a string not a number. I've tried using syntax like this to no avail.
this.value = this.input.nativeElement.value as number;
Instead of that, I had to use the JS hack from the past, i.e. the unary plus operator like so.
this.value = +this.input.nativeElement.value;
Is there a more proper approach to make sure that my input provides a number? Or am I already doing it kinda right?
The markup provides no useful info, probably, but just in case, here it is.
<input #input
value="{{value}}"
(keyup)="onKeyUp($event)"
(keydown.Tab)="onKeyUp($event)">
It is written on the spec that value will always be stored as string. So even if you set the input type as number, it only update the user interface. But the value is still the same in string type.
I don't extract the data the same way with you. Not sure if you have any reason for doing so. I always use the ngModel directive.
Basically it is the two way binding, if you update the data model, it will update the UI and the other way around. So that you don't have to get the value manually through the ElementRef as you did on the question. It is done automatically for you.
app.component.html
<input type="number" [(ngModel)]="inputVal" (keyup)="onKeyUp($event)">
app.component.ts
onKeyUp(event: KeyboardEvent) {
console.log(this.inputVal);
}
Noted the type="number" on the HTML code. When you set it like that, the inputVal will be return as a number. I didn't really check the source code but probably Angular will parse it automatically somehow.
If you don't put it, the value will still be keep as a string.
I prepare the example for it. Please check https://stackblitz.com/edit/angular-ngmodel-number
You can just type into the input and see the value and the type.

Angular - Setting value in input text box in another component

I am trying to set the value in an HTML input text box which is a part of ComponentA from the typescript code which is a part of ComponentB.
Taking a clue from this SO i tried doing:
(<HTMLInputElement>document.getElementById("name")).value = response.name;
But this is not working. Is there anything else i need to take care of?
EDIT: The element with Id "name" is in ComponentA and the above code that is trying to manipulate that element is in ComponentB
If you are trying to set the value of component1's textfield from the compoenent2 then you must have to use of ngModel i.e two way data binding. by providing component2 in the providers list you are able to access all the functions and variables of that component, then you can easily set your value. like this
suppose this is your component 2's value property
name:string = 'Pardeep Jain';
than you can access this in component like this-
<input type="text" [(ngModel)]='name'>
....
constructor(private delete1: Delete){
this.name = this.delete1.name;
}
Working Example
Also
(<HTMLInputElement>document.getElementById("name")).value = response.name;
is used to set the value of current template's field with id named as **name**
This is one of the cases when user interaction on one component ComponentA triggers an update on another component ComponentB.
This article describes multiple approaches, with example code, on how to pass information between components.
My personal favorite is the third approach mentioned in that article in which one of the component (say ComponentA) "listen" for update it is concerned about from any component (say ComponentB) via a service in between them, resulting in a loosely coupled components.
For more approaches here is another link.

django localflavor USStateSelect() inital value

I'm trying to use the django localflavor widget USStateSelect() in a form, but I want the widget to have Nebraska selected by default. The Widget only accepts an attrs arg, so I'm trying to understand what attributes I have to set to get the desired result. Here's what I've got in my forms.py:
state = forms.CharField(widget=USStateSelect(attrs={'value':'NE'}))
This is the docs for the HTML select element: http://www.w3.org/html/wg/drafts/html/CR/forms.html#the-select-element
This is the docs for localflavor: https://django-localflavor.readthedocs.org/en/latest/_modules/localflavor/us/forms/
<option value="NE" selected>Nebraska</option>
This is what I need to have in my html, but I can't figure out what the attrs dict needs to contain to achieve this result. I've tried adding 'selected':'selected' and 'class':'selected' to the dict, but that's not doing it.
I've seen a number of people asking how to add an empty option, but no one seems to want to make it default to a specific state. Any ideas are welcome.
Thanks,
Anthony
You can set the initial value like so:
state = forms.CharField(widget=USStateSelect(), initial='NE')
or you can set it when you instantiate the form:
form = ExampleForm(initial={'state': 'NE'})

Play-framework -What kind of value can be transmitted with a checkbox html?

I have a form where the user can choose different articles with a checkbox. I would like to transmit the article numbers of the checked articles, like so:
<br><input type="checkbox" id="articleNr" name="articleNr" value="${item.articleNr}" />${item.title}
My method in play returns me 0 for the article no, even though articles were checked:
public static void addToX(double boardNr, double articleNr1){
System.out.println("Article Nr: " + articleNr1);
Is what I'm trying to do even possible with a checkbox?
Put a debug point and check value of request.params
See if the variable is there or not.
For checkboxes generally, if it is not checked, nothing gets submitted. Not sure how play handles it. It is is checked, you should be able to see a value in the variable.
nothing is send if you check nothing, becareful by default when you checked the helper checkbox for play it is a boolean, if you use a standart input chekcbox nothing will be in the map of the request params :
Map< String, String[] > map = request().body().asFormUrlEncoded();
String[] checkedValue = map.get( "articleNr" );
it will be null if nothing is checked