Saving dynamically generated inputs grid with the same ng-model - javascript

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

Related

using javascript to specify an html button that only has type, name, and value

I have multiple html forms similar to the one below
<div class="container">
<div class="card">
<div class="card-header bg-danger">
<h3 class="card-title">Form Four</h3>
</div>
<div class="card-body">
<div class="errors">
<!-- Error messages can go here -->
</div>
<form novalidate>
<div>
<label for="password">Password : </label>
<input type="text" name="password" id="password" class="password" />
</div>
<div>
<label for="requiredPassword">Required and Password : </label>
<input type="text" name="requiredPassword" id="requiredPassword" class="required password" />
</div>
<div>
<input type="submit" name="submitBtn" value="Validate" />
</div>
</form>
</div>
</div>
</div>
I am not allowed to change them. The issue I am having is that I can't get my event listeners to work. I am trying to have the button clicked for the specific form only validate that form and not the others.
This is what I have been trying to possibly work with based on other projects I have done with multiple buttons
document.querySelectorAll("input[name=submitBtn]").forEach(item => {
item.addEventListener('click', isAllValid)
//isAllValid is a function to check the inputs in the form
});
This isn't working, and I really need help trying to find out how to make this work. Thank you!
To find the form that belongs to the button, inside isAllValid, you can do this:
function isAllValid(event) {
const btn = event.target;
const form = btn.closest('form');
// ...
}
One of the attributes of form elements is form which returns a reference to the form to which each of these elements belongs.
See the following example with multiple forms.
var buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", (event) => {
event.preventDefault();
var msg = event.currentTarget.textContent;
var form = event.currentTarget.form;
console.log("'" + msg + "' clicked (" + form.id + ")");
return false;
});
});
button {
margin: 0.5rem;
}
<section>
<form id="firstForm" name="firstForm">
<button id="firstFormButton1">Button 1 (Form 1)</button>
<button id="firstFormButton2">Button 2 (Form 1)</button>
<button id="firstFormButton3">Button 3 (Form 1)</button>
</form>
</section>
<section>
<form id="secondForm" name="secondForm">
<button id="secondFormButton1">Button 1 (Form 2)</button>
<button id="secondFormButton2">Button 2 (Form 2)</button>
<button id="secondFormButton3">Button 2 (Form 2)</button>
</form>
</section>
<section>
<form id="thirdForm" name="thirdForm">
<button id="thirdFormButton1">Button 1 (Form 3)</button>
<button id="thirdFormButton2">Button 2 (Form 3)</button>
<button id="thirdFormButton3">Button 3 (Form 3)</button>
</form>
</section>

How to add dynamic field types to Angular FormArray?

I am trying to build a block editor type form in Angular. I want this form to be just one array of dynamic fields. I have the following code so far but the button to add different fields always adds all fields instead of the one it should. How can I add only that specific field to the array? What is the best approach to develop this kind of form?
Form TS
storyForm = this.story.group({
blocks: this.story.array([]),
});
get blocks() {
return this.storyForm.get('blocks') as FormArray;
}
Buttons to add different fields to the above array
addHeading() {
this.blocks.push(this.story.group({
heading: [''],
}));
}
addParagraph() {
this.blocks.push(this.story.group({
paragraph: [''],
}));
}
HTML Template
<div class="form-group" formArrayName="blocks">
<div *ngFor="let piece of blocks.controls; let i=index">
<textarea class="form-control" rows="8" placeholder="heading" formControlName="heading" ></textarea>
<textarea class="form-control" rows="8" placeholder="paragraph" formControlName="paragraph" ></textarea>
</div>
</div>
<button type="button" class="btn btn-secondary" (click)="addParagraph()">Add Paragraph</button>
<button type="button" class="btn btn-secondary" (click)="addHeading()">Add Heading</button>

keep properties after jquery.load

I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question

jqWidgets: How can I post an HTML form inside a jqxWindow?

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.

How to make php content appear in a html div element

I am trying to create a search using ajax and mysql and placing the returned data into a div. I am following a tutorial on youtube and so far so good, however I am trying to pass in dummy data into the div but it isn't appearing.
This here is my jquery
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#search').text(data);
});
}
});
This is my html
<div class="container">
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" method="POST">
<input type="text" name="search" id="search" class="form-control" placeholder="Search">
</form><!-- /form -->
<button class="btn btn-lg btn-primary btn-block btn-signin" value= "search" type="required" id="submit" name="submit">Search</button>
</div><!-- /card-container -->
<div class="row">
<div class="col-md-4">
<div id="search"></div>
<div class="caption">
<p></p>
</div>
</div>
When the user clicks search the content from the searching.php file should appear in the div. Currently in the searching.php file it just has echo"content";. It should have "content" in the div but it isn't appearing in the web browser and there are no errors. Within the network in inspect element the name is searching.php and the status is ok. Not sure where I am going wrong, any help would be grateful.
You have multiple id="search" elements in your HTML. So this isn't going to know which one you mean:
$('#search')
It's probably trying to set the "text" of the <input>, which doesn't have a "text" (it has a "value"). Correct the HTML. Either change the <input> or the <div> to have a unique id. (And, of course, update your jQuery selectors as well as anything else targeting these elements.)
don't use same id (search) for both input and div
change the id in html
<div class="container">
<div class="card card-container">
<p id="profile-name" class="profile-name-card"></p>
<form class="form-signin" method="POST">
<input type="text" name="search" id="search" class="form-control" placeholder="Search">
</form>
<button class="btn btn-lg btn-primary btn-block btn-signin" value= "search" type="required" id="submit" name="submit">Search</button>
</div><!-- /card-container -->
<div class="row">
<div class="col-md-4">
<div id="searchText"></div>
<div class="caption">
<p></p>
</div>
</div>
and javascript
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#searchText').text(data);
});
}
});
.text not work with input
use val() instead of text() for input
$('#search').val(data);
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<button id="btn1">Set Text</button>
<p id="test2">This is another paragraph.</p>
<button id="btn2">Set HTML</button>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button id="btn3">Set Value</button>

Categories

Resources