Angular form is undefined when submitting via ngSubmit - javascript

I have a form outlined in my app.component.html file as below, when I click the Send button to submit the form I get an error in my Javascript saying that the chatForm is undefined.
I've had a look at a few different tutorials and I can't seem to find why this function is not operating as I expect. What am I doing wrong?
Also when I'm submitting the form how do I get the value of the input that is present in my form? I have a name of message defined on the form, how can I use this variable?
app.component.html
<div class="container">
<h2>Message Form</h2>
<form (ngSubmit)="sendMessage(chatForm)" #chatForm="ngForm">
<div>
<label for="message">Message</label>
<input type="text" id="message" name="message" [(ngModel)]="message" required>
</div>
<button type="submit" id="sendmessage" [disabled]="!chatForm.valid">
Send
</button>
</form>
</div>
app.component.ts
public sendMessage(form): void {
console.log("Message sent: " + form.value);
}

You should get the data by using
form.value.message
My example look like this
<form (ngSubmit)="onSubmit(registerForm)" #registerForm="ngForm">
<div class="form-group">
<label for="UserName">Your email</label>
<input
type="text"
ngModel
class="form-control"
id="UserName"
name="UserName"
required
/>
Then in my component I can access to the form data like this
onSubmit(formValue: NgForm) {
const registerModel: AccountModel = {
UserName: formValue.value.UserName,
Password: formValue.value.Password
};

Related

I want to send input value to the other page in node.js

I want to send input value to the to the other page in node.js.I am working on a travel agency project.So i have a buy ticket page and the page that shows your ticket including your name,surname etc.
So i want to take client's name from my input and i want to send that to ticket page and the ticket will shown client's name.I have a js file which i included that both to buy ticket and ticket page.I wrote a function for test.The function is when you click the buy ticket button in the "buy ticket" page,it will do document.write("Hi there"); Like that:
<button onlcick="buy()">Buy</button>
Js:
function buy() {
document.write("Ticket bought");
}
It worked when i click the buy button in the "buy ticket" page it writes "Ticket Bought" in the "ticket" page.Now i want to send the input value which that input including client's name,and i want to show the name on the ticket.
My code
<form class="row g-3 needs-validation" style="margin-top: 50px;" action="/ticket" method="POST" novalidate>
<div class="col-md-6">
<label for="validationCustom01" class="form-label" style="color: white;">First name</label>
<input type="text" class="form-control" id="name" value="" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-6">
<label for="validationCustom01" class="form-label" style="color: white;">Last name</label>
<input type="text" class="form-control" id="surname" value="" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<button type="submit" onclick="buy">Buy</button>
</form>
Javascript:
var user_name,user_surname;
user_name = document.getElementById("name")
user_surname = document.getElementById("surname");
function buy(){
var surnameValue,nameValue;
nameValue = user_name.value;
surnameValue = user_surname.value;
document.write(nameValue + surnameValue);
}
I want that the code will write the user's name and surname but i get an error:
Uncaught TypeError: Cannot read property 'value' of null
How can i solve that?
P.S:I have a controller.js and router.js file which control the localhost path.

Simple use of the 'required' attribute but also validate the form (to exclude '#')

I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.

how to use model binder to post data from a form + value of a span to data base

Good time.
I'm new in Asp.net-MVC .
I have a form which it gets data from user and there is a span in this page which I want to post data of inputs and value of span to my data base.
I wanted to use model binder but I don't know how to name spans same as my model.
here is my action :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,TourId,FirstName,LastName,Email,Phone,Comment,FrequentTraveler,TravelersCount,Date,ContactTimePreference,Country,Archived")] Request request)
{
if (ModelState.IsValid)
{
db.Requests.Add(request);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(request);
}
span is getting value from JavaScript
<span class="col-md-5" id="selecteddate"></span>
and here is my form but I write just one of the inputs here for Shorthand. :
<form role="form" method="post" action="/Tour">
#Html.AntiForgeryToken()
<div class="form-group">
<label for="FName">First Name:</label>
<input type="text" name="FirstName" class="form-control" id="FName" placeholder="Enter FirstName" />
</div>
</form>
I want to post value of span id="selecteddate" to data base in column named Date
appreciate if any one could tell me how it could be possible or if you have any better way as suggestion?
One solution for this is, add a hidden html input to your <from>. When you do your submit, you write its value as a copy from your span using javascript.
<form role="form" method="post" action="/Tour" onsubmit="prepare()">
#Html.AntiForgeryToken()
<div class="form-group">
<label for="FName">First Name:</label>
<input type="text" name="FirstName" class="form-control" id="FName" placeholder="Enter FirstName" />
</div>
<input type="hidden" name="Date" />
</form>
#section Scripts {
<script type="text/javascript">
function prepare() {
document.getElementsByName("Date")[0].value = document.getElementById("selecteddate").innerHtml;
}
</script>
}

passing data from Javascript to Laravel controller

I'm getting the error of MethodNotAllowedHttpException when I run the below code:
<h1>Temp Form</h1>
<form method="post" action="" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="panel panel-default ">
<div class="container">
<div class="panel-body">
<div class="form-group">
<label for="firstName">First Name *</label>
<input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="lastName">Last Name *</label>
<input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
</div>
<div class="form-group">
<label for="qualification">Qualification *</label>
<input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
</div>
<div class="form-group">
<label for="emailAddress">Email address *</label>
<input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactmessage">Message</label>
<textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
</div>
<input type="submit" id="add" class="btn btn-primary" onclick="addUpdateData(id)" value="Add"></button>
</div>
</div>
</div>
</form>
Code for routes.php :
Route::post('welcome/addupdate','FormController#addUpdateData');
code for controller :
public function addUpdateData(Request $req)
{
$id = $req->input('id');
if($id=="add")
{
$bs = new Basicusers;
$bs->fname = $req->fname;
$bs->lname = $req->lname;
$bs->qualification = $req->qualification;
$bs->email = $req->email;
$bs->desc = $req->desc;
$bs->save();
return "Data Successfully Added";
}
}
What I want is, when user clicks on add button, value in variable data add is passed, and on controller, I will check value for variable and if its add, than I will perform add operation.
meanwhile if the user click on edit button which is provided below in form, that row will be filled in form elements and the add button is changed to update button and value of variable data will be now update and I want to perform update operation...
I'm getting error when I am passing data using POST method
moreover I don't know how to get data passed using POST method..
for GET method I am using $id = Input::get('id'); method and its working
Here is JavaScript Function :
function addUpdateData(data) {
$(function() {
$.ajax({
method: "post",
url: "welcome/addupdate",
data: {
id: data
},
success: function(response) {
alert(response);
}
});
});
}
Try to use absolute path in your ajax request: url: "/welcome/addupdate"
Add a some ID for your form (ex. #form) and pass into the addUpdateData function serialized data from the form.
$('#add').on('click', function(e) {
e.preventDefault();
var data = $('#form').serialize();
addUpdateData(data);
});
Add also a input field as hidden type into the form which should have an ID of the existing resource. Then on the controller action you can get an array of the passed data and if if the ID of the resource exists the perform update. If not then create them.

How to store data/parameters in html using angular?

If I have a comment thread, and I want to reply to the comment thread I would have to
return $http.post('/reply/', {
user: username,
test: text ,
parent: parent
}).then(registerSuccessFn, registerErrorFn);
The html would be something in the line of
<form role="form" ng-submit="vm.reply()">
<div class="form-group">
<label for="user">User</label>
<input type="text" class="form-control" id="user" ng-model="vm.user" placeholder="ex. john" />
</div>
<div class="form-group">
<label for="text">text</label>
<input type="text" class="form-control" id="text" ng-model="vm.text" placeholder="text" />
</div>
<div class="form-group">
<label for="parent">parent</label>
<input type="text" class="form-control" id="parent" ng-model="vm.parent" placeholder="parent" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
But the thing is that parent, and the user should be dynamically generated, how do I generate the form dynamically so that each form in html correctly stores the parameter for parent and user such that it reflect the parent of the post and user comment on it?
You can bind the page the form is on (or alternatively just the form itself) to a controller e.g. MyFormController. Then when initially loading the page/form, make sure to load the parent and user information and store in your $scope.vm model.
NB - I'm of course assuming that you have the parent and user information in your database since you said they will be dynamically generated.
var loadData = function () {
$http.get(user_url).success(function (user) {
$scope.vm.user = user;
});
$http.get(parent_url).success(function (parent) {
$scope.vm.parent = parent;
});
};
loadData();
That's about all you'll need to do and the data will be binded to your form.
Cheers

Categories

Resources