How to use map properly? - javascript

I have this method:
getAnnouncements() {
this.restService.get('announcement').subscribe(data => {
this.announcements = data['payload'];
this.optionsFromDb = this.announcements;
this.options = this.optionsFromDb.map(option => ({checked: false, code: option.code, name: option.name}));
});
}
In html I have this:
<div class="form-group" *ngFor="let option of options">
<label class="checkbox-inline custom-checkbox nowrap">
<input type="checkbox" [checked]="option.checked" (change)="option.checked = !option.checked" />
<span>{{option.name}}</span>
</label>
</div>
getListOfChecked() {
return this.options.map( announcement => announcement.checked );
}
What I want is to display this option.name in html, but remove it from options. Any suggestion how can I do that? Because my post function receives only checked and code, not a name, thats why i want to remove it

If I understand, you want to display the name, but remove it before you send it to your web service, right ?
If you want to use map to do that, just do
let paylaodToSendToBackend = this.options.map(option => ({ checked: option.checked, code: option.code }));
before your HTTP call.

Related

Unable to redirect to homepage after posting a form - Express,EJS and JS

I have a view which contains a form and looks like this,
<form class="flex-form" id="form" method="">
<div class="form-component">
<label>Type</label>
<input type="text" id="type" name="type">
</div>
<div class="form-component">
<div class="form-component"><label><b>Contents</b></label></div>
<label>Savoury</label><input type="text" name="savoury" id="savoury">
<label>Fillings</label><input type="text" name="fillings" id="fillings">
<label>Amount</label><input type="text" name="amount" id="amount">
<div class="flex-component">
<button class="set-button" type="button" id="set">Set Item</button>
</div>
</div>
<div class="form-component">
<label class="description-label">Description</label>
<textarea class="fixed-textarea" id="description" name="description" cols="15" rows="10"></textarea>
</div>
<div class="form-component">
<label >Unit Price</label>
<input type="text" id="price" name="unit_price">
</div>
<div class="flex-component">
<button class="form-button" type="submit">Add</button>
</div>
</form>
I have a JavaScript that allows me to capture some intermediary information (via the Set Item button) from the form before the form gets submitted (via the Add Button). I want to handle the form's submission from the script since I need to capture the intermediary data.
let collectedItems = [];
let setter = document.getElementById('set');
let form = document.getElementById('form');
setter.addEventListener('click',getSetContent);
function getSetContent() {
let type = document.getElementById('savoury');
let fillings = document.getElementById('fillings');
let amount = document.getElementById('amount');
const content = {
type: type.value,
fillings: fillings.value.split(','),
amount: Number(amount.value)
};
collectedItems.push(content);
clearInputFields([type,fillings,amount]);
}
function clearInputFields(inputFields) {
inputFields.forEach(field => {
field.value = ''
});
console.log(collectedItems);
}
form.addEventListener('submit',submitForm);
function submitForm() {
const type = document.getElementById('type').value;
const desc = document.getElementById('description').value;
const price = Number(document.getElementById('price').value);
const content = collectedItems;
const data = {
type: type,
contents: content,
description: desc,
unit_price: price
};
post('http://localhost:8001/add/box',
{ 'Content-Type': 'application/json' },
JSON.stringify(data)
);
}
function post(endpoint,header,body) {
const response = fetch(endpoint,{ method: 'POST',headers: header,body: body });
response.then(
resp => {
if (resp.ok) {
console.log('form submitted');
} else {
console.log('form not submitted');
}
}
)
}
I then make a POST request using fetch() to an endpoint I have setup in Express which looks like this,
app.post('/add/box',(req,res) => {
const box: any = req.body;
console.log(box);
// DO SOME DB STUFF
res.redirect('/');
});
The form submission works as intended (logs to terminal using nodemon), however I am unable to redirect to the homepage. Instead I stay on the form page after the submission has occurred and I can't figure out why. Any help with this issue is much appreciated.

Pass parameters via GET to return filter

