I'm trying to get the input from some textboxes, but for some reason in my first textbox i'm getting the input without any problem. But on the second one i'm not getting any value from it even if i type something inside the textbox.
My html elements (the name input tag works):
<div class="form-group">
<label class="control-label">School name</label>
<input placeholder="Name" type="email" class="form-control" name="name" [(ngModel)]="name"
required>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">School Address *</label>
<input placeholder="Address" type="email" class="form-control" name="sh_address" [(ngModel)]="sh_address"
required>
</div>
My code (this is called when the form is submitted):
public name: string = "";
public sh_address: string = "";
validateNewSchoolData() {
console.log(this.sh_address)
}
I tried your code in a new Angular Version 12 project. Your code works. Do you have imported the FormsModule?
imports: [
FormsModule,
...
],
Can you define the angular version you use or create a running code snippet to test?
I checked the two values by a button onClick event and console.log:
buttonClick() {
console.log(this.name, this.sh_address);
}
https://stackblitz.com/edit/angular-ivy-v51ahs
Greetings!
Related
I'm new with Javascript and I'm learning by myself. I have a problem with a form on my page. I just want to test with a simple javascript code that I can manipulate my input "type=submit" by adding a function to it to console.log a string when the form is submitted (I watched it on a video and I wanted to do it by myself).
Here is my code:
(function() {
"use strict";
document.getElementById('enviar').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
and this is my HTML code:
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
The problem that I'm having here is that is not working at all.. my ID element is selected properly but I don't know what is wrong with my code. I created a variable and console my ID selected to see if I was getting the right element from the DOM and I'm getting in the console the right input element. please if someone knows why is not working.
plus: On my text input field I have a regular expression but I'm not getting the output I want.. the goal is that the user has to write at least two names (First and Last), so when they write just one it will be incorrect.. the problem that I'm having with this regular expression if when someone writes more than two names (First, Middle and Last) I DON'T want to make that an incorrect answer because technically is correct. So I need to make a better regular expression to get that result (when the user writes two or more names, not just two) but I don't know too much about Regular Expressions.
You are getting the element with the id enviar which is the submit button element. You need to be querying based on the form's element id which is escribenos. Try running the snippet below and you can see that it has the expected outcome.
(function() {
"use strict";
document.getElementById('escribenos').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
I'm facing the problem to replicate input fields onclick of a button
*I have few input fields and i can fill the data in that
*After filling the input fields i have a different data set to add so i need same fields.
*If i press button (addMore) the fields should replicate and it should allow me to add one more set of data.
*There should be one button(remove) that will help me to remonessessaryve those replicated fields if its not necessary.
I have tried this in angular ..and I'm sharing my sample code and plunker plz help me out
template.ts
<div class="card">
<input type="text" id="name" value="" class="form-control">
<label for="form1">Name</label>
<input type="text" id="mobile" value="" class="form-control">
<label for="form1">Mobile</label>
</div>
<button type="button" title="Add"class="btn btn-sm"
(click)="addMore">Add</button>
test.component.ts
export class App {
addMore() {
//function to replicate the form input fields
}
plunker link :- http://plnkr.co/edit/GCCnoMkLynpELwaYX11m?p=preview
You're looking for generating dynamic inputs using ngFor
You can initially create an array with initial value as follows,
inputelements = [{name: '',mobile:''}];
on click of addmore button you can push more elements and those will be rendered using ngFor
Template code will be,
<div class="card" *ngFor="let word of inputelements; let in=index" class="col-sm-3">
<div class="form-group">
<label for="form1">Name</label>
<input type="text" [(ngModel)]="inputelements[in].name" class="form-control" required>
<label for="form1">Mobile</label>
<input type="text" [(ngModel)]="inputelements[in].mobile" class="form-control" required>
</div>
</div>
<br>
<button type="button" title="Add"class="btn btn-sm pull-right"
(click)="addMore()">Add</button>
WORKING DEMO
Keep the track of the inputs with an array and add/remove with js :
inputs = [];
add() {
this.inputs.splice(0,0,this.inputs.length+1);
}
DEMO
I have a template form, which I wrote from guides and they don't really work though.
I have several of models:
export class User {
constructor(public userId?: UserId,
public firstName?: String,
public lastName?: String,
public address?: Address) {
}
}
export class Address {
constructor(
public street?: String,
public city?: String,
public zipCode?: String) {
}
}
I have component:
Component({
templateUrl: 'user.html'
})
export class MyComponent implements OnInit, OnDestroy{
user: User;
userForm: NgForm;
ngOnInit(): void {
}
And page itself:
<form novalidate #userForm="ngForm">
<div class="form-group">
<input required minlength="4" type="text"
id="firstName"
[(ngModel)]="user.firstName" name="firstName">
<small *ngIf="!firstName.valid">Not valid!</small>
</div>
<div class="form-group">
<input required ng-minlength="4" type="text"
id="lastName"
[(ngModel)]="user.lastName" name="lastName">
</div>
<div ngModelGroup="user.address">
<div class="form-group">
<input required ng-minlength="4"
type="text"
id="address-house"
[(ngModel)]="user.address.address1" name="address.address1">
</div>
<div class="form-group">
<div class="form-group">
<input required ng-minlength="4"
type="text"
id="zipCode"
[(ngModel)]="user.address.zipCode" name="address.zipCode">
</div>
<div>
<input required ng-minlength="4"
type="text"
lass="form-control input-lg"
id="city"
[(ngModel)]="user.address.city" name="address.city">
</div>
</div>
</div>
<button type="button" (click)="checkAndProceed()">Continue</button>
</div>
</form>
The only thing I want to do is to add validation - that's all. None of the guides helped. Can we do in-html validation or ts validation? It would be nice to call validation when clicking 'Continue' button and making it valid if it is so.
In this case of validation I additionally get console error:
Cannot read property 'valid' of undefined
There are lots of attributes on input elements. We have name, Id, and template reference variable. Your code is missing the template reference variable. It is the template reference variable that holds onto the reference to the element and has the valid, dirty, and other flags associated with it.
For example, change your code to include a template reference variable like this:
<div class="form-group">
<input required minlength="4" type="text"
id="firstName"
[(ngModel)]="user.firstName" name="firstName"
#firstNameVar="ngModel">
<small *ngIf="!firstNameVar.valid">Not valid!</small>
</div>
Notice the #firstNameVar. That is the template reference variable. It can be named the same thing as your Id and name attributes. I just named it something different so it could be readily distinguished between the other two attributes.
Notice also that the *ngIf is then changed to use firstNameVar.valid
For more information on template reference variables, see this: https://angular.io/guide/template-syntax#ref-vars
I am getting customer for given id,Customer details are name, email and type of customer {0,1}. For 0, customer will be Regular and 1 will Temporary.
I am able to show details of customer on form but but able to select the type of customer. My select options are showing {'regular', 'temporary'}, but not select any option value.
For example
customer1={'name':'john', 'email':'john#gmail.com', 'customer_type':0}
Form is able to show name and email but not selecting 'regular' options
Controller
$scope.customers_type=['regular','temporary'];
//I will get details of customer
$scope.customer=getCustomer($scope.id);
if($scope.customer.customer_type ==0)
$scope.customer.type=$scope.customers_type[0]
else
$scope.customer.type=$scope.customers_type[1]
HTML
<div>
<label for="Name">Name </label>
<input ng-model='customer.name' name="Name" type="text">
</div>
<div>
<label for="email">Email </label>
<input ng-model='customer.email' name="email" type="text">
</div>
<div>
<label for="enterprise">Type of type of Customer </label>
<select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
</select>
</div>
Code is working fine without any error for angularjs 1.2.23
Just have replaced getCustomer method to object.
If it is not working then Check customer object using breakpoint and check whether it's proper or not and also check which version of angularjs you are using.
angular.module("myApp", []).controller('MyContrl', function($scope) {
$scope.customers_type = ['regular', 'temporary'];
//I will get details of customer
$scope.customer = {
'name': 'john',
'email': 'john#gmail.com',
'customer_type': 0
};
if ($scope.customer.customer_type === 0) {
$scope.customer.type = $scope.customers_type[0]
} else {
$scope.customer.type = $scope.customers_type[1]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyContrl">
<div>
<label for="Name">Name</label>
<input ng-model='customer.name' name="Name" type="text">
</div>
<div>
<label for="email">Email</label>
<input ng-model='customer.email' name="email" type="text">
</div>
<div>
<label for="enterprise">Type of type of Customer</label>
<select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
</select>
</div>
</div>
I think you need to specify ng-selected and set it to your current customer type.
If you don't specify ng-selected you'll end up with 3 options: '', 'regular', 'temporary'
Have a basic registration form, trying to validate it.
I am using form serializeArray() method and loop trough the form and find if the values are null.
HTML CODE
<form name="reg" id="regform">
<fieldset>
<label for="firstname">First Name</label>
<input type="text" name="firstname" value="First Name"/>
</fieldset>
<fieldset>
<label for="lastname">Last name</label>
<input type="text" name="lastname" value="Last Name"/>
</fieldset>
<fieldset>
<label for="date">Age</label>
<input type="text" name="age"/>
</fieldset>
</form>
JQUERY Code
var formElements = $("#regform").serializeArray();
$(formElements).each(function(x)
{
if(formElements[x]["value"] == "")
{
$("[name='" + formElements[x]['name'] +"']").addClass('error');
}
});
From the above code i am able to add the class ".error" when the value is null.
Now i want the code to check the text fields values are not the default values like in my case the default values are "First Name" "Last Name"..
So i want to check even for the default values and add error class to respective element and even focus back the cursor on the first null value text field
Thanks in advance
I highly suggest using http://docs.jquery.com/Plugins/Validation. You can test for various things, such as blank values, and even extend it to detect default values.
For example:
$.validator.addMethod("name", function(value) {
return value != "First Name";
}, 'Please enter your first name.');
Alternatively you can just test against a default value with jQuery's data() function:
Working Demo: http://jsfiddle.net/WpQ2n/2/
var input = $(".name"),
defaultval = input.data("default", input.val());
// Can't submit forms in jsfid, so i just used a click event.
// Change to .submit()
$("input[type='submit']").on("click",function(e){
if(input.val()== input.data("default")){
input.addClass("error");
}
else{
// Yay it validated...
input.removeClass("error");
}
e.preventDefault();
});