user3282242
user3282242

Reputation: 13

How to change div content dynamically

I was looking for a "change div content in php without refreshing a page" and i found the following and applied it:

<script>
$(document).ready(function(){
$('#wwage').submit(function() 
{
    $.ajax(
    {
        data: $(this).serialize(),
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        success: function(response) 
        { 
            $('#wwritemsg').html(response);
        }
    });
    return false;
});
});
</script>

<?php 
    $i=1;
while ( $i<5) 
{ ?>
       <form action="response.php" method="post" name="swages" id="wwage">
          <input name="wpw<?php echo $i; ?>" type="text" value="<?php echo $foo; ?>" />
       <input name="setfoo" type="submit" value="Submit" />
       <div id="wwritemsg">
          <?php  echo "Default pre-submit text.";?>
       </div>
       $i=$i+1;
    }

This code would create 4 forms with 1 input box and a submit button each. And the replace div ajax script would not work for selective div's. it would overwrite only 1.

Now, the logical conclusion would be to append "i" to the form id and the div id, creating unique ones, and modify the ajax code to accept these dynamically created id's. However I am lacking in ajax knowledge and I do not know how I could make the ajax function work with every form.

(I could generate 4 ajax code blocks with a php FOR/WHILE cycle(in this example), but it seems not very efficient if for example I would have 100 forms to apply these functions to. The cycle would create literally 100 unique id ajax scripts for each form/div )

Upvotes: 1

Views: 3625

Answers (2)

jonsuh
jonsuh

Reputation: 2875

The key is to use classes rather than an ID.

HTML:

<form action="response.php" method="post" name="swages" class="wwage wwage-<?php echo $i; ?>">

JavaScript:

$('.wwage').submit(function()

You'll notice that in the HTML portion during the while loop it echos a secondary class for each form that's "unique" class="wwage wwage-<?php echo $i; ?>"> that way if for some reason you wanted to select one of the forms from another, you can easily do it by $(".wwage-4") where the 4 would indicate the appropriate $i value in the loop.

Upvotes: 1

David Lin
David Lin

Reputation: 13353

The trick is to use Class selector instead of ID selector:

 $('.wwage').submit(function() {
    alert(this.id);
    event.preventDefault();
 }
 ) ;

look at this fiddle http://jsfiddle.net/kdRY7/

Upvotes: 1

Related Questions