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>
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:
Firstly, the selector starts with
MytplReasons, so jQuery is going to look for an element of typeMytplReasons, and that doesn’t exist. What you wanted to do was to find elements matching.myClass option, in the HTML fragment contained inMytplReasons. To do that you can useMytplReasonsas the context:Secondly,
getreturns the underlying DOM element, not a jQuery object. DOM elements don’t have anattrmethod. You need to useeqinstead: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
optionelements in your fragment).A couple of other issues:
MyLocationMyLocationis already a jQuery object. You don’t need to pass it into jQuery again to use thehtmlmethodHere’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).