So I got this project I'm working on, I'm successful in adding the text(chips) to the string, but when I remove it, the text value is still there. So something is wrong in the remove part of my code. I need help removing the string and solving it!
My mentor says this is where I need to add changes to the code so I can remove the string from type and make it work. (in between these two codes)
let type = this.editDeliveryOrderForm.value.type;
// remove the string from type
this.editDeliveryOrderForm.patchValue({
type
});
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
console.log(`mat chip`, event);
console.log(`mat chip value`, value);
// Add our fruit
if ((value || '').trim()) {
this.fruits.push({name: value.trim()});
console.log(`fruits`, this.fruits);
let type = this.editDeliveryOrderForm.value.type;
type += ',' + value.trim();
this.editDeliveryOrderForm.patchValue({
type
});
}
// Reset the input value
if (input) {
input.value = '';
}
}
remove(fruit: Fruit): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
let type = this.editDeliveryOrderForm.value.type;
// remove the string from type
this.editDeliveryOrderForm.patchValue({
type
});
}
Here is how you can assign an empty string to type form control :
remove(fruit: Fruit): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
this.editDeliveryOrderForm.patchValue({
type : ""
});
}
}
Related
I have a page that passes some values using URL to input tag on another page. The problem that I have encountered was, that If there wasn't any value passed, there would be undefined as value, inside the input tag. So I was trying to write an if statement:
if (params.name === undefined) {
input.value = '';
} else {
input.value = params.name;
}
if (params.surname === undefined) {
input.value = '';
} else {
input.value = params.surname;
}
But as you can see based on this, it only works on, the params.surname, when I am passing params.name as a value, the input tag is clear. Any ideas how I could connect it together, so both values would show up, inside the input tag?
Use || to alternate between the name (showing it if it exists), or the surname (showing it if it exists), or the empty string:
input.value = params.name || params.surname || '';
params.name will be inputted if it exists. Otherwise, params.surname will be inputted if it exists. Otherwise, it'll be set to the empty string.
If the properties can be the empty string, and not just undefined, and you'd want the empty string to be displayed if it exists, then use the conditional operator instead:
input.value = params.name !== undefined
? params.name
: params.surname !== undefined
? params.surname
: '';
if(!(params.name || params.surname)){
input.value = '';
} else if(params.name) {
input.value = params.name;
} else {
input.value = params.surname;
}
Another more readable approach could be:
input.value = '';
if (params.name) input.value = params.name;
if (params.surname) input.value = params.surname;
Another way, fun to play:
const resolve = att => params[att]? params[att] : '';
input.value = resolve('surname') || resolve('name');
because surname has more priority than name, so in the assignment, surname should take the first place.
If you want name and surname both exist:
const resolve = att => params[att]? params[att] : '';
input.value = resolve('surname') + resolve('name');
I have multiple inputs (type="number") and when someone put a value into it i am creating a object. I like to create a statement and check if a specific object value is greater then 0.
if(el){
el.addEventListener('input', function(evt) {
const input = evt.target
if (input.checked || input.value.length) {
steps[input.dataset.name] = {
value: input.value
}
} else {
delete steps[input.dataset.name]
}
})
}
So my object i looking like that
So in object steps i have multiple objects where each has a unique name and a value. I like to run a function but only when a specific object value is greater then 0, in example when sale_monthly_additional_sales value is > 0 do something. I have no idea how to even start with that.
you could add condition like that.
Create array and add key name of the element name .
Then match with Array#includes().Finally apply you condition as you wish
CODE
var arr =['sale_monthly_additional_sales']; //
if (el) {
el.addEventListener('input', function(evt) {
const input = evt.target
if (input.checked || input.value.length) {
var val =input.value; // initiate default value
if(arr.includes(input.dataset.name)){ //match keyname on your element name
val = parseFloat(input.value) > 0 ?'your code':val; //over write as you condition
}
steps[input.dataset.name] = {
value: input.value
}
} else {
delete steps[input.dataset.name]
}
})
}
I create a search bar. When the user presses the letter 'A' I want to display the users whose first name starts with the letter 'A'.
This works, but my problem is when the search bar is empty.
When it is empty, my program displays all the users, and I want it to show none.
Here is my program to obtain the value entered by the user :
searchUser(): void {
let str;
let element = document.getElementById('chat-window-input');
if(element !== null) {
str = (element as HTMLInputElement).value;
}
else {
str = null;
}
}
Do you know how to detect an empty field ?
I tested this but it does not change anything :
if(str == null) {
this.searchArrayThreads = [];
}
Hi you can try like this,
if(str == null || (!str) || str=='') {
this.searchArrayThreads = [];
}
In your question it seems you have one array of data.
so keep a tempDataSet
this.tempDataSet = [];
then while filtering you can directly assign values.
this.str = '';
searchUser(): void {
let element = document.querySelector('#chat-window-input');
if(element && element.value) {
return this.str = element.value;
}
}
I think this will help you
So I am having trouble getting my code to do something when I hit backspace or delete.
The code I have works just fine. It runs the following code, updating the size and value of multiple text input fields.
It calls compute(), which calls update() multiple times through updateAllFields().
function compute(input,number){
var decider = String(input.value);
updateAllFields(decider,number);
}
function update(label,convert,decider,number){
var updater = document.getElementById(label);
updater.value = parseInt(decider, number).toString(convert);
updater.style.width = ((updater.value.length + 1) * 12.5) + 'px';
}
function updateAllFields(decider,number){
update('binary',2,decider,number);
update('octal',8,decider,number);
update('decimal',10,decider,number);
update('hexadecimal',16,decider,number);
}
Now, that all runs just fine. I ran into an issue that, when an entire field is deleted, I get NaN, and can no longer edit the text fields unless I outsmart the NaN value.
How it happens is that that if a user hits "Ctrl+home", then backspace (wiping the entire field), NaN appears.
What I want, instead, is that when NaN would have appeared, all of the text inputs are reset to the same size and appearance that they were when their placeholders were showing.
I had looked this up, and found the following:
var input = document.getElementById('display');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key !== 8 && key !== 46 )
return true;
};
It doesn't work. I even tried replacing the return false to instead read my replacement code:
function refresh(label,number){
var refresher = document.getElementById(label);
refresher.value = '';
refresher.size = number;
}
function refreshAllFields(){
refresh('binary','3');
refresh('octal','2');
refresh('decimal','4');
refresh('hexadecimal','8');
}
And that doesn't work.
What am I doing wrong? How can I get my fields to just reset to their original states if the entire text-field of one is wiped out?
You don't need to decrease the possibility of error. You need to prevent errors at all. Just validate the input data and you won't get NaN.
Simply add a check in your compute if the input is an integer:
function compute(input,number){
var decider = String(input.value);
if (isNumeric(decider))
{
// do something else
decider = "0"; // for example
}
updateAllFields(decider, number);
}
where isNumeric is a function which determines if a string represents number. There are many ways to do this, for example this:
function isNumeric(value)
{
if (isNaN(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
Also, you can stop passing your decider and number to every function as a string:
function compute(input, number){
if (isNumeric(input.value))
{
updateAllFields(parseInt(input.value, number)); // val is a Number now
} else {
updateAllFields(0); // for example
}
}
function update(label,convert,val){
var updater = document.getElementById(label);
updater.value = val.toString(convert);
updater.style.width = ((updater.value.length + 1) * 12.5) + 'px';
}
function updateAllFields(val) {
update('binary',2,val);
update('octal',8,val);
update('decimal',10,val);
update('hexadecimal',16,val);
}
i validate my formular with ajax and get back the following json object:
{"username":["Please enter a username"],"email":["Please enter an email"],
"plainPassword":{"first": ["Please enter a password"]},"firstname":
["This value should not be blank."],"lastname":["This value should not be blank."],
"terms":["This value should be true."],"privacy":["This value should be true."],
"captcha":["Code does not match"],"securityQuestion":["This value should not be blank."],
"plainSecurityAnswer":["This value should not be blank."],"intention":
["This value should not be blank."],"addresses":[{"state":["This value should not be blank."],
"city":["This value should not be blank."],"zipcode":["This value should not be blank."],
"country":["This value should not be blank."]}]}
The keys are mapped to the input fields id always by:
var id = "fos_user_registration_form_" + key;
I want to present these errors in an efficient way as tooltips to the fields. For that, i've written the following jQuery code (where callback is the returned json object):
$.each( callback, function( key, entry ) {
if(key != "addresses" && key != "plainPassword")
{
var id = "#fos_user_registration_form_" + key;
$(id).tooltip('destroy');
$(id).tooltip({'title': entry});
$(id).closest('div[class="form-group"]').addClass('has-error');
}else if(key == "addresses"){
$.each( entry[0], function( keyAddress, entryAddress ) {
var id = "#fos_user_registration_form_" + key + "_0_" + keyAddress;
$(id).tooltip('destroy');
$(id).tooltip({'title': entryAddress});
$(id).closest('div[class="form-group"]').addClass('has-error');
});
}else if(key == "plainPassword")
{
var id= "#fos_user_registration_form_plainPassword_first,#fos_user_registration_form_plainPassword_second";
$(id).tooltip('destroy');
$(id).tooltip({'title': entry.first});
$(id).closest('div[class="form-group"]').addClass('has-error');
}});
It is working, but i think not very dynamic because i know in this case that the entries of the key "addresses" and "plainPassword" aren't strings and that i have to iterate on them again (here only on addresses).
Is there a nicer way to do this by only using the key and entry variable of the loops, without knowing the "key" names of the json ?
I thought of something like: While entry !== "string", iterate as long threwthe entries as there is another array or object in it and build up the "id" variable. When there is a string field as "entry", use it as tooltip text.
Hope you guys can help me.
Regards.
Recursion will do this!
eg http://repl.it/3hK/5
Code -
var id_stub = "#fos_user_registration_form_"
// Here's the recursive function - we kick it off below.
function process(thing, id) {
var key
for (key in thing) {
// Handle the arrays
if ('length' in thing[key]) {
// Handle the end - we found a string
if (typeof thing[key][0] == "string") {
var html_id = id_stub + id + key
var err_msg = thing[key][0]
console.log(html_id, ":", err_msg)
// Now do your jquery using the html_id and the err_msg...
}
// Else we found something else, so recurse.
else {
var i = 0;
while (i < thing[key].length) {
process(thing[key][i], key + "_" + i + "_")
i++
}
}
}
// Handle the objects by recursing.
else {
process(thing[key], key + "_")
}
}
}
// Start the recursion from here.
process(callback, "")
I added an extra address to test how this code handles nested addresses, and using that I get this in the console:
#fos_user_registration_form_username : Please enter a username
#fos_user_registration_form_email : Please enter an email
#fos_user_registration_form_plainPassword_first : Please enter a password
#fos_user_registration_form_firstname : This value should not be blank.
#fos_user_registration_form_lastname : This value should not be blank.
#fos_user_registration_form_terms : This value should be true.
#fos_user_registration_form_privacy : This value should be true.
#fos_user_registration_form_captcha : Code does not match
#fos_user_registration_form_securityQuestion : This value should not be blank.
#fos_user_registration_form_plainSecurityAnswer : This value should not be blank.
#fos_user_registration_form_intention : This value should not be blank.
#fos_user_registration_form_addresses_0_state : This value should not be blank.
#fos_user_registration_form_addresses_0_city : This value should not be blank.
#fos_user_registration_form_addresses_0_zipcode : This value should not be blank.
#fos_user_registration_form_addresses_0_country : This value should not be blank.
#fos_user_registration_form_addresses_1_state : This value should not be blank.
#fos_user_registration_form_addresses_1_city : This value should not be blank.
#fos_user_registration_form_addresses_1_zipcode : This value should not be blank.
#fos_user_registration_form_addresses_1_country : This value should not be blank.
and sets up the variables you need to do your jQuery work.
function isValidationMessage(entry) {
return entry.length === 1 && typeof entry[0] === 'string';
}
function displayValidationMessage(key, message){
var id = "#fos_user_registration_form_" + key;
$(id).tooltip('destroy');
$(id).tooltip({'title': message});
$(id).closest('div[class="form-group"]').addClass('has-error');
}
function displayValidationMessageForArray(key, entries) {
for(var i = 0; i < entries.length; i++) {
$.each(entries[i], function(keyAddress, entryAddress) {
displayValidationMessage(key + "_i_" + keyAddress, entryAddress);
})
}
}
function displayValidationMessageForObject(key, entries) {
$.each(entries, function(entry, message) {
displayValidationMessage(key + "_" +entry, message);
})
}
function displayAllValidationMessages(callback) {
$.each( callback, function( key, entry ) {
if(isValidationMessage(entry)) {
displayValidationMessage(key, entry);
}else if($.isArray(entry)){
displayValidationMessageForArray(key, entry);
}else {
displayValidationMessageForObject(key, entry);
}
});
}
not fully tested, idea is to extract the if else to small function, and reuse them as much as possible