I want to return a data query via GET to return me values according to what is selected in the v-model.
I would like to know how to get the v-model values from the input and make the request to get by parameter
My filter (the components are already returning object as your id according to what I select)
<div class="row gutter-sm">
<div class="col-md-12">
<q-card class="full-width bg-white q-pa-md q-card-flex">
<div class="col-md-2">
<situacao-select multiple v-model="situacao" :stackLabel="'Situação OS'" style="height:50px;" :clearable="true" />
</div>
<div class="col-md-2">
<input-holder label="Help Desk" style="height:50px;">
<pessoa-funcao-select :funcao="'Help Desk'" :clearable="true" />
</input-holder>
</div>
<div class="col-md-2">
<input-holder label="Supervisor" style="height:50px;">
<pessoa-funcao-select :funcao="'Supervisor'" :clearable="true" />
</input-holder>
</div>
<div class="col-auto">
<q-btn
color="primary"
style="margin-left: auto; margin-right: auto;"
#click="search = false"
>FILTER</q-btn>
</div>
</div>
</q-card>
Request the API (I know it is wrong, I would like to know how to request with the parameter according to what the GET requests)
mounted() {
this.refresh()
},
methods: {
refresh () {
this.$axios.get()
this.$axios.get("/Operacional/GetRelatorio").then(res => {
this.prazos = res.data
this.$refs.chart1.updateSeries([{
name: 'NO PRAZO',
data: [this.prazos.noPrazo, this.prazos.emDia, this.prazos.atrasadas]
}])
})
this.$axios.get("/Operacional/GetAprovadas").then(res => {
this.os = res.data
})
this.$axios.get("/Operacional/GetPendenciasOS").then(res => {
this.os = res.data
this.$refs.chart4.updateSeries([{
name: 'EM DIA',
data: [ this.os.emdiaPendencia, this.os.emdiaSPendencia],
},{
name: 'ATRASADAS',
data: [ this.os.atrasadasPendencia, this.os.atrasadasSPendencia],
}
])
})
This is how you get that value you selected, let's say you want to use 'situacao'.
and pass that value to your backend via GET parameters:
refresh () {
this.$axios.get()
var selectedSituacao = this.situacao;
var url = "/Operacional/GetRelatorio?ID=" + selectedSituacao;
this.$axios.get(url).then(res => { .... })
// or you could do this:
var axiosParams = {
params: {
ID: selectedSituacao
}
}
this.$axios.get("/Operacional/GetRelatorio", axiosParams).then(res => { .... })
edit: Updated url get parameter situacao to ID as requested.

How to use ion-autocomplete

I am using ion-autocomplete in my project and here is what I want to do:
Here is the input field:
<label class="item item-input item-stacked-label">
<span class="input-label">Multiple select autocomplete</span>
<input ion-autocomplete type="text" readonly="readonly"
class="ion-autocomplete" autocomplete="on"
ng-model="model"
item-value-key="lastname"
item-view-value-key="firstname"
items-method="getTestItems(query)"
items-method-value-key="items"
placeholder="Enter test query ..."
items-clicked-method="itemsClicked(callback)"
items-removed-method="itemsRemoved(callback)" />
</label>
Here is the controller:
$scope.getTestItems =function (query) {
if (query) {
return {
items: [
{"matricule":"5324", "id":270, "lastname":"IZIKKI", "firstname"‌​:"SAID"},
{"matricule":"5505", "id":271, "lastname":"BOUKASIM", "firstnam‌​e":"EL MAACHI"},
{"matricule":"5505", "id":272, "lastname":"BELMOUMENE‌​", "firstname":"MHAME‌​D"}
]
};
}
return {
items: []
};
};
What I want to do is, I want to do search by matricule. In other words, when I type 5324, I want to the last name and the first name associate to this matricule appear in the list. When I click done, I want to that appear in the model.
How can I achieve that please?

AngularJS: View is updated properly but not the model

I have a problem when implementing a nested list in Angular: the view gets updated properly but, on the other side, the code is not updated on change.
I think it will be much clearer with the code:
_this.categories = injections.map(function (category) {
return {
title: category.get('title'),
object: category,
criteria: category._criteria.map(function (oneCriteria) {
return {
object: oneCriteria,
type: oneCriteria.get("type"),
min: _this.range(oneCriteria.get("range")).min,
max: _this.range(oneCriteria.get("range")).max,
key: oneCriteria.get("key"),
value: _this.range(oneCriteria.get("range")).min,
defaultValue: _this.range(oneCriteria.get("range")).min,
selected: false
}
})
}
});
_this.category = _this.categories[0];
_this.job = {
title: '',
description: '',
salaryAmount: 0,
salaryTimeUnit: _this.salaryTimeUnits[0],
category: _this.category.object,
criteria: _this.category.criteria,
location: {latitude: 48.137004, longitude: 11.575928}
};
So and, very quick here is my HTML:
<div ng-repeat="category in controller.categories">
<input type="radio" name="group" ng-value="category.object.get('title')" id="{{category.object.get('title')}}"
ng-checked="controller.category == category" ng-click="controller.category = category">
{{category.title}}
</div>
<br>
Criteria:
<div ng-repeat="criterium in controller.category.criteria">
<div class="row vertical-align">
<div class="col-xs-9">
<span ng-click="criterium.selected = !criterium.selected"
ng-class="['list-group-item', {active:criterium.selected == true}]">{{criterium.key}}</span>
</div>
</div>
</div>
The problem is the following: the value are getting updated in the view (when you click on a radio button on the category, you see the corresponding criteria(s)). But the job is for one reason that I ignore not updated although it has the same reference as the HTML (a reference to this category.criteria).
Did I miss something?
controller.job.criteria is still just a reference to controller.categories[0]. Your code should successfully update controller.category to point at whichever category you clicked on, but that does not also update the reference in your job data structure.
What you want to do is make your ngClick event a bit more robust, i.e.:
<input type="radio" ng-click="controller.updateCategory(category)" />
and then in your js:
_this.updateCategory = function (category) {
_this.category = category;
_this.updateJob(category);
};
_this.updateJob = function (category) {
_this.job.category = category.object;
_this.job.criteria = category.criteria;
};
This will update the references in your job to match the new jazz.
I would, however, recommend leveraging ngModel and ngChange in your radios instead. Like:
<input type="radio" ng-model="controller.category" ng-value="category" ng-change="updateJob(category)" /> {{category.title}}

Laravel - Check if username already exists before submitting form with jQuery AJAX

I've made a registration form with a lot of fields. Since when I submit data and the validator redirects back with errors some inputs are empty and the user has to lose time refilling them, I want to implement some front-end validations.
I'm stuck on checking if an username is already used on submit button press becasuse I'm not expert about AJAX.
In the AuthController I've created a function that returns a Json containing a response in relation of existence or not of the username in the database.
class UserAuthController extends Controller
{
public function isUserNameInUse( $username )
{
if (Auth::where('username', $username) != null){
return [ 'is_used' => 1 ];
}
return [ 'is_used' => 0 ];
}
}
In the routes.php there are these lines:
Route::group([ 'as' => 'api', 'prefix' => 'api', 'namespace' => 'Api'], function () {
Route::group([ 'as' => 'auth', 'prefix' => 'auth'], function () {
Route::any('/is_username_in_use/{username}', [
'as' => 'isUserNameInUse',
'uses' => 'UserAuthController#isUserNameInUse']);
});
});
The view is like that (only a piece of the form):
<form action="{{ route('web.company.postSignup') }}" method="post" id="signup-form" class="form-horizontal">
{!! csrf_field() !!}
#include( 'errors.handler' )
<label for="username">
{{ _('Username*') }} </label>
<input type="text" class="form-control" name="username" id="username"
value="{{ Input::old('username') }}" required>
<label for="password">
{{ _('Password*') }}
</label>
<input type="password" class="form-control" name="password" id="password"
value="{{ Input::old('password') }}" onchange="form.confirmPassword.pattern = this.value;"
required>
<label for="confirmPassword">
{{ _('Confirm Password*') }}
</label>
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" required>
<button class="btn btn-warning" id="submit-btn" type="submit">{{ _('Sign Up') }}</button>
</form>
This is the script, for now I've only tried to log the response of the controller, but it prints anything.
$(document).ready(function () {
$('form#signup-form').submit(function () {
var input_username = $('input[name=username]').val();
console.log(input_username);
$.getJSON('/api/auth/is_username_in_use/' + input_username, function (json) {
console.log(json);
});
return false;
});
});
There is no need to make an explicit check if user name is in use. You may skip this part and instead, when you storing your user's data validate them accordingly.
An example of this might be
public function store(Request $request)
{
$this->validate($request, [
'username' => 'required|unique:users',
'password' => 'required|confirmed'
]);
// process your logic
}
This way, if validation failed, you'll get a json response object containing error messages.
Note, this will work if you're on Laravel 5. If you are on 4.* refer to documentation for validation part.
You should change return [ 'is_used' => 0 ]; into return Response::json([ 'is_used' => 0 ]); and add use Response; to the top of your controller.

Categories

Resources