How do I attach a div to the corresponding li list

Hi guys,

I have a loop like this:

<ul>
    <?php foreach($questions as $question) { ?>
        <li class=position_relative>
            <div class=floatleft>
                <?php echo $question['firsttolast']; ?>
            </div>
            <a href="form.php" class=floatright>Answer</a>
        </li>
    <?php } ?>
</ul>

I want to attach a form to the corresponding li item if someone click on the link to answer the question with the code below:

var doc = document
  , ans = doc.getElementsByClassName('floatright');
for ( var i = 0, j = ans.length; i < j; i += 1 ) {
    (function(x) {
        ans[x].addEventListener('click', function(e) {
            e.preventDefault();
            var url = this.getAttribute("href");
            var xhr = newXMLHttpRequest();
            xhr.open("GET", url, false);
            if (xhr.readyState == 4) {
                var div = doc.createElement('div');
                div.innerHTML = xhr.responseText;
                // HOW TO APPEND IT TO THE <LI>?
            }
            xhr.send();
        });
    })(i);
}

How do I do it?
I want it be like a thread comment like in facebok (no real time need).
The current practice I use is going to the form page and return when submit.
I want to add ajax to this case.

thank you,

Hi, Nico :smiley:

Can you use jQuery in your project? If so, I can write an example how to achieve this with jQuery for you.

Thanks,

I don’t use jQuery. People say it was bad and use vanilla JavaScript instead, So I don’t use it ever since I heard of vanilla JavaScript long time ago.

People are wrong. It helps to save huge amount of time and makes you code shorter and cleaner. But, that’s your choice.

Okay Space Captain :blush:
You can show me jQuery code. I’ll use it.

Thanks

Here is it: http://jsfiddle.net/7qbb6o7t/2/
And here is form html: https://raw.githubusercontent.com/r2git/sitepoint/master/demo.response.html

Thank you,

Wow! That’s great. I’ve never seen something like this with jQuery.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.