Saeid
Saeid

Reputation: 448

Sequence of running code in jQuery

This is a part of my code:

$.post('category.php',{datatosend : datatosend},result);

function result(data) {
    $('#placeHolder').append('<select onchange="loadcats();" id="categoryPID" name="categoryPID" >').append(data).append('</select>');  
    alert($('#placeHolder').html());
    });
}

and I want to have this HTML in alert:

<select onchange="loadcats();" id="categoryPID" name="categoryPID">
<option value="37">computer</option><option value="38">mobile</option>
</select>

but the result is:

<select onchange="loadcats();" id="categoryPID" name="categoryPID"></select>
<option value="37">computer</option><option value="38">mobile</option>

why and what should I do?! Thanks.

Upvotes: 1

Views: 66

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

This comes up quite a lot, and it's due to a misunderstanding of what the .append() function does. People seem to get the impression that it's the same as concatenating HTML strings to the innerHTML property of the selected element(s), but it's not.

The .append() function works with actual DOM elements. If you pass in a string then it will parse that as HTML, create the elements, and then append those to the selected element(s). So when you do this:

$('#placeHolder').append('<select onchange="loadcats();" id="categoryPID" name="categoryPID" >')

It creates the entire <select> element (it doesn't care that you didn't close the tag, it does it for you), then appends that to #placeHolder. Then when you call .append(data), it again creates the option elements, then appends those after the <select>.

The best idea would be to create the <select> element individually, add the <option> elements to that, then append it to #placeHolder:

// create the entire <select> element
var select = $('<select onchange="loadcats();" id="categoryPID" name="categoryPID" >');
// append the <option> elements to it
select.append(data);
// append the <select> to #placeHolder
$('#placeHolder').append(select);
// then finally alert its HTML
alert($('#placeHolder').html());

It would actually be possible to chain the majority of those calls but I've split it out purely for the purposes of illustrating what's happening. The chained version would look something like this:

alert($('#placeHolder').append($('<select onchange="loadcats();" id="categoryPID" name="categoryPID" >').append(data)).html());

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

Try this:

$('#placeHolder').append('<select onchange="loadcats();" id="categoryPID" name="categoryPID" >');
$('#categoryPID').append(data);

Upvotes: 0

Related Questions