Angular Form submit getting as object instead of value - javascript

I am creating basic angular form and onsubmit trying to retrieve the form value, but my case instead of getting value I am getting value as object.
Note: copied the code with some example.
can you please let me know why i am getting object instead of value?
Please find my below code:
html:
<div class="container">
<h2> User Data </h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
component:
onSubmit(value: any) {
console.log("Form Value : " + value);
}

Your userForm.value contains two values which are name and email.
So when you do console.log(userForm.value);, it will return something like this:
{
name: 'Surjeet',
email: 'suri#yopmail.com'
}
To access the particular value you can do:
userForm.value.name => It will return 'Surjeet'
userForm.value.email => It will return 'suri#yopmail.com'
So what you can do now:
Two things you can do in your case:
First one: (get the value by its property)
onSubmit(value: any) {
//get the value by its property
console.log("Name: " + value.name);
console.log("Email: " + value.email);
}
Second one: (pass only those value which you need)
//(ngSubmit)="onSubmit(userForm.value.name)"
<div class="container">
<h2> User Data </h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value.name)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

The value has to be an object. The form contains multiple elements , hence has multiple values.
Try this:
onSubmit(value: any) {
console.log("Form Value : ",value);
console.log(value.name);
console.log(value.email);
}

Your input field should be something like this:
<input class="form-control" type="text" [(ngModel)]="name" formControlName="name">
and then in submit function get it's value like
onSubmit(post){
console.log(post.name);
}

--> in HTML file
<div class="container">
<h2> User Data </h2>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value.name,userForm.value.email)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ngModel>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
--> in TS file
onSubmit(name:any, email:any) {
console.log('Name = ' + name);
console.log('Email = ' + email);
}
--> By this code you can get specific value in form either by button triggering (should mention required properties to submit and also in receiving method) or by entire form submit.

Related

How to check all the form fields were given to enable the submit button?

I need to enable the submit button, only when all the Input values were given.
I have a form like the below in my blade file.
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5"> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>
Added the required attribute inside the controller.
In controller:
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required',
]);
}
The problem is, even if I add the name field and click the button , the submit button is disabled on click.
The button should be disabled, only when all the input fields were given.
Script:
const button = document.querySelector("#buttonSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';
button.addEventListener("click", () => {
var form = document.getElementById("contactForm");
var fields = ["name", "email","body"];
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if(form[fieldname].value !== ""){
button.disabled = true;
let now = new Date();
let expirationTime = 1000 * 5; // 5 secs to disable the submit button
let expirationDate = new Date(now.getTime() + expirationTime);
localStorage.setItem(buttonExpirationDataKey, expirationDate);
button.dataset.enabledAt = expirationDate;
}
else {
button.disabled = false;
}
return false;
}
});
The for loop iterates over each input element, if the particular input element have a value and then If we click the submit. The button is disabled and stored in the local storage.
How to check all the form input and the textarea has values and then after clicking the submit button, the button should be disabled for 5 secs.
https://jsfiddle.net/1vgzj8oc/
How could I do this? Could anyone please help?
You can simply add the required attributes to the HTML
<input type="text" name="name" id="name" value="" required/>
But if you choose to do it with jS, you can do it this way...
<input type="text" name="name" id="name" value="" class="requiredInput"/>
<input type="submit" value="Submit" class="requiredInput primary" id="buttonSubmit" disabled/>
const requiredInputs = document.querySelectorAll(".requiredInput");
requiredInputs.forEach(function(input) {
// Logic
});
You can add required attribute. added link for reference
[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required]
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5" required> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>

how to get a dynamic form id generated by jsp in jquery

