How to take selected dropdown value in Angular 8 for ngSubmit()? - javascript

In my project I am using Angular 8.
Created method to bind user to project according to their id, tested with postman back end functionality works properly.
My service for bindUser method:
bindUserToProject(userId: number, projectId: number) {
const seperator = "/";
const body = { userId, seperator, projectId };
return this.http.post(this.baseUrl + '/bind/', body)
}
Component:
export class AddProjectForUserComponent implements OnInit {
users: any = {};
projects: any = {};
constructor(private router: Router, private projectService: ProjectService, private vmService:
VmService, private userService: UserService) { }
ngOnInit() {
this.users = this.getUsersForProject()
this.projects = this.getProjects()
}
getUsersForProject() {
this.projectService.getUsersForProject().subscribe(u => this.users = u);
}
getProjects() {
this.vmService.getProjectsForVm().subscribe(p => this.projects = p)
}
goBackToUserProjects() {
this.router.navigate(["/user-projects"])
}
bindUserToProject(userId: number, projectId: number) {
this.userService.bindUserToProject(userId, projectId);
}
HTML:
<div class="bindProject">
<form #bindProject="ngForm" (ngSubmit)="bindUserToProject()">
<h2 class="text-center text-primary">Bind User to Projects</h2>
<div class="input-group mt-1">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-dot-circle text-info"></i> Users
</div>
</div>
<select name="userId" [(ngModel)]="users.userId" class="form-control" required>
<option disabled>-Please choose User-</option>
<option *ngFor="let item of users" [ngValue]="item.userId">
{{ item.userName }}
</option>
</select>
</div>
<div class="input-group mt-1">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="fas fa-dot-circle text-info"></i> Projects
</div>
</div>
<select name="projectId" [(ngModel)]="projects.projectId" class="form-control" required>
<option disabled>-Please choose Projects-</option>
<option *ngFor="let item of projects" [ngValue]="item.projectId">
{{ item.projectName }}
</option>
</select>
</div>
<div class="form-group mt-1">
<button [disabled]="!bindProject.valid" class="btn btn-success btn-sm mr-5" type="submit"><i
class="fas fa-plus"></i> Add</button>
<button (click)="goBackToUserProjects()" class="btn btn-sm btn-outline-success"><i
class="fas fa-tasks"></i> Go back to user projects</button>
</div>
</form>
</div>
Question is how can I get selected id from both dropdown and pass it to my bindToProject() method.

You should bind the select values with some variables say selectedProject and selectedUser.
app.component.ts :
selectedUser : number;
selectedProject : number;
bindUserToProject() {
this.userService.bindUserToProject(this.selectedUser, this.selectedProject);
}
app.component.html :
<select name="userId" [(ngModel)]="selectedUser">
<option disabled>-Please choose User-</option>
<option *ngFor="let item of users" [ngValue]="item.userId">
{{ item.userName }}
</option>
</select>
<select name="projectId" [(ngModel)]="selectedProject">
<option disabled>-Please choose Projects-</option>
<option *ngFor="let item of projects" [ngValue]="item.projectId">
{{ item.projectName }}
</option>
</select>
Demo : https://stackblitz.com/edit/angular-3udq1g

Define a variable in your component called something like selectedUserId, change [(ngModel)]="users.userId" to [(ngModel)]="selectedUserId". Then in bindUserToProject() you can access that value directly from the component.
You can do the same for the projects dropdown.

try like this
<form #bindProject="ngForm" (ngSubmit)="bindUserToProject(bindProject.value)">
<select name="userId" class="form-control" ngModel required>
<option disabled>-Please choose User-</option>
<option *ngFor="let item of users" [ngValue]="item.userId">
{{ item.userName }}
</option>
</select>
<select name="projectId" class="form-control" ngModel required>
<option disabled>-Please choose Projects-</option>
<option *ngFor="let item of projects" [ngValue]="item.projectId">
{{ item.projectName }}
</option>
</select>
<button type="submit">
Add
</button>
</form>
component
bindUserToProject({userId, projectId}) {
this.userService.bindUserToProject(userId, projectId);
}
bindUserToProject will get the hole form value but this {userId, projectId} is ES2015 feature called destruction
demo 🚀

In case someone has same issue my service also was wrong which threw exception json Parser.
I changed this one to and it worked fine:
bindUserToProject(userId: number, projectId: number) {
return this.http.post(this.baseUrl + '/bind/' + userId + "/" + projectId, {})
}

These are the following step of solution-:
Initialize two variable for userId and projectId.
Apply these variable in ngModel like [(ngModel)]="UserId" and [(ngModel)]="projectId"
use (ngSubmit)="bindUserToProject()"
In component file use initialized variables in bindUserToProject() function.
Select dropdown and click Submit.
Now, you have a selected value in your variable.

Related

Angular: Show value in a select

I have two select and I show value if they exist:
page.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
customer: any = {
city: '',
state: '',
};
ngOnInit() {
// I recover this info from BE
this.customer.state = 'England';
this.customer.city = 'London';
}
}
page.html
<div class="col configurator-form-input col-12 col-md-6">
<label class="text">State *</label>
<div
class="input-group input-error"
[ngClass]="
customer.state ? 'input-group input error' : 'input-group input-error'
"
>
<select
id="state"
class="form-control"
[(ngModel)]="customer.state"
[ngModelOptions]="{ standalone: true }"
(change)="onChangeProvinceForState($event.target.value)"
appTab
tabIndex="14"
>
<option disabled value="">Select State</option>
<option
*ngFor="let state of stateList"
ngDefaultControl
[value]="state.name"
>
{{ state.name }}
</option>
</select>
</div>
</div>
<div class="col configurator-form-input">
<label class="text">City *</label>
{{ this.customer.city }}
<div
class="input-group input-error"
[ngClass]="customer.city ? 'input-group' : 'input-group input-error'"
>
<!-- <span class="fake-option" *ngIf="existingCustomer">{{customer.city}}</span> -->
<select
id="city"
name="city"
class="form-control"
[(ngModel)]="customer.city"
[ngModelOptions]="{ standalone: true }"
appTab
tabIndex="15"
>
<option value="">Select City</option>
<option *ngFor="let city of citiesList" ngDefaultControl [value]="city">
{{ city }}
</option>
</select>
</div>
</div>
https://stackblitz.com/edit/angular-wyendp?file=src/app/app.component.html
I recover the city and state from an api call, but I don't understand how to show in the select directly
EDIT:
onChangeStateForCity(e) {
console.log("e ", e)
let countiesObservable = this.citiesService.getAllState();
countiesObservable.pipe(untilDestroyed(this)).subscribe((data: any) => {
this.citiesList = data[e];
});
}
You are missing the declaration of properties stateList and citiesList. I have modified your SB, to generate some static dropdown down options. You can easily assign these variables to the response you get from your API.
Stackblitz demo
app.component.ts (defined the variables):
stateList = [
'England',
'France'
]
citiesList = [
'London',
'Paris'
]
app.component.html (bind them in template):
<option *ngFor="let state of stateList" ngDefaultControl [value]="state">
<option *ngFor="let city of citiesList" ngDefaultControl [value]="city">
Just add array of stateList and citiesList.
stateList = [{ name: 'England' }];
citiesList = ['London'];

