Gas
Gas

Reputation: 737

Javascript convert a true/false value string text

I have a jQuery script that collects the values of checkboxes in variables:

var 1_val = $("input[type='checkbox'][name='val_1']").prop( "checked" );
var 2_val = $("input[type='checkbox'][name='val_2']").prop( "checked" );

Then I output these in a message to be sent via e-mail:

...<strong>Value 1</strong>: 1_val + '<br /><strong>Value 2</strong>: ' + 2_val + '<br />...

But in the message body I get the string with booleans true/false, and I would want to make some more user-friendly message like Yes/No. How can I change it?

Upvotes: 0

Views: 2858

Answers (4)

Victor H&#246;gemann
Victor H&#246;gemann

Reputation: 230

Probably far from being the best solution, but one way would be:

var YesNo = {
   'true' : 'Yes',
   'false' : 'No'
};

And use like this on your HTML fragment:

var html = '<strong>Value 1 :</strong>' 
    + YesNo[val_1] + '<strong>Value 2</strong>' + YesNo[val_2];

Upvotes: 1

StephenTG
StephenTG

Reputation: 2647

You could replace 1_val with (1_val ? 'Yes' : 'No') when you output it. (and do the same for 2_val) Alternatively, if you only use these variables for this output, you could do what tymeJV suggests.

Upvotes: 1

Aegis
Aegis

Reputation: 1789

You can use the ternary operator (which is essentially a short if-statement):

(2_val ? 'Yes' : 'No')

The value of this expression will be the string Yes if 2_val == true, else No.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Assign that value to the variable:

var 1_val = $("input[type='checkbox'][name='val_1']").prop( "checked" ) ? "Yes" : "No";

Upvotes: 6

Related Questions