In UI, I create a object and set one of the property as boolean :
function UserObject(componentId, componentName, checkedOut) {
this.componentId = componentId;
this.componentName = componentName;
this.checkedOut = checkedOut; //this is boolean variable
}
But from backend, while I set boolean values in my object, json converts it into string.
private UserObject createUserObject(EntityDTO entity) {
UserObject userObject = new UserObject();
userObject.setComponentId(entity.getEntityId());
userObject.setComponentName(entity.getEntityName());
userObject.setCheckedOut(entity.getCheckedOut());
return userObject;
}
Now, here is the problem, I match some conditions twice (1) while creating (2) later while getting data from backend. Whenever I match the conditions for "checkedOut" object, it fails for the case when object comes from backend:
if(cell.value.checkedOut === true){
//some code
}else{
//some more code
}
What should I do? Thanks in advance :)
if(cell.value.checkedOut === "true"){
//some code
}else{
//some more code
}
As it is a string in json now use double quotes for comparision
if you want to convert string "true or false" to boolean type, use eval():
if(eval(cell.value.checkedOut) === true) {
//some code
} else {
//some more code
}
Related
I have an array containing 10 objects. Each contains a question string, a correctAnswer string, and an object with 4 answer strings:
const DB = [
{
question: "some question",
answers: ["a", "variety", "of", "choices"],
correctAnswer: "variety"
}, ...
I have a function which captures the user's answer via radio button input, and saves it in a variable:
function getFeedback(){
return $("form input[type=radio]:checked")
.closest('.css-answerscss-answers')
.children('label')
.text()
}
function feedbackPage(){
$('.js-quizform-questions').on('click', '.js-button-next', function(event){
event.preventDefault()
let yourAnswer = getFeedback()
$('.js-feedback-page').show().html(evalCorrectAnswer(DB))
})
}
The last line then calls evalCorrectAnswer() with a parameter of DB. I want to compare the answer given by the user (yourAnswer) to the correctAnswer in DB. All the console logs work in that they return the correct and same answers. Yet the Correct/Wrong html is not sent back:
function evalCorrectAnswer(yourAnswer){
console.log(yourAnswer)
console.log(DB[0].correctAnswer)
if (DB[0].correctAnswer === yourAnswer){
`<p>Correct</p>`
} else {
`<p>Too bad</p>`
}
}
What am I missing?
You are missing the return statement, make it
function evalCorrectAnswer(yourAnswer){
console.log(yourAnswer)
console.log(DB[0].correctAnswer)
return DB[0].correctAnswer === yourAnswer ? `<p>Correct</p>` : `<p>Too bad</p>`;
}
isn't a return call missing? Inside the if/else
like this:
if (DB[0].correctAnswer === yourAnswer){
return `<p>Correct</p>`;
} else {
return `<p>Too bad</p>`;
}
You need to return the value! Like in
...
return '<p>Correct</p>';
...
Also make sure that you use the correct quotation marks,' instead of ```.
Some languages allow you to return a value with just a single statement (return becomes implicit). JavaScript is not one of those languages. To return the result of the function you need to explicitly use a return statement.
Minimal fix to your code:
function evalCorrectAnswer(yourAnswer){
console.log(yourAnswer)
console.log(DB[0].correctAnswer)
if (DB[0].correctAnswer === yourAnswer){
return '<p>Correct</p>'
} else {
return '<p>Too bad</p>'
}
}
let's imagine, I've got 5 strings and any of it can be filled in or just stay empty (it's based on user input)
I wonder how to separate them nice with comma. I feel like this problem have to be trivial but only idea I found out that will work and is not totally stupid is:
// Create a function which return me string of arrays
public getAddress(): string[] {
let result = [];
if (this.application.applicant.city) {
result.push(this.application.applicant.city);
}
if (this.application.applicant.postalCode) {
result.push(this.application.applicant.postalCode);
}
if (this.application.applicant.state && this.application.applicant.state.name) {
result.push(this.application.applicant.state.name);
}
return result
}
// Then somewhere in ngOnInit() just call this method:
this.address = this.getAddress();
And inside of my tempalte:
<span *ngFor="let item of address; let isLast=last">
{{item}}{{isLast ? '' : ', '}}
</span>
or clasic JS way:
<span> {{address.join(", ")}} </span>
And I still feel like this is overcomplicated. Am I missing some easy solution?
Thanks for any advise
There is a typescript function to split a string. It also remove the ,
this.addres = this.address.split(', '); // this is now an array instead of a string.
EDIT
I create a string and but the newValue in it the newValue can be anything.
let string = '';
if() {
string = `${string}, ${newValue}`;
}
here is a sample solution than yours ,you create the address's string in your method and show it directly in your html template (i think it's more simpler than iterating on the array.. )
in your .ts :
address : string ;
// Create a function which return me string of arrays
public getAddress(): string {
let result = "";
if (this.application.applicant.city) {
result.push(this.application.applicant.city+",");
}
if (this.application.applicant.postalCode) {
result.push(this.application.applicant.postalCode+",");
}
if (this.application.applicant.state && this.application.applicant.state.name) {
result.push(this.application.applicant.state.name+",");
}
if (result.length !== 0 )
result.substring(0, result.length-1);
return result
}
// Then somewhere in ngOnInit() just call this method:
this.address = this.getAddress();
in your HTML template :
<span>{{address}}</span>
Hope it helps :)
How do I render a Boolean to a JavaScript variable in a cshtml file?
Presently this shows a syntax error:
<script type="text/javascript" >
var myViewModel = {
isFollowing: #Model.IsFollowing // This is a C# bool
};
</script>
You may also want to try:
isFollowing: '#(Model.IsFollowing)' === '#true'
and an ever better way is to use:
isFollowing: #Json.Encode(Model.IsFollowing)
Because a search brought me here: in ASP.NET Core, IJsonHelper doesn't have an Encode() method. Instead, use Serialize(). E.g.:
isFollowing: #Json.Serialize(Model.IsFollowing)
The JSON boolean must be lowercase.
Therefore, try this (and make sure nto to have the // comment on the line):
var myViewModel = {
isFollowing: #Model.IsFollowing.ToString().ToLower()
};
Or (note: you need to use the namespace System.Xml):
var myViewModel = {
isFollowing: #XmlConvert.ToString(Model.IsFollowing)
};
var myViewModel = {
isFollowing: '#(Model.IsFollowing)' == "True";
};
Why True and not true you ask... Good question:
Why does Boolean.ToString output "True" and not "true"
A solution which is easier to read would be to do this:
isFollowing: #(Model.IsFollowing ? "true" : "false")
Here's another option to consider, using the !! conversion to boolean.
isFollowing: !!(#Model.IsFollowing ? 1 : 0)
This will generate the following on the client side, with 1 being converted to true and 0 to false.
isFollowing: !!(1) -- or !!(0)
Defining a conversion operation and adding an override of .ToString() can save a lot of work.
Define this struct in your project:
/// <summary>
/// A <see cref="bool"/> made for use in creating Razor pages.
/// When converted to a string, it returns "true" or "false".
/// </summary>
public struct JSBool
{
private readonly bool _Data;
/// <summary>
/// While this creates a new JSBool, you can also implicitly convert between the two.
/// </summary>
public JSBool(bool b)
{
_Data = b;
}
public static implicit operator bool(JSBool j) => j._Data;
public static implicit operator JSBool(bool b) => new JSBool(b);
// Returns "true" or "false" as you would expect
public override string ToString() => _Data.ToString().ToLowerInvariant();
}
Usage
You can directly cast a C# bool, as in the case of the question:
{
// Results in `isFollowing : true`
isFollowing : #((JSBool)Model.IsFollowing)
}
But you can also use a JSBool directly in the Razor code with the expectation that it will give true and false without having to do any extra work:
#{
JSBool isA = true;
JSBool isB = false;
// Standard boolean operations work too:
JSBool isC = a || b;
}
<script>
if (#isC)
console.log('true');
</script>
This works because of the implicit conversion operators we defined above.
Just make sure to only ever use this when you intend to use it in Razor code. In other words, don't use it with normal C# as this can make your code messy.
I have the following script in my ASP.NET MVC Core View:
window["dataSet1"] = [];
#foreach (var item in Model.SelectedOptions)
{
foreach (var item2 in Model.MyChartData)
{
// ".mph" exists in 'MyChartData' model
// This works... but it's not dynamic
#:window["dataSet1"].push(['#item', #item2.mph);
// How can I get a dynamic variable determine
// what field to retrieve from the model?
// Example values for 'SelectedOptions' are:
// > "mph", "kph", "m/s", "knots"
// I'd like this to work...
#:window["dataSet1"].push(['#item', #item2.#item);
}
}
Instead of creating if else statements for each possible 'SelectedOptions' value (mph, kph, m/s, knots etc.), is it possible to simply use a variable to reference a specific object within my model?
The data I get back from my attempt is:
window["dataSet1"].push(['mph', MyProject.Models.MyChartData.mph]);
Rather than a value from my model, for example:
window["dataSet1"].push(['mph', 15.16451]);
You can solve it in c# adding a property using reflection to get the value or a simple case
Example:
#:window["dataSet1"].push(['#item', #item2.correctvalue( item );
In the item2 class:
public decimal correctvalue( propName ) {
return this.GetType().GetProperty(propName).GetValue(this, null);
}
Or more simple:
public decimal correctvalue( propName ) {
if (propName = "mph") {
return this.mph;
}
else ...
}
Keep in mind that you should validate the propName or the reflection will error. More info on using reflection to get the property value
The solution I created, whilst whacking it into a static class so it can be easily accessed in future.
public static object GetPropertyValue(this object myProperty, string propertyName)
{
return myProperty.GetType().GetProperties()
.Single(pi => pi.Name == propertyName)
.GetValue(myProperty, null);
}
I am working on an assignment using javascript. I am attempting to use filter_var to test if my form has empty fields but I cannot get it to run.
I'm not confident that my Syntax is right.
function validate_reg_form(form)
{
var form = "";
if (filter_var(form, FILTER_VALIDATE_BOOLEAN))
{
alert("validate_reg_form() not yet implemented");//remove this
}
}
filter_var is a PHP function. It does not exist in JavaScript. The exact equivalent is:
var truthyBooleanStrings = ['1', 'true', 'on', 'yes'];
function validateRegForm(form) {
var form = '';
if (truthyBooleanStrings.indexOf(form) !== -1) {
// …
}
}
Maybe that’s not the right approach for
test if my form has empty fields
, though. If you want to test that something is not an empty string, just use !== '' or the implicit truthiness of non-empty strings, as in
if (form) {
// Not empty!
}