Creating a dropdown that dynamically creates another dropdown in Laravel

I'm fairly new to Laravel (and I love it!) I'm trying to do something a bit complicated: Creating a drop-down menu that upon selection of an option -will display a second drop-down menu that will give further options dynamically based on the previous selection.
My controller looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Manufacturer;
use App\GearCategory;
use App\SubCategory;
use App\GearItem;
class GearItemController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create(Manufacturer $manufacturers, GearItem $gearItem, GearCategory $gearCategory, SubCategory $subCategory)
{
// dd($gearCategory->all());
$catNum = 6; // <-- needs to be equal to the dispaly div name. Hard coded as 6 for test purposes.
$gearCategory = $gearCategory->all();
$subCategory = $subCategory::where('gear_categories_id', $catNum)->get();
$manufacturers = $manufacturers->all();
return view('gearitem.create', compact('gearCategory'), compact('subCategory'), compact('manufacturers'), compact('gearItem'));
}
}
My blade looks like this:
<div class="card-header">
<h3>Add a new gear Item</h3>
</div>
<div class="container">
<select name="gear_categories_id" id="gear_categories_id" class="custom-select mb-3 mt-3"
onchange="selector('display_div', this)">
<option value="" selected>Choose category</option>
#foreach ($gearCategory as $category)
<option id="cat_selector" value="{{ $category->id }}"
{{ (old("gear_categories_id") == $category->id ? "selected" : "") }}>{{ $category->name }}
</option>
#endforeach
</select>
</div>
<script>
"use strict"
function selector(divId, element) {
console.log(element.value);
document.getElementById(divId).setAttribute("name", element.value)
}
</script>
<div class="display_div container" id="display_div" name="">
<select name="sub_categories_id" id="sub_categories_id" class="custom-select mb-3 mt-3"
onchange="selector('display_div', this)">
<option value="" selected>Choose item's type</option>
#foreach ($subCategory as $scategory)
<option id="cat_selector" value="{{ $scategory->id }}"
{{ (old("sub_categories_id") == $scategory->id ? "selected" : "") }}>{{ $scategory->name }}
</option>
#endforeach
</select>
</div>
(Sorry for using vanilla JS i haven't gotten into Vue yet...) I'm trying to pass the name of the "display_div" onto the $catNum variable in the controller (set to "6" just to test if it works but should be set to whatever the user is choosing on the first dropdown) The values of the 'gear_categories_id' appear as a foreign key in the SubCategory model and if i'll manage to feed these values to the second dropdown it would work. I've been struggling for hours with it and I can't figure it out... Please help and sorry for being such a n00b.
You can use an AJAX request on change of the parent category drop-down to populate the subcategories. See the code below. I have added a second route to get subCategories for a specific categoryID.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Manufacturer;
use App\GearCategory;
use App\SubCategory;
use App\GearItem;
class GearItemController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create(Manufacturer $manufacturers, GearItem $gearItem, GearCategory $gearCategory, SubCategory $subCategory)
{
// dd($gearCategory->all());
$catNum = 6; // <-- needs to be equal to the dispaly div name. Hard coded as 6 for test purposes.
$gearCategory = $gearCategory->all();
$subCategory = $subCategory::where('gear_categories_id', $catNum)->get();
$manufacturers = $manufacturers->all();
return view('gearitem.create', compact('gearCategory'), compact('subCategory'), compact('manufacturers'), compact('gearItem'));
}
public function getSubCategories($categoryID) {
return SubCategory::where('gear_categories_id', $categoryID)->get();
}
}
Route::get('/sub-categories/{categoryID}', 'GearItemController#getSubCategories');
<div class="card-header">
<h3>Add a new gear Item</h3>
</div>
<div class="container">
<select name="gear_categories_id" id="gear_categories_id" class="custom-select mb-3 mt-3"
onchange="selector('display_div', this)">
<option value="" selected>Choose category</option>
#foreach ($gearCategory as $category)
<option id="cat_selector" value="{{ $category->id }}"
{{ (old("gear_categories_id") == $category->id ? "selected" : "") }}>{{ $category->name }}
</option>
#endforeach
</select>
</div>
<script>
"use strict"
function selector(divId, element) {
console.log(element.value);
document.getElementById(divId).setAttribute("name", element.value);
fetch('/sub-categories/')
.then(res => res.json())
.then(subCategories => {
var options = subCategories.reduce( (opts, cat) =>
`${opts}<option value="${cat.id}">${cat.name}</option>`, "");
document.getElementById("sub_categories_id").innerHTML = `<option value="" selected>Choose item's type</option>${options}`;
});
}
</script>
<div class="display_div container" id="display_div" name="">
<select name="sub_categories_id" id="sub_categories_id" class="custom-select mb-3 mt-3"
onchange="selector('display_div', this)">
<option value="" selected>Choose item's type</option>
</select>
</div>

