278204
278204

Reputation: 598

Button in list from Javascript loop throws back the of the list

I got this javascript loop which generates a unordered list with maybe 50 list items.. Now I want to put a button in every list item which stores the content in a database. Think retweet.

I figured out a way which is put the button and the content from the listitem within a hidden input in the loop but that seems like a bad shortcut. Like this:

html += "<form action=\"add.php\" method=\"post\"><input type=\"hidden\" value=\"" + listitem + "\" name=\"item\"\/>";
    html += "<input type=\"submit\" value=\"repost\" \/><\/form>";

Using jQuery seems much more subtle and more like the right thing to do. I've gotten this far:

    $("button").click(function() 
    var value = ($(this).text());
$.post('add.php',{value:value};
});

With a button in the loop instead of the input. But I can't even get the jQuery to response to the button click. Is there anyway this is possible or should I just go with the shortcut?!

The loop =

  var html = "<li><h2 class=\"postTitle\">" + title + " <\/h2>";
                html += "<p id=\"postText\" class=\"postText\">" + text + "</p></li>";
$('#Content').append($(html));

And the html where the loop ends up:

<ul id="list">
<div id="Content">
    &nbsp;
</div>
</ul>

Upvotes: 0

Views: 226

Answers (3)

balkon_smoke
balkon_smoke

Reputation: 1206

First, if you send your data via AJAX $.post, you should prevent submitting a form:

$("button[type=submit]").click(function(oEvent) {
    oEvent.preventDefault();
    // or in the end of handler
    return false;
});

Second, <input> and <button> elements will return nothing in $(elem).text(), to get a value you should use $(elem).val() method.

Third, use the id attribute for HTML elements, this will help you manage DOM easier.

Upvotes: 0

Teun Pronk
Teun Pronk

Reputation: 1399

Try giving your button a unique id? resulting in:

$('#myId').click(function(){
//your code here
});

That is much better to specify. You can also try to give it a class and an id

$('.myClass').click(function(){
var myButton = $(this).attr('id');
if(myButton == 'myId'){ do this} else if(myButton == 'myOtherId'){do this}

});

that way you can handle several buttons in one function, and if there are many buttons if statements will make your code look all messed up and you can use a select case :)

Upvotes: 0

jabclab
jabclab

Reputation: 15052

From the code above the jQuery selector being used ("button") will not match anything in your code as you've used an input for the button; try:

$("input[type=submit]").click(function () {
    ...
});

Ideally use a more targeted selector as I presume you don't want every submit button to do this :)

Upvotes: 1

Related Questions