How to get a formId that is generated by using a jsp using jquery?
<c:url var="updateSubUserDetails" value="/employer/recruiters/updateSubUserDetails"/>
<form id="updateform${subUser.employerId}" action="${updateSubUserDetails}" method="post" >
<div class="modal-body">
<input type="hidden" name="subUserId" value="${subUser.employerId}"/>
<div class="form-group">
<input type="text" id="subUserName${subUser.employerId}" name="subUserName" class="form-control " value="${subUser.firstName}" placeholder="Edit Sub User Name"/>
</div>
<div class="form-group">
<input type="text" id="subUserEmail${subUser.employerId}" name="subUserEmail" class="form-control " value="${subUser.emailId}" onchange="checkMail(${subUser.employerId})" placeholder="Edit Email"/>
</div>
<span id="avialabilityMessage${subUser.employerId}"></span>
<div class="form-group">
<input type="text" id="subUserMobile${subUser.employerId}" name="subUserMobile" class="form-control " value="${subUser.mobileNumber}"placeholder="Edit Contact No"/>
</div>
<sec:csrfInput/>
<div class="modal-footer">
<input type="button" id="muEditButtonID" onclick="updateSubUserDetails(${subUser.employerId})" class="btn btn-warning btn-lg glyphicon glyphicon-ok-sign" value="Update"> 
</div>
</div>
</form>
How to get above dynamically generated form id in javascript jquery? Please assist me.
//if you sure there is only one form
document.forms[0]
//else
document.querySelector('[id^="updateform"]')
so, if you want to get id just add .id
//if you sure there is only one form
document.forms[0].id
//else
document.querySelector('[id^="updateform"]').id

Error message in contact form

I have created a contact (4 input text) form and I want if user doesn't text in anyone of input a text message will appear above each input.
Contact From:
<form class="form-horizontal" method="post" action="#" name="form" onsubmit="return validation();">
<fieldset>
<div><h2 style="font-family: Myriad Pro;color:#7f8c8c">form</h2></div>
<div class="form-group">
<div class="col-sm-8">
<input id="fname" name="name" type="text" placeholder="Όνομα" class="form-control">
<div id="error1" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input id="lname" name="surname" type="text" placeholder="Επώνυμο" class="form-control">
<div id="error2" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 ">
<input id="email" name="email" type="email" placeholder="E-mail" class="form-control">
<div id="error3" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 ">
<textarea id="message" name="message" type="text" placeholder="Το σχόλιο σας.." columns="7" rows="7" class="form-control" style="background-color:#e5e6e6;" required=""></textarea>
<div id="error4" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 text-center">
<button type="submit" class="btn btn-primary btn-block" id="label" >SEND</button>
</div>
</div>
</fieldset>
</form>
And the script I use:
function validation(){
if (document.form.name.value == "") {
document.getElementById('error1').innerHTML="*Error Msg1 ";
}else if (document.form.surname.value == "") {
document.getElementById('error2').innerHTML="*Error Msg2 ";
}else if (document.form.email.value == "") {
document.getElementById('error3').innerHTML="*Error Msg3 ";
}else if (document.form.message.value == "") {
document.getElementById('error4').innerHTML="*Error Msg4 ";
}
return false;
}
My issue is that if for example the user doesn't fill his name(error message displayed below the text field) BUT then if he text his name the error message IS still displayed.How can I solve this?
There is an example here: Fiddle
I would suggest that you clear the error message at the start of the validation again:
function validation(){
document.getElementById('error1').innerHTML=""
document.getElementById('error2').innerHTML=""
document.getElementById('error3').innerHTML=""
document.getElementById('error4').innerHTML=""
//Your validation code below:
...
}
This way whenever the input validates, all of the error messages will be cleared and evaluated again.
You might want to consider storing the labels at the start of the function in a field so you have easy access to them later. This should help with readability as well. For example:
function validation(){
var errorMessage1 = document.getElementById('error1');
//Access the label using your new variable:
errorMessage1.innerHTML = "Your value here"
...
On keyup event lets try resetting the error message
document.form.name.addEventListener("keyup", function(){
document.getElementById('error1').innerHTML = '';
});

Detect the name of required field and not validated when submit a form

I create a form in html5 like this example :
<form action="/my/url/insert.php" method="POST">
<div class="row">
name <input name="name" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
$('form').submit(function(){
console.log('test');
});
</script>
The problem :
I want to detect the name of the required field that are not validated when submiting and logging it.
for example : if I don't fill the input "album" when submit i detect it before the message "a field is required..."
is there a way to do this ?
thank you.
Here you go.. Loop through each input:required field and get its name with .attr.
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
console.log($(this).attr('name'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Updated
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
if($(this).val()==""){ //check if its empty
console.log($(this).attr('name'));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Assuming that only required will be the property for validation, above condition will hold good and yea, by default when you say required, browser will have its validation suppressing validation written by you. If you want your validation to work, add novalidate to form as said in one of the comments above..
Select them by property required:
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
console.log($(this).attr("name"));
});
});
});
To do a simple required check on your own make a simple "not empty" condition. But for this, your form need the novalidate class, otherwise submit callback will not be triggered and nothing ever happens.
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
if( $(this).val() != "" )
console.log($(this).attr("name"));
});
});
});
Full example here: https://jsfiddle.net/vvdh66rb/
You can also do like this:
<form action="/my/url/insert.php" method="POST" onSubmit="return myFunction()">
<div class="row">
<!--I am only giving id to one to show an exmaple you can give to differnt-->
name <input name="name" id="some" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
function myFunction() {
var x = document.getElementById('some').value;
if (x == "" || x == null) {
alert('sadsd');
return false;
//You can give anything else than alert
}
}

