0

I have a javascript variable that is a consolidation of many different lines of text (html markup). See below. the info from the image property of the data object I'm injecting into this function may or may not be blank. So, I want a basic if statement to check if it is blank and output some other text if it is.

function(data) {

    var div = [
        <a href="/profile/'+data.message.name+'">',
            if (data.message.image == "") {
                // Some other string
            }
            <img src="/images/profiles/'+data.message.image+'" alt="#"/>',
        </a>',  
    ].join('');
}

Is it possible to nest an If statement in a variable like this? If so, what's the proper syntax?

Thanks!

4
  • 1
    Conditional (ternary) Operator Commented Feb 9, 2016 at 4:19
  • 1
    You can't mix JavaScript and HTML like that... Commented Feb 9, 2016 at 4:22
  • Thanks, Arun. That worked. Commented Feb 9, 2016 at 4:29
  • It helps if you post code without obvious syntax errors. Commented Feb 9, 2016 at 4:31

3 Answers 3

1

Conditional (Ternary) Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax

variablename = (condition) ? value1:value2 
Sign up to request clarification or add additional context in comments.

Comments

0

I don't know for what you want to write this kind of code you can use Jquery append method for your solution.

For your code this will work

div = []
div.push '<a href="/profile/'+data.message.name+'">'
if data.message.image == ""
    //do something
    div.push "someting"
div.push '<img src="/images/profiles/'+data.message.image+'" alt="#"/>'
div.push '</a>'
div.join('')

This code is written in coffee but you will understand it.

Comments

0

"" will be falsey value hence you could try the same using || operators.

Try this:

function test(data) {
  var image = 'Some other string';
  var div = [
    '<a href="/profile/' + data.message.name + '">',
    '<img src="/images/profiles/' + (data.message.image || image) + '" alt="#"/>',
    '</a>'
  ].join('');
  alert(div);
}
test({
  message: {
    name: 'Test Name',
    image: ''
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.