I working on Angular 4 project. I am using smart table and form in it.
<div class="row">
<div class="col-lg-12">
<nb-card>
<nb-card-header>Default Inputs</nb-card-header>
<nb-card-body >
<form #f="ngForm" (ngSubmit) = "addNewStudent(f)" >
<div class="row full-name-inputs">
<div class="col-sm-6 input-group">
<input type="text" placeholder="First Name" class="form-control" name="firstName" [(ngModel)]="data.firstName" />
</div>
<div class="col-sm-6 input-group">
<input type="text" placeholder="Last Name" class="form-control" name="lastName" [(ngModel)]="data.lastName" />
</div >
<div class="col-sm-6 input-group">
<input type="text" placeholder="ID" class="form-control" name="id"[(ngModel)]="data.id" [required]=false />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="cancel" class="btn ">Cancel</button>
</form>
</nb-card-body>
</nb-card>
</div>
</div>
On edit button of table the form is open and shows the whole data of that row in that form, similar form button will be open on add new data in which the data should be added but if I enter only one data and submit it it does not add it it requires all fields.
The add function is as follows:
addNewStudent(f: NgForm)
{
console.log(f.value);
if(this.isAddPage)
{
this.service.addNewEnquiry(f.value);
console.log("addenquiry");
}
else{
this.service.editEnquiry(f.value);
console.log("editenquiry");
}
this.router.navigate(['pages/dashboard1']);
}
The addNewEnquiry function in service is as follows:
addNewEnquiry(data)
{
this.af.list('/enquirydata/').push(data);
}
When I enter all fields it added it to the firebase but when I doesn't fill all fields it shows me error.
ERROR Error: Reference.push failed: first argument contains undefined
in property 'enquirydata.lastName
When you want to push an object into Firebase, you can't have values of the properties equals undefined. Firebase accepts value or null only. Else you always show this error.
In your case :
{ id:undefined, lastName:undefined, firstName:undefined }
To resolve your issue :
public data:any = { id:null, lastName:null, firstName:null };
Before inserting it into your list, you can eliminate undefined ones from object.
addNewEnquiry(data)
{
var newData = data.filter(resp=>{
if(resp.firstName && resp.lastName) {
return resp;
}
})
this.af.list('/enquirydata/').push(newData);
}
Related
Html:
<div class="col-6 col-12-medium">
<header>
<h1>Sign Up</h1>
<p>Join the Team!</p>
</header>
<!--form method="post" action="#"-->
<div class="row gtr-uniform">
<div class="col-12">
<input type="text" name="demo-name" id="demo-name" value=""
placeholder="Name" />
</div>
<div class="col-12">
<input type="email" name="demo-email" id="demo-email" value=""
placeholder="Email" />
</div>
<div class="col-12">
<input type="password" name="demo-password" id="demo-password" value=""
placeholder="Password" />
</div>
<div class="col-12">
<input type="password" name="demo-password" id="demo-password" value=""
placeholder="Confirm Password" />
</div>
<!-- Break -->
<div class="col-12">
<ul class="actions">
<li><button class="primary" onclick="addUser()">Add User</button></li>
<li><input type="reset" value="Reset" /></li>
</ul>
</div>
</div>
<!--/form-->
</div>
JavaScript:
//function to add the player to the database
function addUser() {
pId = 0;
//check to ensure the mydb object has been created
if (mydb) {
//get the values of the make and model text inputs
var uname = $("#demo-name").val();
//Test to ensure that the user has entered both a name
if (uname !== "") {
//check that player does not already exist:
//Insert the user entered details into the players table, note the use of the ? placeholder,
//these will replaced by the data passed in as an array as the second parameter
mydb.transaction(function (t) {
t.executeSql("INSERT OR IGNORE INTO tb_users (name) VALUES (?)", [uname]);
// outputUsers(_updatePlayerList);
// outputUsers(_updateVoterList);
// outputUsers(_updatePlayerVotingList);
});
} else {
alert("You must enter a player's name details!");
}
} else {
alert("db not found, your browser does not support web sql!");
}
$("#demo-name").val("");
}
What is wrong with my code here? I have tried using breakpoints but it doesn't even recognise "uname" as a variable in the developer console. I've included more code showing the inclusion of the function call. I have commented out the form in the html because I assumed it would not be necessary and could be the reason of failure.
Also I opened the database file created and stored by Google Chrome and it had all the correct parameters but none of the prompted information was added.
I created the following HTML form inside a jqxWindow widget for a Laravel project:
<div id="provinceWindow">
<div id="provinceWindowHeader"></div>
<div id="provinceWindowContent">
<form id="provinceForm" method="POST" action="{{route('province.store')}}">
{{ csrf_field() }}
<input type="hidden" name="provinceId" id="provinceId" value=""/>
<div class="form-group row">
<div class="col-6"><label>English province name</label></div>
<div class="col-6"><input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20"/></div>
</div>
<div class="form-group row">
<div class="col-6"><label>Spanish province name</label></div>
<div class="col-6"><input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20"/></div>
</div>
<br/>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3" />
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3" />
</div>
</form>
</div>
</div>
This is the javascript file:
$(document).ready(function () {
var datarow = null;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
//-----------------------------
// Window settings
//-----------------------------
$('#provinceWindow').jqxWindow({
autoOpen: false,
isModal: true,
width: 400,
height: 160,
resizable: false,
title: 'Province name',
cancelButton: $('#cancelBtn'),
initContent: function () {
$('#submitBtn').jqxButton();
$('#submitBtn').on('click', function () {
$('#provinceForm').submit();
});
}
}).css('top', '35%');
The file routes\web.php has only one resourse route defined for this page:
// Routes for province maintenance
Route::resource('province', 'provinceController');
Checking the available routes with php artisan route:list command, I get these:
Method URI Name Action
GET|HEAD / APP\Http\Controllers\homeController#index
GET|HEAD province province.index APP\Http\Controllers\provinceController#index
POST province province.store APP\Http\Controllers\provinceController#store
GET|HEAD province/create province.create APP\Http\Controllers\provinceController#create
GET|HEAD province/{province} province.show APP\Http\Controllers\provinceController#show
PUT|PATCH province/{province} province.update APP\Http\Controllers\provinceController#update
DELETE province/{province} province.destroy APP\Http\Controllers\provinceController#destroy
GET|HEAD province/{province}/edit province.edit APP\Http\Controllers\provinceController#edit
My controller action:
public function store(Request $request)
{
$fields = $request->all();
if ($request->provinceId == '') {
$province = new province($fields);
$validator = Validator::make($fields, $province->rules());
if ($validator->fails()) {
return redirect('')->withErrors($validator)->withInput();
}
else {
$province->save();
}
return view('province/index');
}
}
The form is shown on top of a jqxGrid widget, as a modal window, in order to capture the required information and perform the CRUD operations for the corresponding DB table.
The problem is, when I click the "Submit" button the window is closed and nothing else happens. The form is not posted to the indicated action and the data entered get lost.
It does not matter if I initialize the submitBtn inside the initContent or outside of it. The form is never posted.
I also tried the Close event of the jqxWindow to no avail.
If I take a look to the generated HTML it looks like this:
<form id="provinceForm" method="POST" action="http://mis:8080/province">
<input type="hidden" name="_token" value="Y9dF5PS7nUwFxHug8Ag6PHgcfR4xgxdC43KCGm07">
<input type="hidden" name="provinceId" id="provinceId" value="">
<div class="form-group row">
<div class="col-6">
<label>English province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20">
</div>
</div>
<div class="form-group row">
<div class="col-6">
<label>Spanish province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20">
</div>
</div>
<br>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3 jqx-rc-all jqx-button jqx-widget jqx-fill-state-normal" role="button" aria-disabled="false">
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3">
</div>
</form>
Pressing the submit button takes me to the home page and nothing gets added to the DB table.
I guess the issue has something to do with Laravel routes because I get no errors.
What is missing or what is wrong with this approach?
Any light is appreciated.
Alright, because I erroneously added in my Model a validation, that was not needed, for a column (there was already a constraint defined at the DB table level), it was not possible to fulfill the validator when saving a new record. I commented that line in my Model and, that was it!
protected $rules = array(
'provinceNameEn' => 'required|alpha|max:20',
'provinceNameSp' => 'required|alpha|max:20'
//'deleted' => 'required|in:M,F' // This is already validated in a DB constraint.
);
I noticed the control was returned to my home page but without any message or error, but if you pay attention to my controller it was precisely the behavior programmed. However, there is no implementation to display the error messages, so I added dd($validator); before that return statement. There I read the message and finally found the solution.
I have a simple input params that are required. I want to disable my submit button until all the required fields are satisfied. Granted I am new to django, and the particular code I am working on is very old. As a result, post like this or this are not helping.
Current code that I am trying from one of the posts linked and including my own template
<script type="text/javascript">
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
$('#submit').on('click', function() {
var zip = $('#zip').val();
var email = $('#email').val();
var name = $('#name').val();
//if inputs are valid, take inputs and do something
});
<form class="form-horizontal" action="" method="get" id="dataform">
<div class="form-group">
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-3">
<input class="col-md-12" id="zip" type="text" placeholder="Enter zip code" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="name" type="text" placeholder="Enter last name" aria-required="true">
</div>
<div class="col-md-3">
<input class="col-md-12" id="email" type="email" placeholder="Enter email address" aria-required="true">
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="btn btn-primary" id="submit" type="submit">Submit</div>
</div>
</div>
</form>
any help on disabling my submit button until input fields are not validated/filled is much appreciated. Again, new to django and I am unable to use existing threads on said topic
From your current code, looks like your selector for the submit input is not actually getting the submit "button". Currently, your template defines the submit as a div and not an input, thus your selectors should be $("div[type=submit]") not $("input[type=submit]")
Better yet, just select by div id $('#submit')
Instead of targeting attributes, I was targeting props. Below is the fix for my particular issue.
if (inputsWithValues === 3) {
$("div[type=submit]").attr("disabled", false);
} else {
$("div[type=submit]").attr("disabled", 'disabled');
}
I have these snippets of code :
$scope.createPack = function(informationsPack, informationsActivite) {
PackService.add(informationsPack, informationsActivite)
.then(function(res) {
$state.go('packs.list');
}, function(error) {
alert('error : ' + error);
})
};
<form name="packAddForm" id="packAddForm" class="form-horizontal">
<div ng-repeat="item in items">
Jour {{ item.jour }}
<div class="form-group">
<div>
<input type="text" id="nom_activite" class="form-control" placeholder="Nom Activité"
ng-model="informationsActivite.name_activity">
</div>
</div>
<div class="form-group">
<div>
<textarea name="description_activite" id="description_activite" cols="60"
rows="5" ng-model="informationsActivite.description_activity"></textarea>
</div>
</div>
</div>
</form>
<button type="button" class="btn btn-primary" data-dismiss="modal"
ng-click="createPack(informationsPack, informationsActivite)">
Enregistrer</button>
What I'm trying basically to do is generating 1, 2 or 3 input based on what the user gave. And that is what the ng-repeat is doing. But the problem is when I submit the form how can I get all the values of the generated inputs. If it was just one input it would be ok. But for example if I have 2 informationsActivite.name_activity generated how can I get all datas. I really need help.
I think you need to do something like this
<div>
<textarea name="description_activite{{$index}}"
id="description_activite{{$index}}" cols="60" rows="5"
ng-model="informationsActivite.description_activity{{$index}}"></textarea>
</div>
to make these attribute values unique.
Side note- duplicate id attributes in a html document makes it invalid
I'm trying to do some basic form validation in Angular. I have the following code for my form:
<div class="col-xs-12 col-md-6" ng-controller="contactFormCtrl">
<form class="contact-form" ng-show="formVisible" novalidate>
<div class="form-group">
<label for="name">Name</label><small> Required</small>
<input type="text" class="form-control" ng-model="contact.name" id="name" placeholder="Name" required>
<div ng-show="nameEmpty">Please enter your name</div>
</div>
<div class="form-group">
<label for="email">E-mail</label><small> Required</small>
<input type="email" class="form-control" ng-model="contact.email" id="email" placeholder="E-mail" required>
<div ng-show="emailEmpty">Please enter your e-mail address</div>
</div>
<div class="form-group">
<label for="tel">Telephone</label>
<input type="text" class="form-control" ng-model="contact.tel" id="tel" placeholder="Telephone">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="5" ng-model="contact.message" required></textarea>
</div>
<input type="submit" ng-click="submit(contact)" class="btn btn-success" value="Submit">
<input type="button" ng-click="reset()" class="btn btn-primary" value="Reset">
</form>
<div ng-show="submissionSuccess">
<h4>Your message was sent successfully! We'll get back to you as soon as possible</h4>
<button class="btn btn-info" ng-click="reset()">Send another message</button>
</div>
</div>
And the following code in my controller:
$scope.contact = {};
$scope.formVisible = true;
$scope.userEmpty = false;
$scope.emailEmpty = false;
$scope.submit = function(contact) {
if (typeof $scope.contact.name != 'undefined' && typeof $scope.contact.email != 'undefined'){
$http.post('php/contact.php', contact)
.success(function(){
$scope.submissionSuccess = true
$scope.formVisible = false
})
} else if (!$scope.contact.name) {
$scope.nameEmpty = true
} else if (!$scope.contact.email) {
$scope.emailEmpty = true
}
}
The form already highlights empty or erroneously formatted fields in red, but now I'm trying to prevent submission of an invalid form too. My thought was to check if the $scope.contact.user and $scope.contact.email variables were undefined, and go from there. However, when I run this and try and submit and empty form, I get an error:
TypeError: Cannot read property 'name' of undefined
However, if I enter something in the Name field, then submit with an empty e-mail, it works as expected. This leads to think it's an initialization problem, but I thought I'd initialized the variable in the first line of my controller with $scope.contact = {}.
What am I doing wrong?
Codeschool provide full tutorial about form validation, so watch it and do it.
First button near to the will execute ng-submitt="SOMEmETHOD" in tag. Thru the name of the form get $valid property and use this condition to disabled button. also use out of box angular validation methods in form of clear and easy to use directives like ng-minlenght. For live http requests use watcher or assync
$scope.$watch('contact.email',function(newValue, oldValues){
if(newValue !== undefined){
$timeout(function(){
REQUEST.success(function(){
scope.reqs = 'this is it'
})
},600);
}
});
_.isEmpty required underscore.js
$scope.test = "Test";
angular.isUndefined($scope.test); // false
angular.isUndefined($scope.test.newField); // true
_.isEmpty($scope.test); // false
$scope.test = "";
angular.isUndefined($scope.test); // false
_.isEmpty($scope.test); // true
$scope.myObject = {};
angular.isUndefined($scope.test); // false
_.isEmpty($scope.myObject ); // true
But I see all correct in your code. If you initialize $scope.contact={} before function submit is called, the error shouldn't appear. So, or you call the function submit and after you initialize $scope.contact or in some point you overwrite the value and after you call the function.