My JSON information:
{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}
I want the RES_ID as autocomplete for the following input:
<input id="reservation_id" class="ui-autocomplete-input form-control" />
And when the input reservation_id will be filled take the rest RES_CHECK_IN and RES_CHECK_OUT and autofill them in
<input type="text" class="form-control" name="start">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" name="end">
I tried to mix ajax + autocomplete do achieve that without any luck.
(function autocomplete_search() {
//this function take the #res_id input
$("#reservation_id").autocomplete({
source: "/police/get_res"
});
})();
How I show RES_ID as autocomplete and how i fill the rest of the inputs based on the RES_ID?
$("#reservation_id").kendoAutoComplete( {
dataTextField: "name",
dataSource: {
transport: {
read: {
url: "JSON File name",
serverPaging:true,
type: "POST",
data: {
json: JSON.stringify([{"name": "Karan"}, {"name": "Singh"}] )
}
}
}
}
} );
and in HTMl Side
<input id="reservation_id" />
Go : Link
or :
var data = [{
"RES_ID":"2622959",
"PROP_ID":"76055",
"RES_CHECK_IN":"2015-04-21",
"RES_CHECK_OUT":"2015-04-25",
"RES_N_ADULTS":"6",
"RES_GUEST_FIRSTNAME":"Nicolas",
"RES_GUEST_LASTNAME":"Prantzos"
}];
$("#reservation_id").autocomplete({
source: function (request, response) {
response($.map(data, function(v,i){
return {
label: v.RES_ID,
value: v.RES_GUEST_LASTNAME
};
}));
}
});
Final Fiddle :-Final
So I haven't found an easy solution for this. had to code myself.
jQuery:
(function autocomplete_search() {
//this function take the #res_id input
var ac_config = {
source: "/police/get_res",
select: function(event, ui) {
$("#reservation_id").val(ui.item.RES_ID);
$("#checkin").val(ui.item.RES_CHECK_IN);
$("#checkout").val(ui.item.RES_CHECK_OUT);
$("#firstname").val(ui.item.RES_GUEST_FIRSTNAME);
$("#lastname").val(ui.item.RES_GUEST_LASTNAME);
},
minLength: 1
};
$("#reservation_id").autocomplete(ac_config);
})();
HTML:
<div class="form-group">
<label class="col-md-3 control-label" for="inputTooltip">Firstname <span class="required">*</span>
</label>
<div class="col-md-6">
<input type="text" title="" data-toggle="tooltip" data-trigger="hover" class="form-control" data-original-title="What is your name?" id="firstname" aria-describedby="tooltip332323">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="inputTooltip">Lastname <span class="required">*</span>
</label>
<div class="col-md-6">
<input type="text" title="" data-toggle="tooltip" data-trigger="hover" class="form-control" data-original-title="What is your Last name?" id="lastname" aria-describedby="tooltip332323">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Checkin / Checkout:</label>
<div class="col-md-6">
<div class="input-daterange input-group" data-plugin-datepicker="">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" class="form-control" id="checkin" name="checkin" value="">
<span class="input-group-addon">to</span>
<input type="text" class="form-control" id="checkout" name="checkout" value="">
</div>
</div>
</div>
Codeigniter model which generates the JSON:
function get_res($q) {
$this->db->select('RES_ID, PROP_ID, RES_CHECK_IN, RES_CHECK_OUT, RES_N_ADULTS, RES_GUEST_FIRSTNAME, RES_GUEST_LASTNAME');
$this->db->like('RES_ID', $q);
$query = $this->db->get('reservations');
if($query->num_rows() > 0){
foreach ($query->result_array() as $row){
//build an array
$row['value'] = $row['RES_ID'];
$row['label'] = "{$row['RES_ID']}";
$matches[] = $row;
}
echo json_encode($matches); //format the array into json data
exit;
}
}
Controller:
function get_res(){
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->Police_model->get_res($q);
}
}
Hope It will help someone!
Related
I'm new to jQuery and Bootstrap, I'm using jquery and Bootstrap 4 for validation of my form modal, whenever there is an error it must show the error below the corresponding fields, but in my case the select field gets overwritten by the error and select field disappears but it works fine for input field.
here have a look and if you want to have a close look on image just click on it..
As you can see the select fields get overwritten by the fieldError but it's fine for input field.
here's my jQuery validation code:
$(function(){
setCategorySelect();
$(document).on('shown.bs.modal','#manageItemsModal', function () {
$('#manageItemsModal #btnSubmit').on('click', function(){
if (validateForm()) {
messageSuccess("Very well");
} else {
messageError("Oops!!");
}
});
});
});
function validateForm() {
var validationStatus = true;
if ($('#manageItemsForm #selectedCategory').val().length == 0) {
showFieldError(('#manageItemsForm #selectedCategory'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedCategory').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBrandModel').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBrandModel'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBrandModel').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #serialNo').val().length == 0) {
showFieldError(('#manageItemsForm #serialNo'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #serialNo').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedVendor').val().length == 0) {
showFieldError(('#manageItemsForm #selectedVendor'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedVendor').focus() };
validationStatus = false;
}
if ($('#manageItemsForm #selectedBranch').val().length == 0) {
showFieldError(('#manageItemsForm #selectedBranch'), 'Must not be blank');
if (validationStatus) { $('#manageItemsForm #selectedBranch').focus() };
validationStatus = false;
}
return validationStatus;
}
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
function setCategorySelect() {
var $categorySelect = $('#manageItemsForm #selectedCategory').selectize({
selectOnTab: true,
closeAfterSelect: true,
persist: false,
create: false,
valueField: 'id',
labelField: 'text',
options: [],
preload: true,
onInitialize : function() {
var self = this;
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: '*'
},
error: function() {
callback();
},
success: function(res) {
self.addOption(res.data);
}
});
},
load: function(query, callback) {
if (query.length <= 2) return callback();
$.ajax({
url: '/assetCategory/search',
type: 'POST',
dataType: 'json',
data: {
searchText: query + "*"
},
error: function() {
callback();
},
success: function(res) {
console.log(res.data);
callback(res.data);
$categorySelect.refreshItems();
},
fail : function() {
callback();
}
});
}
});
}
here's my HTML:
<div class="modal-body">
<form id="manageItemsForm">
<input type="hidden" id="id" name="id">
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="selectedCategory" class="col-form-label"><span class="text-danger">* </span>Category</label>
<select class="form-control" name="selectedCategory" id="selectedCategory"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="selectedBrandModel" class="col-form-label"><span class="text-danger">* </span>Brand & Model</label>
<select class="form-control" name="selectedBrandModel" id="selectedBrandModel"></select>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">* </span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-8">
<div class="form-group">
<label for="description" class="col-form-label">Description</label>
<input type="text" class="form-control" id="description" name="description">
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Vendor</label>
<select class="form-control" name="selectedVendor" id="selectedVendor"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="selectedVendor" class="col-form-label"><span class="text-danger">* </span>Purchase Date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="supportTillDate" class="col-form-label"><span class="text-danger">* </span>Support till date</label>
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="supportTillDate" name="supportTillDate" />
<span class="input-group-text input-group-append input-group-addon"><i class="simple-icon-calendar"></i></span>
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-9">
<div class="form-group">
<label for="selectedBranch" class="col-form-label"><span class="text-danger">* </span>Branch</label>
<select class="form-control" name="selectedBranch" id="selectedBranch"></select>
<div class="invalid-feedback"></div>
</div>
</div>
<div class="col-3">
<label for="purchasePrice" class="col-form-label">Purchase Price</label>
<div class="input-group">
<div class="input-group-prepend"><span class="input-group-text input-group-addon" style="padding: 0.4rem 0.75rem 0.3rem 0.75rem;">₹</span></div>
<input id="purchasePrice" name="purchasePrice" type="text" class="form-control" aria-label="Amount" style="text-align:right;">
</div>
<div class="invalid-feedback"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="btnSubmit" type="button" class="btn btn-primary">Save</button>
</div>
</div>
By the way I am using jQuery in Spring boot and everything is working fine(save, update, delete) except for validation from jQuery.
Please help!!
I can't see working code because you using some external references like selectize.
I suggest you get used to "snippets" to provide code.
Bytheway, your problem seems to be just about styles. I can't know, but my bet is you just need to provide a css style for
.select::after.error {
color:red;
}
You can inspect and copy CSS code.
The problem is in Your HTML, the nodes of your .input-group does not have allways the same structure. In some cases you have .invalid-feedback just after the input such as this HTML
<div class="form-group">
<label for="serialNo" class="col-form-label"><span class="text-danger">*
</span>Serial No.</label>
<input type="text" class="form-control" id="serialNo" name="serialNo">
<div class="invalid-feedback"></div>
</div>
For other fields the .invalid-feedback isn't after the input but outside from .form-group. take a look
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div class="invalid-feedback"></div>
This difference in HTML structure of the form made your showFieldError() and clearFieldError() not working allways as you expected, because $(element).next() don't catch the right DOM node for insert/remove the validation message. So in some cases clearFieldError remove the wrong HTML tag and this can make your selects disappear
function showFieldError(element, message) {
$(element).addClass('is-invalid');
$(element).next().html(message);
$(element).next().show();
}
function clearFieldError(element) {
$(element).removeClass('is-invalid');
$(element).removeAttr('required');
$(element).next().html('');
}
So you have to fix Your HTML to obtain the same structure for all fields. Put the <div class="invalid-feedback"></div> allways just below the select or input field. Otherwise you have to change the selector that you pass to showFieldError() and clearFieldError() functions according to your HTML
Otherwise a simply approach is to add a ID to divs with class .invalid-feedback, an ID which you can easily manage by his related input ID, something like
<div class="input-group date" data-date-format="dd-M-yyyy">
<input type="text" class="form-control" id="purchaseDate" name="purchaseDate" />
<span class="input-group-text input-group-append input-group-addon">
<i class="simple-icon-calendar"></i>
</span>
</div>
<div id="purchaseDate_err_mex" class="invalid-feedback"></div>
in this way you can pass the input name to your functions and them becomes
function showFieldError(input_id, message) {
$('#'+input_id).addClass('is-invalid');
$('#'+ input_id +'_err_mex').html(message).show();
}
function clearFieldError(input_id) {
$('#'+input_id).removeClass('is-invalid');
//$('#'+input_id).removeAttr('required');
/* don't need to remove required attribute from mandatory fields */
$('#'+ input_name +'_err_mex').html('').hide();
}
and the validation function
function validateForm() {
var validationStatus = true;
if ($('#selectedCategory').val().length == 0) {
showFieldError('selectedCategory', 'Must not be blank');
if (validationStatus) { $('#selectedCategory').focus() };
validationStatus = false;
}
........
return validationStatus;
}
You only check if the length of all fields is more than 0, so you can validate the entire form within a loop
function validateForm() {
var validationStatus = true;
var form_inputs = $('#manageItemsForm input, #manageItemsForm select')
$.each(form_inputs,function(){
var input_id = $(this).attr('name');
clearFieldError(input_id);
if ($.trim($(this).val()).length == 0 && $(this).is("[required]")) {
showFieldError(input_id, 'Must not be blank');
if (validationStatus) { $('#'+input_id).focus() };
validationStatus = false;
}
});
return validationStatus;
}
On click at button "Salvar" I need to verify if any required fields are null and if one of those are null, I need to abort vue.js method post before it goes to the action in controller.
Is there anyone that can help me out?
Here is the code:
Thanks!
var vm = new Vue({
el: '#form',
data: {
endereco: "",
cidade: "",
estado: "",
cep: "",
},
methods: {
postResults: function () {
this.$http.post('/Controller/Action/', {
Endereco: this.endereco,
Cidade: this.cidade,
Estado: this.estado,
CEP: this.cep,
SEND: false
}).then((response) => {
console.log(response.data);
console.log(response.data.worked);
if (response.data.worked) {
console.log("DADOS ADICIONADOS!");
}
});
}
}
})
<div class="form-group label-floating">
<label class="control-label" for="endereco">
Endereço
</label>
<input type="text" class="form-control" id="endereco" v-model="endereco" required>
<span class="material-input"></span>
</div>
<div class="form-group label-floating">
<label class="control-label" for="cidade">
Cidade
</label>
<input type="text" class="form-control" id="cidade" v-model="cidade" required>
<span class="material-input"></span>
</div>
<div class="form-group label-floating">
<label class="control-label" for="estado">
Estado
</label>
<input type="text" class="form-control" id="estado" v-model="estado" required>
<span class="material-input"></span>
</div>
<div class="form-group label-floating">
<label class="control-label" for="cep">
CEP
</label>
<input type="text" class="form-control" id="cep" v-model="cep" required>
<span class="material-input"></span>
</div>
<button class="btn btn-success" style="width: 80%;" v-on:click="postResults" type="submit">Salvar</button>
Really you should wrap this in a form:
<form v-on:submit.prevent="postResults">
Then remove the click handler from the button.
Next, create a new method, we'll call it validatesFields. Make it return a promise that either resolves or rejects based on validity:
validatesFields: function() {
return new Promise(function(resolve, reject) {
if (this.field.valid && this.other_field.valid&&) {
return resolve()
} else {
return reject()
}
})
}
Finally, observe this promise in your postResults function:
postResults: function () {
this.validatesFields()
.then(function(){
this.$http.post('/Controller/Action/', {
Endereco: this.endereco,
Cidade: this.cidade,
Estado: this.estado,
CEP: this.cep,
SEND: false
}).then((response) => {
console.log(response.data);
console.log(response.data.worked);
if (response.data.worked) {
console.log("DADOS ADICIONADOS!");
}
});
}).error(function(){
// field validation failed, do something here
})
}
I am new to MVC.
When I want to pass the form data from ejs file to controller, it does not work.
Create.ejs file
<!--create.ejs-->
<h2 class="col-sm-offset-1">Person Create form</h2>
<form action="/person/create" method="POST" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Name: </label>
<div class="col-sm-8">
<input class="form-control" name="Person[name]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Age: </label>
<div class="col-sm-8">
<input class="form-control" name="Person[age]" type="number"
min="0" max="120">
</div>
</div>
<button class="btn btn-default col-sm-offset-2" type="submit" value="ADD">Submit</button>
PersonController.js
module.exports = {
create: function(req, res) {
if (req.method == "POST") {
Person.create(req.body.Person).exec( function(err, model) {
return res.send("Successfully Created!");
});
} else {
return res.view('person/create');
}
},
The result is that it cant get inside the (req.method == "POST") condition.
Give me 404 error.
A 404 is a not found result.
When POSTing ensure you are targeting your Controller functions try:
'POST /person/create': 'person/PersonController.create',
Though why do you have a subfolder named person when you are using a controller?
Using Actions
In Sails v1.0 you would separate your controller functions into more manageable actions. A sub folder api/controllers/person makes more sense now.
Your routes.js file would read 'POST /person/create': {action: 'person/create'},
For simplicity I have removed req.body.Person as an array...
<form action="/person/create" method="POST" class="form-horizontal">
<input type="hidden" name="_csrf" value="<%= _csrf %>" />
<div class="form-group">
<label class="control-label col-sm-2">Full Name: </label>
<div class="col-sm-8">
<input class="form-control" name="fullName" placeholder="John Johnson" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Age: </label>
<div class="col-sm-8">
<input class="form-control" name="age" type="number" min="0" max="120">
</div>
</div>
<button class="btn btn-default col-sm-offset-2" type="submit" value="ADD">Submit</button>
</form>
then your async function would be like...
module.exports = {
friendlyName: 'Create Person.',
description: 'Creating a new person.',
exits: {
success: {
description: 'Person Created successfully.',
viewTemplatePath: 'person/review',
}
},
fn: async function (inputs, exits) {
if (!this.req.me) throw {redirect: '/'};
let params = this.req.allParams();
let person = await Person.create(params).fetch();
return exits.success({person:person});
}
}
Like #Tejashwi suggested you need to change your route to a POST.
'POST /api/v1/create': { action: 'create/person-create-form' },
I am new to salesforce and don't have a lot of experience with javascript. The issue I am having is that as I am testing a form and filling out the inputs it is adding the the "has-error" class to the parent div even when the input is filled out correctly. However, it will allow the form to be submitted so it is not conflicting with that.
I took over the work from another developer so Im not sure what is causing the error.
The is the javascript for the salesforce form. I am also using validate.js:
'use strict';
var constraints = {
// First Name
'00N4100000CJ8sT': {
presence: {
message: '^First Name is required'
},
length: {
maximum: 80
}
},
// Last Name
'00N4100000CJ8sY': {
presence: {
message: '^Last Name is required'
},
length: {
maximum: 80
}
},
// Appointment Date
'00N4100000EWaN0': {
presence: {
message: '^Date is not valid'
},
format: {
pattern: /^\d{1,2}\/\d{1,2}\/\d{4}$/,
},
},
// Patient Email
'00N4100000CJ8sE': {
presence: {
message: '^Email is required'
},
email: {
message: '^Email is not valid'
}
},
// Phone
'phone': {
presence: true,
format: {
pattern: /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/,
message: '^Phone Number is not valid'
}
}
};
$('.salesforce-form').each(function () {
var form = this;
form.addEventListener('submit', function (ev) {
ev.preventDefault();
handleFormSubmit(form);
});
var inputs = document.querySelectorAll('input, textarea, select');
for (var i = 0; i < inputs.length; ++i) {
inputs.item(i).addEventListener('change', function (ev) {
var errors = validate(form, constraints) || {};
showErrorsForInput(this, errors[this.name]);
});
}
function handleFormSubmit(form, input) {
var errors = validate(form, constraints);
showErrors(form, errors || {});
if (!errors) {
showSuccess(form);
}
}
function showErrors(form, errors) {
_.each(form.querySelectorAll('input[name], select[name]'), function (input) {
showErrorsForInput(input, errors && errors[input.name]);
});
}
function showErrorsForInput(input, errors) {
var formGroup = closestParent(input, 'form-group');
var messages = formGroup.querySelector('.messages');
resetFormGroup(formGroup);
if (errors) {
formGroup.classList.add('has-error');
_.each(errors, function (error) {
addError(messages, error);
});
} else {
formGroup.classList.add('has-success');
}
}
function closestParent(child, className) {
if (!child || child == document) {
return null;
}
if (child.classList.contains(className)) {
return child;
} else {
return closestParent(child.parentNode, className);
}
}
function resetFormGroup(formGroup) {
formGroup.classList.remove('has-error');
formGroup.classList.remove('has-success');
_.each(formGroup.querySelectorAll('.help-block.error'), function (el) {
el.parentNode.removeChild(el);
});
}
function addError(messages, error) {
var block = document.createElement('p');
block.classList.add('help-block');
block.classList.add('error');
block.innerText = error;
messages.appendChild(block);
}
function showSuccess(form) {
var myEmail = form.querySelector('#my-email').value;
if (!myEmail.length > 0) {
form.querySelector('#orgid').value = '00D41000000MWct';
var postData = $(form).serializeArray();
$.ajax({
type: 'POST',
url: '(salesforce url goes here)',
data: postData,
success: function success(data, textStatus, jqXHR) {
//data: return data from server
},
error: function error(jqXHR, textStatus, errorThrown) {
//if fails
$(form).find('.form-group').fadeOut();
$('.thank-you-message').last().clone().appendTo(form).fadeIn();
dataLayer.push({
'event': 'gtm.formSubmit',
'gtm.elementClasses': form.className
});
}
});
}
}
});
This is the html for the salesforce form:
<form class="salesforce-form salesforce-contact-form" novalidate>
<div class="hide form-group">
<input id="my-email" name="my-email" type="text" />
<input type="hidden" id="orgid" name="orgid" />
<input type="hidden" id="email" name="email" value="test#email.com"/>
<input type="hidden" id="00N4100000IkI2v" name="00N4100000IkI2v" value="<?php echo get_permalink(); ?>" />
<input type="hidden" id="00N4100000IkHtO" name="00N4100000IkHtO" value="<?php echo get_client_ip(); ?>" />
<input type="hidden" id="00N4100000HxXj4" name="00N4100000HxXj4" value="New" />
<input type="hidden" id="00N4100000CL2tK" name="00N4100000CL2tK" value="Request Appointment" title="Form Type" />
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group first-name">
<label for="00N4100000CJ8sT" class="hidden">First Name</label>
<input id="00N4100000CJ8sT" maxlength="80" name="00N4100000CJ8sT" size="20" type="text" placeholder="First Name: *">
<div class="messages"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group last-name">
<label for="00N4100000CJ8sY" class="hidden">Last Name</label>
<input id="00N4100000CJ8sY" maxlength="80" name="00N4100000CJ8sY" size="20" type="text" placeholder="Last Name: *">
<div class="messages"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group email">
<label for="00N4100000CJ8sE" class="hidden">Email</label>
<input id="00N4100000CJ8sE" maxlength="80" name="00N4100000CJ8sE" size="20" type="email" placeholder="Email: *">
<div class="messages"></div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6 form-group phone">
<label for="phone" class="hidden">Phone</label>
<input id="phone" maxlength="40" name="phone" size="20" type="text" placeholder="Phone: *">
<div class="messages"></div>
</div>
<div class="col-md-12 col-xs-12 form-group appointment-date">
<label for="00N4100000EWaN0" class="hidden">Appointment Date</label>
<input id="00N4100000EWaN0" name="00N4100000EWaN0" size="20" type="text" placeholder="Appointment Date: *">
<div class="messages"></div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 form-group comments">
<label for="description" class="hidden">Comments</label>
<textarea id="description" name="description" placeholder="Comments:"></textarea>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 form-group submit">
<input type="submit" value="Submit +" class="btn small"/>
</div>
</form>
Let me know if this needs more explanation or if you need to see any other files.
I am submitting a form - and adding the contents to an array, however whenever the item is added to the array, it is still bound to the form.
I would like to add the item, clear the form. Something like jquery's reset();
Here's my template:
<div class="col-xs-12" ng-controller="ResourceController">
<div class="col-md-4">
<h3>Name</h3>
</div>
<div class="col-md-8">
<h3>Description</h3>
</div>
<form class="form-inline" role="form" ng-repeat="item in resources">
<div class="form-group col-md-4">
<input type="text" class="form-control" value="{{ item.name }}"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" value="{{ item.description }}"/>
</div>
</form>
<form class="form-inline" role="form" name="addResourceForm" ng-submit="addResource()">
<div class="form-group col-md-4">
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Name"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" name="description" ng-model="description" placeholder="Description"/>
</div>
<div class="form-group col-md-1">
<button type="submit" class="btn btn-default">Add</button>
</div>
</form>
</div>
And my controller:
(function(){
var app = angular.module('event-resources', []);
app.controller('ResourceController', function($scope){
$scope.addResource = function(){
$scope.resources.push(this);
}
var defaultForm = {
name : '',
description: ''
};
$scope.resources = [
{
name: 'Beer',
description: 'Kokanee'
},
{
name: 'Pucks',
description: 'Black Round Things'
}
]
});
})();
Use angular.copy() to copy the item data to the resources array, and then you can safely clear the item data. The angular.copy() makes a deep copy of the object, which is what you want.
Alternately, here is a simpler method, which doesn't use any extra method calls:
$scope.addResource = function() {
$scope.resources.push({
name: $scope.name, // recreate object manually (cheap for simple objects)
description: $scope.description
});
$scope.name = ""; // clear the values.
$scope.description = "";
};
$scope.addResource = function(){
$scope.resources.push(angular.copy(this));
$scope.name="";
$scope.description=""
}
Push the copy to the resources array and change name and description back to ""