How to get the div id's of this form?

Working on an app that exports what the user typed on the app to a particular website with the similar components. For example, if the user typed a title on the app, when he presses a button, it imports that value to a webpage which also requests the user to type.
This is the flow chart or something
User --> User inputs a text in the app --> App copies what the user's typed --> App opens a particular website --> App pastes what he copied to the website.
(Website: A google form for an example.)
Now I've already finished all of it except for the latter part where the app pastes what he copied.
The problem is the app do not know where to paste it.
So I want to get the ID's of the code below, it is perfectly fine if you just identify all the id's or something similar and how to call it.
Have imported data from backend successfully, but have zero clue on how to get the id's or the variable names of a textarea, radio buttons, the div.
javascript:
(function () {
function WW(ele, val)
{
if(document.getElementById(ele) && val != "")
{
document.getElementById(ele).value = val;
}
}
WW("story-title", "The Good Peacock");
)();
Copied this from someone.
This works with other sites that have the an id, like:
<textarea id="story-title">
So, need to know the id's of the HTML below.
This is a part of the source code of the website, which is auto-fill.
Tried calling with getElementByClassName(), but didn't work.
<form class="main-edit-form">
<div class="required-form-wrapper">
<div class="form-group title-form">
<label>Title</label>
<span class="empty-warning hidden" id="title-warning">Required</span>
<div contenteditable="true" class="story-title">Untitled Story</div>
</div>
<div class="form-group description-form">
<div class="form-wrapper">
<label>Description</label>
<span data-toggle="popover" class="popover-icon" id="description-tooltip" title="" data-original-title="Add a story description"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="empty-warning hidden" id="description-warning">Required</span>
</div>
<textarea type="text" name="title" class="story-description "></textarea>
</div>
<div class="form-group tags-form">
<div class="form-wrapper">
<label>Tags</label>
<span data-toggle="popover" class="popover-icon" id="tags-tooltip" title="" data-original-title="Help readers find your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="empty-warning hidden" id="tag-empty-warning">Required</span>
</div>
<div class="tag-container">
<div id="editable-tags">
<div class="component-wrapper" id="component-TagGrid-storyTags-/myworks/new"></div>
</div>
<div id="add-tag" class="tag-item with-icon on-add-tag">
<span>Add a tag</span><span class="fa fa-plus fa-wp-black " aria-hidden="true" style="font-size:12px;"></span>
</div>
<span id="tag-input-wrapper">
<input id="tag-input" class="hidden on-tag-input" placeholder="Separate tags with a space" autocomplete="off">
</span>
</div>
</div>
<div class="form-group inline-form">
<div class="form-wrapper">
<label for="categoryselect">Genre</label>
<span data-toggle="popover" class="popover-icon" id="category-tooltip" title="" data-original-title="Tell Wattpad the genre of your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="categoryselect" class="form-control ">
<option value="-1">Select a genre</option>
<option value="14">Action</option>
<option value="11">Adventure</option>
<option value="24">ChickLit</option>
<option value="6">Fanfiction</option>
<option value="3">Fantasy</option>
<option value="21">General Fiction</option>
<option value="23">Historical Fiction</option>
<option value="9">Horror</option>
<option value="7">Humor</option>
<option value="8">Mystery / Thriller</option>
<option value="16">Non-Fiction</option>
<option value="12">Paranormal</option>
<option value="2">Poetry</option>
<option value="19">Random</option>
<option value="4">Romance</option>
<option value="5">Science Fiction</option>
<option value="17">Short Story</option>
<option value="13">Spiritual</option>
<option value="1">Teen Fiction</option>
<option value="18">Vampire</option>
<option value="22">Werewolf</option>
</select>
<span class="empty-warning hidden" id="category-empty-warning">Required</span>
</div>
</div>
</div>
<div class="inline-form-wrapper">
<div class="inline-form-row">
<div class="form-group inline-form">
<div class="form-wrapper">
<label>Language</label>
<span data-toggle="popover" class="popover-icon" id="language-tooltip" title="" data-original-title="What language is your story in?"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="languageselect" class="form-control ">
<option value="1" selected="selected">English</option>
<option value="2">Français</option>
<option value="3">Italiano</option>
<option value="4">Deutsch</option>
<option value="5">Español</option>
<option value="6">Português</option>
<option value="38">Català</option>
<option value="19">Tiếng Việt</option>
<option value="18">Filipino</option>
<option value="20">Bahasa Indonesia</option>
<option value="22">Bahasa Melayu</option>
<option value="32">ภาษาไทย</option>
<option value="7">Русский</option>
<option value="15">Română</option>
<option value="23">Türkçe</option>
<option value="24">Česky</option>
<option value="14">Polski</option>
<option value="28">Magyar</option>
<option value="30">ελληνικά</option>
<option value="35">Eesti</option>
<option value="36">Latviešu</option>
<option value="37">Lietuvių</option>
<option value="39">Босански</option>
<option value="40">Српски</option>
<option value="41">Hrvatski</option>
<option value="43">Български</option>
<option value="44">Slovenčina</option>
<option value="42">Slovenščina</option>
<option value="45">Беларускі</option>
<option value="46">Українська</option>
<option value="26">Svenska</option>
<option value="27">Norsk</option>
<option value="34">Suomi</option>
<option value="29">Dansk</option>
<option value="13">Nederlands</option>
<option value="33">Íslenska</option>
<option value="12">简体中文</option>
<option value="8">繁體中文</option>
<option value="9">日本語</option>
<option value="10">한국어</option>
<option value="16">العربية</option>
<option value="53">ગુજરાતી</option>
<option value="17">עברית</option>
<option value="21">हिन्दी</option>
<option value="25">മലയാളം</option>
<option value="54">ଓଡ଼ିଆ</option>
<option value="31">فارسی</option>
<option value="55">ਪੰਜਾਬੀ</option>
<option value="56">অসমীয়া</option>
<option value="47">বাংলা</option>
<option value="48">اُردُو‎</option>
<option value="49">தமிழ்</option>
<option value="50">Kiswahili</option>
<option value="51">Afrikaans</option>
<option value="57">मराठी</option>
<option value="11">Other</option>
</select>
</div>
</div>
<div class="form-group inline-form copyright-form">
<div class="form-wrapper">
<label>Copyright</label>
<span data-toggle="popover" class="popover-icon" id="copyright-tooltip" title="" data-original-title="Who owns your story?"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="copyrightSelect" class="form-control ">
<option value="0">Not Specified</option>
<option value="1">All Rights Reserved</option>
<option value="2">Public Domain</option>
<option value="3">Creative Commons (CC) Attribution</option>
<option value="4">(CC) Attrib. NonCommercial</option>
<option value="5">(CC) Attrib. NonComm. NoDerivs</option>
<option value="6">(CC) Attrib. NonComm. ShareAlike</option>
<option value="7">(CC) Attribution-ShareAlike</option>
<option value="8">(CC) Attribution-NoDerivs</option>
</select>
</div>
</div>
</div>
<div class="form-group rating-form">
<div class="form-wrapper">
<label class="rating-label">Rating</label>
<span data-toggle="popover" class="popover-icon" id="rating-tooltip" title="" data-original-title="Rate your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="toggle-prompt">Mature</span>
<div class="onoffswitch ">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="mature-switch">
<label class="onoffswitch-label" for="mature-switch">
<div class="onoffswitch-inner">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
<span class="onoffswitch-switch"></span>
</label>
</div>
</div>
Thank you in advance!
These id's you are looking for are not generated by them self.
You need to assign id to field that you like.
I don't prefer to use id to implement css. Element id is only to be needed to implement javascript and fetch there value example from input tag.
You need to assign id while writing down your code like in following sample html.
Point to note:
Not all tags have id.
Mostly tags related to user input have id.
No 2 elements / tag have same id.
id's of different type of elements are used for different purpose, like <div>, <span> id's are used for show-hide, where as input id's are used for fetching value.
HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/app.css" />
<link rel="icon" href="logo.jpg" />
<title>Info</title>
</head>
<body>
<div class="col-md-6 offset-md-3">
<div class="col-md-6">
<p class="btn btn-primary form-control" onclick="showForm('#addInfo')">Add Detail</p>
</div>
<div class="col-md-6">
<p class="btn btn-primary form-control" onclick="showForm('#showInfo');getDetail();">Show Detail</p>
</div>
<!-- No need for `form` as will use JavaScript for Single Page Application -->
<div id="addInfo" class="hide">
<div id="data"></div>
<div class="col-md-12 form-group">
<label for="addEmail">Email:</label>
<input id="addEmail" class="form-control" type="email">
<span id="addEmailError" class="hide error">Valid Email Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addFname">First Name:</label>
<input id="addFname" class="form-control" type="text">
<span id="addFnameError" class="hide error">Valid First Name Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addLname">Last Name:</label>
<input id="addLname" class="form-control" type="text">
<span id="addLnameError" class="hide error">Valid Last Name Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addPhone">Phone:</label>
<input id="addPhone" class="form-control" type="text">
<span id="addPhoneError" class="hide error">Valid Phone Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addGender">Gender:</label>
<select id="addGender" class="form-control">
<option value="">Select:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="addGenderError" class="hide error">Gender Required</span>
</div>
<div class="col-md-12 form-group">
<p class="btn btn-primary form-control" onclick="addInfo()">Submit</p>
</div>
</div>
<!-- No need for `form` as will use JavaScript for Single Page Application -->
<div id="showInfo" class="hide">
<div id="showDetails" class="col-md-12"></div>
</div>
</div>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<!-- `login.js` is only used in `login.ejs` -->
<script type="text/javascript" src="/js/addInfo.js"></script>
<script type="text/javascript" src="/js/getInfo.js"></script>
<script type="text/javascript" src="/js/service.js"></script>
</body>
</html>
addInfo.js:
"use strict";
function addInfo() {
// JavaScript uses `id` to fetch value
let email = $("#addEmail").val(),
fName = $("#addFname").val(),
lName = $("#addLname").val(),
phone = $("#addPhone").val(),
gender = $("#addGender").val();
// Show error `span` when email is invalid
if ( validateEmail(email) ) {
$("#addEmailError").addClass("hide");
} else {
$("#addEmailError").removeClass("hide");
return;
}
// Show error `span` when First Name is invalid
if ( validateFname(fName) ) {
$("#addFnameError").addClass("hide");
} else {
$("#addFnameError").removeClass("hide");
return;
}
// Show error `span` when Last Name is invalid
if ( validateLname(lName) ) {
$("#addLnameError").addClass("hide");
} else {
$("#addLnameError").removeClass("hide");
return;
}
// Show error `span` when Phone is invalid
if ( validatePhone(phone) ) {
$("#addPhoneError").addClass("hide");
} else {
$("#addPhoneError").removeClass("hide");
return;
}
// Show error `span` when Gender is invalid
if ( validateGender(gender) ) {
$("#addGenderError").addClass("hide");
} else {
$("#addGenderError").removeClass("hide");
return;
}
// Calling local API to set authentication
// Everything in public is visible for hackers
// Thus to hide auth calling local backend
$.ajax({
"url": "/v1/detail",
"method": "POST",
"data": {email, fName, lName, phone, gender}
})
.then( result => {
// On success empty all the input fields.
$("#addEmail").val('');
$("#addFname").val('');
$("#addLname").val('');
$("#addPhone").val('');
$("#addGender").val("");
// Message to notify success submition
alert("Successfully added user.");
return;
})
.catch( err => {
// Notify in case some error occured
alert("An error occured.");
return;
});
}
getInfo.js:
"use strict";
function getDetail () {
// Request to get details of all user.
$.ajax({
"url": "http://localhost:4000/v1/detail",
"method": "GET"
})
.then( result => {
// On success using table to display data.
// This table is dynamic.
let table = `<div class="alert alert-success" role="alert">
Details fetched successfully.
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>`;
let headers = [];
// Setting dynamic headers to ease work at frontend in case field changes
for ( let key in result[0] ) headers.push(key);
for ( let h of headers ) table += `<th scope="col">` + h + `</th>`;
table += ` </tr>
</thead>
<tbody>`;
let i = 1;
// Dynaic rows of table based upon headers.
for(let row of result) {
table += ` <tr>
<th scope="row">` + i + `</th>`;
for (let key of headers) table += `<td>` + row[key] + `</td>`;
table += ` </tr>`;
i++;
}
table += ` </tbody>
</table>`;
// Loading dynamic table into our static HTML page.
$("#showDetails").html(table);
})
.catch( err => {
// If error setting dynamic error
let data = `<label class="alert alert-warning">Unable to fetch details</label>`;
// Loading dynamic error into our static HTML page
$("#showDetails").html(data);
})
}
service.js:
"use strict";
/**
* Common services used by all the other scripts
* All these are generic functions
*
*/
// To toggle between different views
function showForm (id) {
// Hide all views
$("#addInfo").addClass("hide");
$("#showInfo").addClass("hide");
// Show the view user had clicked
$(id).removeClass("hide");
}
// Validate Email based upon pattern
function validateEmail (email) {
if ( email && email.match(/^([A-z0-9_.]{2,})([#]{1})([A-z]{1,})([.]{1})([A-z.]{1,})*$/) ) {
return true;
}
return false;
}
// Validate First Name based upon pattern
function validateFname (fName) {
if ( fName && fName.match(/^([A-z]{2,})*$/) ) {
return true;
}
return false;
}
// Validate Last Name based upon pattern
function validateLname (lName) {
if ( lName && lName.match(/^([A-z]{2,})*$/) ) {
return true;
}
return false;
}
// Validate Phone based upon pattern
function validatePhone (phone) {
if ( phone && phone.match(/^([0-9]{10})*$/) ) {
return true;
}
return false;
}
// Validate Gender based upon pattern
function validateGender (gender) {
if ( gender && gender.match(/^([A-z]{4,6})*$/) && (gender === "male" || gender === "female") ) {
return true;
}
return false;
}

Change the colours of a button on the basis of the selected values in React

I am new to the react js. I have a form which is a normal form , using simple bootstrap 3 forms. Here, I have two select
<form className="form-inline text-center row" role="form">
<div className="col-xs-4">
<div className="form-group col-xs-12">
<label className="control-label">company/project</label>
<select id="company" className="form-control" onChange={(event, newValue) => this.setState({ company: event.target.value, hasUserFilledCompany: true })}>
<option disabled selected value>None Selected</option>
<option>abc</option>
<option>pqr</option>
<option>xyz</option>
<option>cdcdc</option>
<option>abcd</option>
</select>
</div>
</div>
<div className="col-xs-4">
<div className="form-group col-xs-12">
<label>Select Technology</label>
<select id="Technology" className="form-control" onChange={(event, newValue) => this.setState({ Technology: event.target.value, hasUserFilledTech: true })}>
<option disabled selected value>None Selected</option>
<option>qwe</option>
<option>gahs</option>
<option>cdbcdbhcd</option>
<option>cdcdc</option>
<option>cdcbdc</option>
</select>
</div>
</div>
<div className="col-xs-4">
<div className="form-group col-xs-12" style={jobUpload}>
<div className="row">
<label>Job Description</label>
<button type="button" className={"btn " + ((this.state.hasUserFilledTech && this.state.hasUserFilledCompany) ? 'enable-Button' : 'jd-button')} onClick={(event) => this.createJob(event)}>Add/Paste</button>
<span style={or}>Or</span>
<button type="button" className="btn jd-button">Upload File</button>
</div>
</div>
</div>
</form>
Now, Here, what I want to do is that is user selects value from the select then buttons colour will get changed and also it will enabled. for this, my solution is I have use two variables on select as a state variable and if this becomes true then I am applying condition classes to this buttons.
This is working, But I don't think this is a proper solution to validate a form . How can I do this?
This is how you can do this. A few good practise would be how you implement onChange function in select. You repeat a bit there. Notice how I destructured the event in onChange function. And You don't need another variable you can just check !!company && company.length > 0.
Here is the demo https://codesandbox.io/s/30yj7mrq4q
class App extends React.Component {
state = {
company: "",
tech: ""
}
onChange = ({ target: { name, value } }) => {
this.setState({ [name]: value });
}
render() {
const { tech, company } = this.state;
const enabled = (!!tech && tech.length > 0) && (!!company && company.length > 0)
return (
<div>
<div>
<label> Company </label>
<select name="company" onChange={this.onChange}>
<option disabled selected value>None Selected</option>
<option> Google </option>
<option> Facebook </option>
<option> Microsoft </option>
</select>
</div>
<div>
<label> Tech </label>
<select name="tech" onChange={this.onChange}>
<option disabled selected value>None Selected</option>
<option> React </option>
<option> Angular </option>
<option> Vue </option>
</select>
</div>
<div>
<button className={`btn ${enabled ? "enabled" : "disabled"} `} disabled={!enabled}>Upload File</button>
</div>
</div>
)
}
}

Access value of option in select and pass it to function - Angular 5

I have an angularForm and a combobox which is filled with options from the database. I need to get the selected option and pass it to a function on button click
<div class="form-group">
<select class="form-control" formControlName="product" #product>
<option *ngFor="let product of products" [value]='product'>{{product.name}}</option>
</select>
</div>
<div class="form-group">
<button (click)="addFeature(name.value, description.value,product.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
</div>
When I click the button and console.log product.value I get [object,object], how to fix this?
addFeature(name, description, product) {
console.log(product);
// this.featureservice.addFeature(name, description,product);
// this.router.navigate(['/features/index']);
// location.reload();
}
UPDATE
The values in the combobox are filled by:
ngOnInit() {
this.getProducts();
}
getProducts() {
this.productservice.getProducts().subscribe(res => {
this.products = res;
})
}
You are getting the whole object, if you need name or description , access it as
addFeature(name, description, product) {
console.log(product.name);
}
EDIT
You can use ngModel and access the variable directly
<select class="form-control" [(ngModel)]="selectedProduct" formControlName="product" #product>
<option *ngFor="let product of products" [value]='product'>{{product.name}}</option>
</select>
and you can access it as,
addFeature() {
console.log(this.selectedProduct);
}
Bind to ngValue instead value of the option tag:
<div class="form-group">
<select class="form-control" formControlName="product" #product>
<option *ngFor="let product of products" [ngValue]='product'>{{product.name}}</option>
</select>
</div>
See Differences between value and ngValue in Angular 5 for more info.
I don't get your doubt precisely but try to change your select tag to something like so:
<select class="form-control" formControlName="product" #product>
<option *ngFor="let product of products" [value]='product.value'
{{product.name}}
</option>
</select>
I found the solution myself
<select class="form-control" [(ngModel)]='selectedOption' formControlName="product" #product>
<option *ngFor="let product of products" [ngValue]='product'>{{product.name}}</option>
</select>
<button (click)="addFeature(name.value, description.value,selectedOption.name)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>

Categories