tags:

views:

42

answers:

3

My form has several <p> elements which are added dynamically. This is how one would look:

<p id="numbox-1" class="numbox">1</p>

I need to set up a function so that when a button is clicked I get the id (the id's will be labeled numbox-1, numbox-2, etc) and the value of the p element for all of them on the page.

I need to pass the values to a php script that will process them, it would be nice if I could get the data as an array so I can use a for loop in php.

I have been using JSON to pass data, but Im not sure if that's the best way to go on this, please advise, thanks-

A: 

I'm not sure what you mean by 'checking' buttons, but maybe this will help a bit.

$(function(){
  $("#send-button").click(function(){
    var data = [];
    $('.numbox').each(function(){
      var $this = $(this);
      data.push( {
        id: $this.attr('id'),
        value: $this.html()
      } );
    });
    $.post('myurl.php', { numboxes: data });
  });
});

When #send-button is clicked, it creates a return array that contains objects for each numbox id and value. It then posts that array to the server.

BBonifield
`.val()` is for input elements, this is a `<p>` and there's no need for `.attr("id")` you can simple to `this.id`. Also, overall you can use `.map()` which is specifically for this purpose.
Nick Craver
Yeah the `val()` was a typo on my part. While i agree that `this.id` is proper, I just gave the jQuery version as to not confuse people that don't know the raw JavaScript equivalents. That said, I do agree that it's a good usage of `.map()`.
BBonifield
+4  A: 

You can use .map() for this, for example:

var arr = $('.numbox').map(function(){
            return { name: this.id, value: this.innerHTML };
          });

Then you could pass this as the data argument, for example:

$.post("mypage.php", arr);

This would result in a POST of the name/value pairs, like this:

numbox-1=1&numbox-2=XX....
Nick Craver
This works perfectly. Quick follow up - is it possible to append another value pair the the arr - if so how?
jriggs
@jriggs - you can add to `arr` before using it, for example `arr.push({ name: 'someName', value: 'someValue' });` *then* use it :)
Nick Craver
A: 
function getNumbox()
{
    var objNumbox = new Array();
    $('.numbox').each(function(index){
        objNumbox[index] = $(this);
    });
    return objNumbox;
}

//Test it out
$(document).ready(function(){
    var test = getNumbox();
    $(test).each(function(index){
        alert('ID: ' + $(test[index]).attr('id') + ' Text: ' + $(test[index]).text());
    });
});
alexm
On second though I'd use .map() as mentioned in the post above!
alexm