I have the following code written in angular JS
<html lang="en" ng-app="person_info">
<head>
<meta charset="utf-8">
<title>Person info</title>
<script src="../angular.min.js"></script>
<script src="controller_class2.js"></script>
<style type="text/css">
.forms{width:200px;height:300px;padding:75px;float:left;background:#CCC;}
.deatils{width:200px;height:auto;padding:100px;float:left;background:#CCC;margin- left:10px;}
.fields {background:#999999;float: left;height:120px;padding: 20px;width:260px;}
</style>
</head>
<body ng-controller="info">
<div class="forms"> Name:</br>
<input type="text" value="name" ng-model="person.name">
</br>
</br>
First Name :</br>
<input type="text" value="fname" ng-model="person.firstname">
</br>
</br>
Phone Number :</br>
<input type="number" value="number" ng-model="person.number">
</br>
</br>
Email :</br>
<input type="email" value="email" ng-model="person.email">
</br>
</br>
Address :</br>
<input type="text" value="address" ng-model="person.address">
</br>
</br>
<input type="submit" value="submit" name="submit" ng-click="test()">
</div>
<div class="deatils">
<p>Name : {{person.name}}</p>
<p>First Name : {{person.firstname}}</p>
<p>Phone Number: {{person.number}}</p>
<p>Email : {{person.email}}</p>
<p>Address :{{person.address}}</p></br></br>
<p>Details in json format : </br>{{ person | json }}
</div>
<div class="fields">
Submit the persons serial number to display his details
</br>
</br>
<input type="number" >
</br>
</br>
<input type="submit" value="submit number">
</div>
</body>
</html>
Controller code
var person_info = angular.module('person_info', []);
person_info.controller('info', function($scope) {
$scope.test = function () {
console.log($scope.person);
}
});
When the user fills the form and click on submit button i want the details to be saved into a array and clear all the field so that the next users details can be filled. each user details will be stored in the array.
i have also created a text field where user can enter the serial number of the user whose detail have to be displayed. for example when i enter the value 3 and submit this. the 3rd person's details in the array have to be displayed.
you can define a function like your test() function in your controller to save current model into an array and clear it, here is example function,
$scope.savePerson = function () {
$scope.personList.push($scope.person);
//clear person model/form
$scope.person = {};
};
and here is html form,
<div class="forms">
Name: <input type="text" value="name" ng-model="person.name">
First Name : <input type="text" value="fname" ng-model="person.firstname">
Phone Number : <input type="number" value="number" ng-model="person.number">
Email : <input type="email" value="email" ng-model="person.email">
Address : <input type="text" value="address" ng-model="person.address">
<input type="submit" ng-click="savePerson()">
</div>
and define another function to retrieve data from your personList[] array like this,
$scope.getPerson = function (index) {
//selected person details
$scope.personDetail = $scope.personList[index];
};
of course you shoudl make few changes in your html as well, here is full PLUNKER of my solution...
you can try extracting the value using .serialize() like this
var count=0;
var formArr={};
$('.forms input[type=submit]').on('click',function () {
formArr[count++]=$( "form" ).serialize(); //this would serialize the form data
// clear the form data for next client details entry
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
$('.fields input[type=submit]').on('click',function () {
var serNo=$(this).find ('input[type=text]').val();
var formData= formArr[serNo];
formData=formData.split("&");
for(i=0;i<formData.length;i++)
{
$('input[name='+ formData[i]+']').val(formData[++i]);
}
});
Note: this is untested code, it may require few code tunings
Happy Coding :)
Related
I have a very simple form here with 2 required inputs.
When you click submit button without filling them - there are popups saying that you should do it. The problem is that popups are showed one by one - for example, if both inputs arent filled, only the first input will have this popup. And when the first one is filled only then it goes to the second and vice versa.
Is there any way to show all the fields that are not filled/filled incorrect during the validation at the same moment? So the user sees immediately everything he/she has to fill?
I am quite new to this, so please help me find the solution in pure JS (if it is about JS).
Here is the code:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST">
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" required=""
oninvalid="setCustomValidity('Enter first name')" oninput="setCustomValidity('')"
placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" required=""
oninvalid="setCustomValidity('Enter last name')" oninput="setCustomValidity('')"
placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
The code you provided is using a built in function of JavaScript, setCustomValidity(). This most likely is the reason for the pop-up. Instead we can write a custom function to show a little paragraph/span with the text instead.
Here we have a HTML form, but with a call for the custom function validateFields(), when clicking the Submit button:
<form class="" action="your-post-page.html" method="post" id="my-form-id" name="my-form-name" onsubmit="return validateFields()" target="_blank" class="validate" novalidate="">
<input id="name_1" type="text">
<br><br>
<input id="name_2" type="text">
<br><br>
<input id="name_3" type="text">
<br><br>
<input type="submit" name="" value="SUBMIT FORM">
</form>
<p id="error_messages" style="background-color: red; color: white;"></p>
The JS that makes it happen:
(custom function that reacts to inputs being empty and lets the user know which fields need fixing, put code before the </html> tag in your html-page)
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["name_1", "name_2", "name_3"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["Name 1", "Name 2", "Name 3"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["my-form-id"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
Now lastly, here is your own code with this example:
<html lang="eng">
<head>
<title>Title</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
</head>
<body>
<form id="mainForm" action="#" method="POST" onsubmit="return validateFields()" >
<div>
<div>
<label for="first_name" title="first_name">First name<span class="mandatory">*</span></label>
<input id="first_name" name="first_name" type="text" value="" placeholder="Enter first name">
<p class="error_message"></p>
</div>
<div>
<label for="lastName" title="lastName">Last name<span class="mandatory">*</span></label>
<input id="lastName" name="lastName" type="text" value="" placeholder="Enter last name">
<p class="error_message"></p>
</div>
<div class="">
<input class="email_btn btn btn-block" type="submit" value="Submit">
</div>
<!-- here I added a new box for the error messages in your code -->
<div class="">
<p id="error_messages" style="background-color: red; color: white;"></p>
</div>
</div>
</form>
</body>
<script type="text/javascript">
function validateFields() {
// reference to the message paragraph we aim to fill with error messages.
var error_text_output_element = document.getElementById("error_messages");
var fields_to_check = ["first_name", "lastName"]; // enter the IDs of all fields you want to check for errors in this list.
var fields_human_names = ["First name", "Last name"]; // these are just the human readable names for the fields.
var check_field;
var error_message = "Errors occurred, please fill in these fields: "; // setting basic text here.
var errors_exist = 0;
for (var i = 0; i < fields_to_check.length; i++) {
check_field = document.forms["mainForm"][fields_to_check[i]].value;
if (check_field == "") {
if (errors_exist === 0) {
error_message += fields_human_names[i]; // first time we add a field, no comma.
} else {
error_message += ", " + fields_human_names[i]; // for each field that was empty, add the field and the comma.
}
errors_exist += 1; // increment with one for each error that occurs.
}
}
if (errors_exist > 0) { // only output error messages or stop the form if any fields are empty.
error_text_output_element.innerHTML = error_message;
return false; // stops the sending of the form in the post procedure.
}
} // end message_class function.
</script>
</html>
That was with custom scripting to get a box that you can style and enhance yourself, in this case below the form. But if you are okay with some default (and perhaps not unified styling, due to browser differences) you can also just remove the JavaScript function you had in your original code, the setCustomValidity(''). That will leave you with a generic message using the already present attribute required="", which produces this:
To achive that behaviour, change your tags for each field to look like this instead:
<input id="first_name" name="first_name" type="text" value="" required="" placeholder="Enter first name">
Im trying this for so long and i dont know how to fix it. The idea is simple, The user insert the requiered data in the HTML forms, then the inserted data is stored in an array and display all the data with a text. I think the problem is when i try to store the data from the form into the array.
This is what ive done so far
<html>
<header>
<meta charset="UTF-8">
<title>Second Homework</title>
</header>
<body>
<h1>Welcome!</h1>
<p>Please insert the data in the following form: </p>
<form>
<input type="text" id="name"><br>
<input type="text" id="lname"><br>
<input type="text" id="age"><br>
<input type="text" id="city"><br>
<input type="text" id="pet"><br>
<input type="text" id="pet_name"><br>
<button type="button" id="" onclick="data()">Enviar</button>
</form>
<script type="text/javascript">
function data(){
var info=[getElementById("name").innerHTML.value,getElementById("lname").innerHTML.value,
getElementById("age").innerHTML.value,getElementById("city").innerHTML.value,getElementById("pet").innerHTML.value,getElementById("pet_name").innerHTML.value]
document.write("Your name is: "+info[0])
document.write("Your lastname is: "+info[1])
document.write("You are "+info[2]+" years old")
document.write("You live in: "+info[3])
document.write("Do you have pets? "+info[4])
document.write("Your pets name is: "+info[5])
}
</script>
</body>
<footer>
</footer>
</html>
in HTML, form inputs elements must use a name attribute
do this way:
const myForm = document.forms['my-form']
myForm.onsubmit = e =>
{
e.preventDefault() // disable submit
let info = Array.from(new FormData(myForm).entries()).map(([k,v])=>v)
document.write("<br>Your name is: "+info[0])
document.write("<br>Your lastname is: "+info[1])
document.write("<br>You are "+info[2]+" years old")
document.write("<br>You live in: "+info[3])
document.write("<br>Do you have pets? "+info[4])
document.write("<br>Your pets name is: "+info[5])
/* ------------------------------- or
let msg = `
Your name is: ${myForm.name.value}
Your lastname is: ${myForm.lname.value}
You are ${myForm.age.value} years old
You live in ${myForm.city.value}
Do you have pets? ${myForm.pet.value}
Your pets name is: ${myForm.pet_name.value}`
console.log( msg )
------------------------------------- */
}
<h1>Welcome!</h1>
<p>Please insert the data in the following form: </p>
<form name="my-form">
<input type="text" name="name" placeholder="name" ><br>
<input type="text" name="lname" placeholder="last name"><br>
<input type="text" name="age" placeholder="age" ><br>
<input type="text" name="city" placeholder="city" ><br>
<input type="text" name="pet" placeholder="pet" ><br>
<input type="text" name="pet_name" placeholder="pet name" ><br>
<button type="submit">Enviar</button>
</form>
I am developing a system for equipment rental in PHP.
I need to send a form that contains the id, quantity, time and value fields of the selected equipment.
Each rent can have N equipments, consequently N amount of fields.
How do I do this? Do I generate the fields by javascript? To send, an array for each piece of equipment?
It would be something like that:
<input type='text' name='equipment[]'>
<input type='text' name='quantity[]'>
<input type='text' name='time[]'>
But how would I do it like this:
array(array[0](equipment=>1,quantity=>2,time=>4),array[1](equipment=>2,quantity=>2,time=>4),array[2](equipment=>1,quantity=>2,time=>4));
I think you could group by rental doing like this:
<div id="rental_group_1">
<input type="text" name="rent_1[]" id="equipment_1">
<input type="text" name="rent_1[]" id="quantity_1">
<input type="text" name="rent_1[]" id="time_1">
</div>
<div id="rental_group_2">
<input type="text" name="rent_2[]" id="equipment_2">
<input type="text" name="rent_2[]" id="quantity_2">
<input type="text" name="rent_2[]" id="time_2">
</div>...
This way you will get on Post an array per group so:
$rent_1[0] = equipment_1
$rent_1[0] = quantity_1
$rent_1[0] = time_1
...
Adding this to #Blesson Christy solution will create a good UI/UX for what you want.
Hope it helps! :D
A small example :
HTML:
<div id="content">
<input type="text" class="fieldone" id="fields_1" name="fields[]"/>
</div><input type="button" id="addmore" />
Jquery:
counter=1;
$(document).on('click','#addmore',function(){
counter++;
var htmltoadd='<input type="text" class="fieldone" id="fields_"'+counter+' name="fields[]"/>';
$("#content").append(htmltoadd);
});
You need to include jquery in this example.
I am creating an onlineshop and I want to use Javascript ( I think) or JQuery, in order when the user is entering details for adding a new product into the database, like:
-Title (TEXT)
-Price (FLOAT)
-Description (TEXT)
-Quantity Available (INT)
How to set a check to occur and inform the user that he has an incorrect data type for a specific field? Because now my database lets the user add whatever he wants, and at the preview of the product the field price shows "£0". Also, if the check completes for all the fields and is okay, a message will be shown that it okay.
code below
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<div id="formContents">
<label for="title">Title of your product:
<div id="formContents"> </label><input type="text" name="title" style="width: 180px" onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value=" title of your product here" maxlength="19" /><p>
</div>
<div id="formContents">
<label for="description">Description of your product:
<div id="formContents"> </label><input type="text" name="description" style="width: 180px" onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value="description of the product" maxlength="19" /><p>
</div>
<label for="price">Price: £ </label><input type="INT" name="price" style="width: 40px" /><p>
<label for="stock">Quantity:</label><input type="text" name="stock" style="width: 40px" />
<p>
</div>
you can do it two ways:
prevent him from entering anything other than intended characters :
for example , for fields that would have INT values :
$('.nonly').bind('keyup blur',function(){$(this).val($(this).val().replace(/[^0-9]/g,''));});
validate after entering :
var intRegex = /^\d+$/;
var cellphone = $('#register_phonenum');
if ((cellphone.val()=='')||(!intRegex.test(cellphone.val()))) {
/* do something*/
return false;
}
I have researched online on how to create an additional form field. The method I am using comes from this site.
http://mrngoitall.net/blog/2013/10/02/adding-form-fields-dynamically-in-angularjs/
So basically what I am trying to do, is have data inputted in. But I don't know how many data points a certain person would like to put in. So I what to enable it so I can let them put additional points if they wish.
I have this in my tag:
<script>
function AngularCtrl($scope) {
function Controller($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.showAddChoice = function(choice) {
return choice.id === $scope.choices[$scope.choices.length-1].id;
};
$scope.showChoiceLabel = function (choice) {
return choice.id === $scope.choices[0].id;
}
}
</script>
I then have this in my tag:
<div class="form-group" ng-controller="Controller" data-ng-repeat="choice in choices">
<form novalidate class="simple-form">
Title of Chart: <input type="text" ng-model="chart.title" /><br />
Series Name: <input type="text" ng-model="chart.series" /><br />
Series Data: <input type="text" ng-model="series.data" /><br>
<label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
<button ng-show="showAddChoice(choice)" ng-
click="addNewChoice()">Add another choice</button>
<input type="text" ng-model="choice.name" name="" placeholder="Enter
a new data point">
<br>
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
</div>
So as you can see, what I have is 4 form fields. I want choices to add a new form field. I have the button, but when I click the button to add another form field; it does not work. It stays the same.
I was wondering if what I have in my tags was off a bit.
Thank you for the help. Been struggling on this for hours.
To expand on my comment:
Directive html:
<label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
<input type="text" ng-model="choice.name" name="" placeholder="Enter a new data point" />
<br>
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
Primary content:
<div class="form-group" ng-controller="Controller">
<form novalidate class="simple-form">
Title of Chart: <input type="text" ng-model="chart.title" /><br />
Series Name: <input type="text" ng-model="chart.series" /><br />
Series Data: <input type="text" ng-model="series.data" /><br>
<button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another choice</button>
<div choice-editor ng-repeat="c in choices" choice="c"></div>
</form>
I'm very fuzzy on the best practices with directives. it seems like I mix too much into a single directive sometimes, i.e., i'm not sure if you want the ng-repeat and choice attributes on the same element... Maybe someone else can improve this answer. But that should give you some ideas of how to proceed, hopefully.