Search code examples
jqueryhtml-selectclone

clone and add html fragment, then set select/option value


On a click event, I want to add a fragment of html code which includes a select/option box, to a page. First I get the appropriate location to put it, then take fragment of code in a javascript string, turn it into a jquery object. Next I want to select the appropriate value in the select/option box. In this example, I am having trouble targeting the correct select/option box.

tplReasons = "<td>Reason</td>\n\
    <td class='none'>\n\
    <div data-role='fieldcontain' class='select'>\n\
        <select class='myClass' name='select-choice-1' id='select-choice-1'>\n\
            <option value='01'>option 1</option>\n\
            <option value='02'>option 2</option>\n\
            <option value='03'>option 3</option>\n\
        </select>\n\
    </div>\n\
    </td>\n";



$('.my_class').live('change', function (){  
   var MyLocation = $('some_div');
   var MytplReasons = $(tplReasons);                        
   if(someCondition == 2){
     $('MytplReasons .myClass option').get(2).attr('selected', 'selected');
   }
   // (add jquery mobile formatting)
   MytplReasons.appendTo(MyLocation).trigger('create');                 
});     

</script>

Solution

  • Assuming I've understood what you're trying to do, there are several issues with your code. What I think you're trying to do is set the selected option in the HTML fragment (presumably you're then going to append that HTML fragment to the DOM).

    This is the line that causes the problems:

    $('MytplReasons .myClass option').get(6).attr('selected', 'selected');
    

    Firstly, the selector starts with MytplReasons, so jQuery is going to look for an element of type MytplReasons, and that doesn't exist. What you wanted to do was to find elements matching .myClass option, in the HTML fragment contained in MytplReasons. To do that you can use MytplReasons as the context:

    $('.myClass option', MytplReasons)
    

    Secondly, get returns the underlying DOM element, not a jQuery object. DOM elements don't have an attr method. You need to use eq instead:

    $('.myClass option', MytplReasons).eq(6).attr('selected', 'selected');
    

    A further problem (perhaps just because you have shortened the code in the question) is that there isn't a matching element at index 6 (there are only 3 option elements in your fragment).

    A couple of other issues:

    1. You are missing a semi-colon after the declaration of MyLocation
    2. MyLocation is already a jQuery object. You don't need to pass it into jQuery again to use the html method

    Here's a working example of your code (modified slightly, so the HTML fragment is appended to a table, so you can actually see the result).