0

My jquery/javascript problem: I need to return the code of an html select input, but I also need to set the selected option dynamically.

function(data){
  return '<select class="form-control"'+
            '<option value="1"'+ if(data === 1){selected}+'>Name 1</option>'+
            '<option value="2"'+ if(data === 2){selected}+'>Name 2</option>'+
            '<option value="3">Name 3</option>'+
          '</select>';
}

Attention: using $(selector).val(data); AFTER the html is rendered is NOT an option (unfortunately)

3 Answers 3

5

You can't put an if inside of a sting, but you could use a ternary operator.

function(data){
    return '<select class="form-control"'+
            '<option value="1"'+(data === 1 ? ' selected' : '')+'>Name 1</option>'+
            '<option value="2"'+(data === 2 ? ' selected' : '')+'>Name 2</option>'+
            '<option value="3">Name 3</option>'+
          '</select>';
}
Sign up to request clarification or add additional context in comments.

3 Comments

You need to put selected in quotes (i.e., ' selected'), otherwise, it will try to interpret it as a variable.
@talemyn ahh i was figuring it was a variable from outside the scope of the function, I'll change it.
Very good. Thank you very much. I'll accept your answer. Tested and working great. I upvoted all 3 answers as they provided working alternatives
2

if statements do not evaluate to a value. You cannot embed them inside an expression this way.

Your options are to use the ternary operator, or to build your string over several statements.

function(data){
  var str = '<select class="form-control"'+
            '<option value="1"';

  if(data === 1){str += "selected"}

  str += '>Name 1</option>'+
            '<option value="2"';

  if(data === 2){str += "selected"}

  str += '>Name 2</option>'+
            '<option value="3">Name 3</option>'+
          '</select>';
  return str;
}

Comments

1

You can do this with jQuery in a much cleaner fashion:

function(data){
     return   $('<select class="form-control"'+
                '<option value="1">Name 1</option>'+
                '<option value="2">Name 2</option>'+
                '<option value="3">Name 3</option>'+
              '</select>').val(data);
}

EDIT: After further testing i found that converting the jquery object to html doesn't preserve the selected attribute. Alternatively, the function can return the jquery object then .appendTo the element as is.

2 Comments

It should be noted this will return a jQuery object instead of a string.
yes, edited although returning the jquery object can be more useful.

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.