I'm working on a clickButton function to populate a table based on the entered value from user. There are 3 fields to input data. First Name, Last Name, Zip. If I type firstName, click search I need to see the associated JSON data in the table. Same thing for lastName and zipCode. When I set $scope.results = data, the table is populated correctly based on entered value for firstName. I am trying to add conditions for the other two fields and then push the results to jsp. What am I doing wrong?
JS
$scope.results = [];
$scope.clickButton = function(enteredValue) {
$scope.items=this.result;
var url = 'http://localhost:8080/application/names/find?firstName='+enteredValue+'&lastName='+enteredValue+'&zipCode='+enteredValue
$http.get(url).success(function(data){
angular.forEach($scope.items, function (item) {
if(items.first_nm === enteredValue || items.last_nm ==enteredValue || items.zip_cd == enteredValue){
$scope.results.push({
firstName: item.first_nm,
lastName: item.last_nm,
zipCode: item.zip_cd
});
}
})
})
};
JSP
<input id="firstName" name="firstName" type="text" data-ng-model="enteredValue" />
<input id="lastName" name="lastName" type="text" data-ng-model="enteredValue" />
<input id="zipCode" name="zipCode" type="text" data-ng-model="enteredValue" />
<button class="btn btn-primary" data-ng-click='clickButton(enteredValue)'>Search</button>
<tr data-ng-repeat="result in results" class="text-center">
<td data-title="'ID'" >{{result.firstName}}</td>
<td data-title="'Name'" >{{result.lastName}}</td>
<td data-title="'Status'" >{{result.zipCode}}
</td>
Currently you are binding all search parameters to the same property - enteredValue. Instead you can assign them to separate properties and then use them accordingly in your search method:
HTML:
<input id="firstName" name="firstName" type="text" data-ng-model="enteredValue.firstName" />
<input id="lastName" name="lastName" type="text" data-ng-model="enteredValue.lastName" />
<input id="zipCode" name="zipCode" type="text" data-ng-model="enteredValue.zipCode" />
<button class="btn btn-primary" data-ng-click='clickButton(enteredValue)'>Search</button>
Controller:
$scope.clickButton = function(enteredValue) {
$scope.items=this.result;
// instead of enteredValue use enteredValue.lastName and other properties
// If your API allows it, you can even add the value only if it exists,
// not always as it is done currently
var url = 'http://localhost:8080/application/names/find?firstName='+
enteredValue.firstName+'&lastName='+
enteredValue.lastName+'&zipCode='+enteredValue.zipCode
$http.get(url).success(function(data){
angular.forEach($scope.items, function (item) {
if(items.first_nm === enteredValue || items.last_nm ==enteredValue || items.zip_cd == enteredValue){
$scope.results.push({
firstName: item.first_nm,
lastName: item.last_nm,
zipCode: item.zip_cd
});
}
});
});
};
Related
I'm working with DOM and web API to POST some information about the company like name, worker's name.
But when I write something in the input DOM can't reach the value and return empty so I post an empty object.
That looks like :
adress: ""
companyName: ""
contactName: ""
contactTitle: ""
My form block:
<form>
<div class="form-group">
<label for="">Company Name</label>
<input
type="text"
class="form-control"
id="companyName"
placeholder="Company Name!"
/>
</div>
<div class="form-group">
<label for="">Contact Name</label>
<input
type="text"
class="form-control"
id="contactName"
placeholder="Contact Name!"
value=""
/>
</div>
<div class="form-group">
<label for="">Contact Title</label>
<input
type="text"
class="form-control"
id="contactTitle"
placeholder="Contact Title!"
/>
</div>
<div class="form-group">
<label for="">Country</label>
<input
type="text"
class="form-control"
id="inputCountry"
placeholder="Country!"
/>
</div>
</form>
And my JS code:
'use strict';
let inputCompanyName = document.getElementById('companyName');
let inputContactName = document.getElementById('contactName');
let inputContactTitle = document.getElementById('contactTitle');
let country = document.getElementById('inputCountry');
const btnSubmit = document.getElementById('submit');
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
btnSubmit.addEventListener('click', e => {
e.preventDefault();
axios
.post('https://northwind.vercel.app/api/suppliers', newCompany)
.then(res => {
console.log('Response', res.data);
alert('Success!');
});
});
I tried innerHTML and innerText and form method but I cant solve this problem.
You're reading the values immediately upon loading the page, long before the user has had a chance to enter any values.
Instead, read the values in the click event:
btnSubmit.addEventListener('click', e => {
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
// the rest of the click handler logic...
});
const ProductEdit = () => {
const[user]=useAuthState(auth);
const {inventoryId}=useParams();
const [product,SetProduct]=useState({});
useEffect(()=>{
const url=`http://localhost:5000/product/${inventoryId}`;
fetch(url)
.then(res=>res.json())
.then(data=>SetProduct(data));
},[])
return (
<div className='mt-5 '>
<h3 className='text-center'> Product Detail of {product.name}</h3>
<form className='w-50 mx-auto'>
<input className='w-100 mb-2' type="text" placeholder='Name' name='name' value={product.name} required/>
<br />
<input className='w-100 mb-2' type="text" placeholder='Price' name='quantity' value={product.price} required/>
<br />
<input className='w-100 mb-2' type="text" placeholder='Quantity' name='number' value={product.quantity} required/>
<br />
<input onclick={handleReduce} type="submit" value="Delivered" />
</form>
I want to reduce the amount of the quantity from the data which is loaded also in MongoDB. what should do?
I see what you are trying to do.
You can do this in a couple of ways.
1st method is that you reduce the quantity from the server side by just sending -1 in the body.
2nd method is that you do your calculation from the client-side and send the updated quantity to the server-side.
In any case, you can do this with a function.
I see that you are calling a function on the onClick event.
So, why not use that?
All you have to do is wrap that onClick function as a callback function.
Just like this:
<input onclick={()=>handleReduce(-1)} type="submit" value="Delivered" />
See? I just pass -1 as the function parameter.
And you can declare the function like this:
const handleQuantity = (number) => {
axios.patch(
`http://localhost:5000/items/${id}`,
{
quantity: item.quantity + number,
},
{
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
const newItem = { ...item, quantity: item.quantity + number };
setItem(newItem);
};
Hi and sorry for the Newbie-Question
I am trying to push a HTML-Input into an existing array on Button-click, but i cannot find my mistake.
Can anyone spot the mistake? The console.log(user) stays undefined and I don't know why the let newUser() I create does not get pushed into the array.
<template>
<div>
<form #submit.prevent="customSubmit">
<label>Name</label>
<input type="text" required name="name" id="name">
<label>E-mail:</label>
<input type="email" required name="email" id="email">
<label>Mobile Number</label>
<input type="number" required name="number" id="number">
</form>
<button type="submit" class=buttonSignup #click="customSubmit">Submit</button>
</div>
</template>
<script>
export default {
data() {
return{
user:[{
name: '',
email:'',
number:''
}]
};
},
methods: {
customSubmit(){
let newUser = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
number: document.getElementById('number').value
}
this.user.push(newUser)
console.log(this.user.value)
},
}
}
</script>
With Vue, you use v-model instead of directly accessing the DOM. For example, you can re-write your code by:
Change name=name to v-model=user.name
Use user and users. user collects one user's data and users collects all user input into an array. This is reflected in the modified customSubmit.
Reset user after each input.
There are more elegant ways to do this but this is the clearest and close enough to your original code.
<template>
<div>
<form #submit.prevent="customSubmit">
<label>Name</label>
<input type="text" required v-model="user.name" id="name">
<label>E-mail:</label>
<input type="email" required v-model="user.email" id="email">
<label>Mobile Number</label>
<input type="number" required v-model="user.number" id="number">
</form>
<button type="submit" class=buttonSignup #click="customSubmit">Submit</button>
<br/>
You typed:<br/>
name: {{user.name}}<br/>
email: {{user.email}}<br/>
number: {{user.number}}
</div>
</template>
<script>
export default {
data() {
return {
users: [],
user: {
name: '',
email: '',
number: ''
}
};
},
methods: {
customSubmit() {
// do some checking here
this.users.push(this.user)
this.user = {name:'', email:'', number:''};
console.log(this.users)
},
}
}
</script>
I have a form with form-groups each containing similar text fields and checkboxes which are sent as arrays when submitting the form as below:
<form method="POST" action="http://localhost/save-form" id="formAddUser">
<div class="form-group">
<input type="text" class="name" name="username[]" />
<input type="text" class="phone" name="phone[]" />
<input type="text" class="country" name="country[]" />
<input type="checkbox" class="isMobile" name="isMobile[]" />
</div>
<div class="form-group">
<input type="text" class="name" name="username[]" />
<input type="text" class="phone" name="phone[]" />
<input type="text" class="country" name="country[]" />
<input type="checkbox" class="isMobile" name="isMobile[]" />
</div>
<div class="form-group">
<input type="text" class="name" name="username[]" />
<input type="text" class="phone" name="phone[]" />
<input type="text" class="country" name="country[]" />
<input type="checkbox" class="isMobile" name="isMobile[]" />
</div>
</form>
After every time someone enters their phone, I want to do a remote validation but I would like to send isMobile field along with the request. Currently I am able to send the phone field for validation but couldn't send the corresponding mobile field along with it in the data attribute. Here is my code
$('#frmAddUser').bootstrapValidator({
fields: {
'phone[]': {
trigger: 'blur',
validators: {
notEmpty: {
message: ' '
},
remote: {
message: 'Phone does not exist',
url: 'http://localhost/verify-phone',
data: function () {
// leaving this empty just sends the phone. How do I send isMobile parameter along with this?
}
},
callback: {
callback: function () {
}
}
}
}
}
})
Edit: The following worked.
remote: {
message: 'Phone does not exist',
url: 'http://localhost/verify-phone',
data: function () {
var isMobile = validator.getFieldElements('isMobile[]').val()
}
},
As suggested by #Sumesh, using validator.getFieldElements('isMobile[]').val() worked
remote: {
message: 'Phone does not exist',
url: 'http://localhost/verify-phone',
data: function () {
var isMobile = validator.getFieldElements('isMobile[]').val()
}
}
I would like to do a simple base where I can add memebers to array. I change a "Tour of Heroes" from Angular tutorial (link). What I want to do is instead of passing name (string) to function I would like to give a whole class object (User). I use form where user is typing his name and surname (and city if he want). I have no idea how to get from input to function this whole object, instead of list of string parameters. Here is my code:
form.html:
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" required name="nameField" [(ngModel)]="ngModel" #nameField="ngModel" >
<div [hidden]="nameField.valid || nameField.pristine" class="alert alert-danger">Name is required</div>
</div>
<div class="form-group">
<label for="surname">surname</label>
<input type="text" class="form-control" id="surname" required name="surnameField" ngModel #surnameField="ngModel">
<div [hidden]="surnameField.valid || surnameField.pristine" class="alert alert-danger">Surname is required</div>
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" class="form-control" id="city" name="city" ngModel #cityField="ngModel" >
</div>
<button type="submit" class="btn btn-success" [disabled]="!userForm.form.valid">Submit</button>
</form>
function on submit:
onSubmit(name: string, surname: string, city: string ): void{
name = name.trim();
surname = surname.trim();
city = city.trim();
this.myservice.create(name, surname, city)
.then(newUser => this.arrayUsers.push(newUser));
}
And function create inside myservice:
private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/mainArray'; // URL to web api
create(name: string, surname: string, city?: string): Promise<User> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name, surname:surname, city:city}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as User);
}
Declare the ngModel attribute to bind each input to the form :
For example :
<input type="text" class="form-control" id="name" ngModel required name="nameField" >
<input type="text" class="form-control" id="surname" ngModel required name="surnameField" >
<input type="text" class="form-control" id="city" ngModel required name="cityField" ngModel >
And in the form element, give a name to the form to be able to bind it in the component and add the form as parameter in the onSubmit() method :
<form #f="ngForm" (ngSubmit)="onSubmit(f)" >
Now you should be able to retrieve the user with the f.value property :
onSubmit(f: NgForm): void{
this.myservice.create(f.value)
.then(createdUser=> this.arrayUsers.push(createdUser));
}
More information here : https://angular.io/api/forms/NgModel