Problem with writing a proper If statement - javascript

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');

Related

How do I remove a text from a string in my coding

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 : ""
});
}
}

Ajax check value of data

I'm getting data as JSON response and each time one of my fields is empty and one has value so I need to make if statement to check which one has value and print that one.
So far I tried:
if(data.longtext_dec != ''){
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
and
if($.trim(data.longtext_dec) === '')
{
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
each time the code keeps printing longtext_dec or show both as null.
So I need help to get this right, the result of this ress I want to append it in my view (either this or that).
How can I fix this code?
UPDATE
network response tab:
product_id 15
specification_id 5
text_dec ddd
longtext_dec null
id 69
payload
{"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69}
Just use if (data.longtext_desc) it's a way to check if data variable evaluates to true. undefined, null, false, 0, an empty string evaluates to false.
var ress; // undefined
if (data.longtext_desc) {
ress = data.longtext_desc;
} else {
ress = data.text_dec;
}
Optionally use a ternary operator:
var ress = data.longtext_desc ? data.longtext_desc : data.text_dec;
There is a difference between empty string, null, undefined and boolean true/false. As shown in the JSON you want to check if the value from the response object is null. So just check
if( data.longtext_dec !== null )
Here is very well explained:
https://stackoverflow.com/a/27550756/3868104
Optional you can check for whatever you want for example:
if( data.longtext_dec !== "" )
and so on.
you can leverage javascript || operator as below
var res = data.longtext_dec || data.text_dec;
Try this :
var data = {"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69};
var ress;
(data.longtext_dec !== null) ? ress = data.longtext_dec : ress = data.text_dec;
console.log(ress);

Detecting an empty field of an input

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

how to check null in javaScript function?

I want to check null and empty id in JavaScript function,but if syntax isn't work ?
var id = "<%=Request["Id"]%>";
if (id !== "")
if (id !== null)
{var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id; }
With javascript,
If you are trying to test for not-null (any value that is not explicitly NULL) this should work for you:
if( myVar !== null ) {
// your code
}
If you are only interested to test for not-empty (null value, zero number, empty string etc..) then try:
if( !myVar ) {
// your code
}
If you want to test for if a variable is defined at all (which I believe is what you are trying to achieve) then you can do it like:
if( typeof myVar !== 'undefined' ) {
// your code
}
Please let me know if it works for you.
Read into binary logic:
var id = "<%=Request["Id"]%>";
if (id !== "" && id != null) {
var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id;
}
Then again, var id = "<%=Request["Id"]%>"; will never be null, only empty string, so perhaps you can drop that check altogether.

How do you set the display value of any DOM element?

Sometimes I want to update the value of a random DOMNode but I don't really know what type of element it is for sure. I am assuming I will need some block of code that checks to see what type of node it is.
if(el.tagName == 'input' ) el.value = "foo";
if(el.tagName == 'div') el.innerHTML = "foo";
Or even if certain properties exist:
var value = "foo";
if(el.value != "undefined" && el.value != value) {
el.value = value;
}
if(el.innerHTML != "undefined" && el.innerHTML != value) {
el.innerHTML = value;
}
The el.nodeType does list several basic types, but they are just basic node types.
What is the best way to update any type of elements display?
Update: #dfsq had a good idea.
el["value" in el ? "value" : "innerHTML"] = value;
However, it doesn't seem to work with just any element:
["value" in document.createElement('li')] // true
Update 2 strict type checking might be a solution:
document.createElement('input').value
""
document.createElement('li').value
0
document.createElement('div').value
undefined
document.createElement('textarea').value
""
Note: No jQuery solutions unless you want to point out how jQuery does it
Seems type checking on the el.value is the way to go:
var els = ['p', 'div', 'li', 'a', 'input', 'textarea'];
for (var i in els) {
var el = document.createElement(els[i]); el.value = 'foo'; console.log(el.value);
}
jsfiddle
el[typeof el.value === "string" ? "value" : "innerHTML"] = value;

Categories

Resources