jQuery's val() returns empty string on bootstrap popover input field

I have a bootstrap popup form with a few input fields. I've added a submit button to the form, that triggers client-side JS validation. However, when the button is clicked, the current value of the input fields is not captured by jQuery's val() method: I just get an empty string.
Here is the markup:
<div class="popover fade right in" style="top: -154.5px; left: 249px; display: block;">
<div class="arrow">
</div>
<h3 class="popover-title">New Job Site contact</h3>
<div class="popover-content">
<form class="popover-form form-horizontal" id="newjobsite_contact_form" accept-charset="utf-8" method="post" action="http://dev.temperature/home/#">
<div class="form-group">
<div class=" required ">
<input type="text" class="form-control" id="popover-first_name" required="1" placeholder="First name" value="" name="first_name">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Phone" value="" name="phone">
</div>
<div class="">
<input type="text" class="form-control" placeholder="Mobile" value="" name="mobile">
</div>
<div class="">
<input type="email" class="form-control" placeholder="Email" value="" name="email">
</div>
<div class="">
<input type="url" class="form-control" placeholder="Website" value="" name="website">
</div>
</div>
<div class="popover_buttons">
<button class="btn btn-success" onclick="submit_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_submit">Submit</button>
<button class="btn btn-warning" onclick="close_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_cancel">Cancel</button>
</div>
</form>
</div>
</div>
Here is the JS:
function submit_newjobsite_contact() {
errors_found = validate_popover_form($('#newjobsite_contact_form'));
if (errors_found.length == 0) {
// Form values submitted to PHP code through AJAX request here
} else {
error_msg = "Please check the following errors:\n";
$(errors_found).each(function(key, item) {
error_msg += "- "+item.message+"\n";
});
alert(error_msg);
}
}
function validate_popover_form(form_element) {
found_errors = [];
$('span.error').remove();
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
console.log($(item).val()); // More validation here, just putting debugging code instead
});
return found_errors;
}
What am I doing wrong? All other attributes for these input fields are being correctly retrieved by jQuery, just not the value after I've typed text into them.
The answer to this problem couldn't be found here because I didn't post the whole source JS, which is too large. What really happened is that I accidentally cloned the popover form, which led to a duplication of the input fields.
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
I Modified it to:
form_element.find('select,input').each(function(key, item) {
if ($(this).data('required') == '1' && $(this).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(this).attr('name'), message: "A value for "+$(this).attr('placeholder')+" is required"});
}
Try using data attributes so instead of using required="1" use data-required="1"
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
so your input should be like this:
<input type="text" class="form-control" data-required="1" placeholder="Surname" value="" name="surname">

Categories