how can i increment the form id by 1 every time i click submit button?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • luke noob
    New Member
    • Aug 2009
    • 69

    how can i increment the form id by 1 every time i click submit button?

    I would like to use jquery, but couldnt find a subject on that so posted this in javascript hope thats ok.

    my HTML form is like this

    [code=html]

    <form id="10" method="post" action="">

    <input type="text" name="name">

    <input type="submit" name="submit" value="Submit">

    </form>

    [/code]

    i am new to jQuery but my code is as follows....

    [code=javascript]
    $(function(){
    var form_id = $("form").attr( "id"); // output 10
    $("#submit").cl ick(function(){ // onclick submit
    form_id = +1 // increment by 1
    // form_id = 2
    });
    });
    [/code]

    This doesn't work as i think i need to set the id, or am i doing something completely wrong?
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    there are several problems:
    - an ID must only start with a letter or an underscore
    - changing a string (the ID value) does not change anything in the HTML Document
    - = +1 simply assigns 1
    - + is also the string concatenation operator

    Comment

    • luke noob
      New Member
      • Aug 2009
      • 69

      #3
      profile.php

      [code=php]

      <div id="main" align="center">
      <div id="addCommentC ontainer" align="left">
      <p>Add a Comment</p>

      <form id="addCommentF orm-10" method="post" action="">
      <div>
      <input type="hidden" name="name" id="name" />

      <label for="body">Comm ent Body</label>
      <textarea name="body" id="body" cols="20" rows="1"></textarea>

      <input type="submit" id="submit" value="Submit" />
      </div>
      </form>
      </div>

      <?php
      /*
      / Output the comments one by one:
      */

      foreach($commen ts as $c){
      echo $c->markup();

      }
      ?>
      <div id="showComment sHere">


      </div>
      </div>
      [/code]
      submit.php....
      [code=php]
      <?php

      // Error reporting:
      error_reporting (E_ALL^E_NOTICE );

      include "database.p hp";
      include "comment.class. php";

      /*
      / This array is going to be populated with either
      / the data that was sent to the script, or the
      / error messages.
      /*/

      $arr = array();
      $validates = Comment::valida te($arr);

      if($validates)
      {
      /* Everything is OK, insert to database: */

      mysqli_query($m ysqli,"INSERT INTO comments(name,u rl,email,body)
      VALUES (
      '".$arr['name']."',
      '".$arr['url']."',
      '".$arr['email']."',
      '".$arr['body']."'
      )");

      $arr['dt'] = date('r',time() );
      $arr['id'] = mysqli_insert_i d($mysqli);

      /*
      / The data in $arr is escaped for the mysql query,
      / but we need the unescaped variables, so we apply,
      / stripslashes to all the elements in the array:
      /*/

      $arr = array_map('stri pslashes',$arr) ;

      $insertedCommen t = new Comment($arr);

      /* Outputting the markup of the just-inserted comment: */

      echo json_encode(arr ay('status'=>1, 'html'=>$insert edComment->markup()));

      }
      else
      {
      /* Outputtng the error messages */
      echo '{"status":0,"e rrors":'.json_e ncode($arr).'}' ;
      }

      ?>
      [/code]
      script.js...
      [code=javascript]
      $(document).rea dy(function(){
      /* The following code is executed once the DOM is loaded */

      /* This flag will prevent multiple comment submits: */
      var working = false;

      /* Listening for the submit event of the form: */
      $('#addCommentF orm').submit(fu nction(e){

      e.preventDefaul t();
      if(working) return false;

      working = true;
      $('#submit').va l('Working..');
      $('span.error') .remove();

      /* Sending the form fileds to submit.php: */
      $.post('submit. php',$(this).se rialize(),funct ion(msg){

      working = false;
      $('#submit').va l('Submit');

      if(msg.status){

      / If the insert was successful, add the comment
      / below the last one on the page with a slideDown effect
      /*/

      $(msg.html).ins ertAfter('#addC ommentContainer ').hide().slide Down();
      $('#body').val( '');
      }
      else {

      /*
      / If there were errors, loop through the
      / msg.errors object and display them on the page
      /*/

      $.each(msg.erro rs,function(k,v ){
      $('label[for='+k+']').append('<spa n class="error">' +v+'</span>');
      });
      }
      },'json');

      });

      });
      [/code]

      comment.class.p hp....

      [code=php]
      <?php
      require 'database.php';

      class Comment
      {
      private $data = array();

      public function __construct($ro w)
      {
      /*
      / The constructor
      */

      $this->data = $row;
      }

      public function markup()
      {
      /*
      / This method outputs the XHTML markup of the comment
      */

      // Setting up an alias, so we don't have to write $this->data every time:
      $d = &$this->data;

      $link_open = '';
      $link_close = '';

      if($d['url']){

      // If the person has entered a URL when adding a comment,
      // define opening and closing hyperlink tags

      $link_open = '<a href="'.$d['url'].'">';
      $link_close = '</a>';
      }

      // Converting the time to a UNIX timestamp:
      $d['dt'] = strtotime($d['dt']);

      // Needed for the default gravatar image:
      $url = 'http://'.dirname($_SER VER['SERVER_NAME'].$_SERVER["REQUEST_UR I"]).'/img/default_avatar. gif';

      return '

      <div class="comment-10" align="left">
      <div class="avatar">
      '.$link_open.'
      <img src="image.jpg" />
      '.$link_close.'
      </div>

      <div class="name">'. $link_open.$d['name'].$link_close.'</div>
      <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
      <p>'.$d['body'].'</p>

      <a href="#">Reply</a>

      </div>';
      }

      public static function validate(&$arr)
      {
      /*
      / This method is used to validate the data sent via AJAX.
      /
      / It return true/false depending on whether the data is valid, and populates
      / the $arr array passed as a paremter (notice the ampersand above) with
      / either the valid input data, or the error messages.
      */
      require 'database.php';
      $errors = array();
      $data = array();

      if(!($data['url'] = filter_input(IN PUT_POST,'url', FILTER_VALIDATE _URL)))
      {
      // If the URL field was not populated with a valid URL,
      // act as if no URL was entered at all:

      $url = '';
      }

      // Using the filter with a custom callback function:

      if(!($data['body'] = filter_input(IN PUT_POST,'body' ,FILTER_CALLBAC K,array('option s'=>'Comment::v alidate_text')) ))
      {
      $errors['body'] = 'Please enter a comment body.';
      }

      if(!empty($erro rs)){

      // If there are errors, copy the $errors array to $arr:

      $arr = $errors;
      return false;
      }

      // If the data is valid, sanitize all the data and copy it to $arr:

      foreach($data as $k=>$v){
      $arr[$k] = mysqli_real_esc ape_string($mys qli,$v);
      }

      // Ensure that the email is lower case:

      $arr['email'] = strtolower(trim ($arr['email']));

      return true;
      }

      private static function validate_text($ str)
      {
      /*
      / This method is used internally as a FILTER_CALLBACK
      */

      if(mb_strlen($s tr,'utf8')<1)
      return false;

      // Encode all html special characters (<, >, ", & .. etc) and convert
      // the new line characters to <br> tags:

      $str = nl2br(htmlspeci alchars($str));

      // Remove the new line characters that are left
      $str = str_replace(arr ay(chr(10),chr( 13)),'',$str);

      return $str;
      }
      }

      ?>[/code]

      i would like to add a unique div id for every outputted comment..

      i was thinking of adding something like this...

      Code:
      $('#addCommentForm').submit(function(){ // when submitted
      
      var comment_id = $("form").attr("id"); // comment-10 
      var comment_id_split = str.split(-); // comment 10
      var comment_id_number = comment_id_split[1]; // 10
      var comment_update_number_for_next_comment = comment_id_number + 1; // 11
      but not sure where to put the code, and how to out out it in every click, or even if its right, please could you help,

      i need to add a unique div id
      Last edited by Dormilich; Nov 8 '10, 02:45 PM. Reason: some minor space clean-up

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        is there any reason, why you would change the form ID on the client side?

        Comment

        • luke noob
          New Member
          • Aug 2009
          • 69

          #5
          say i have an upload form on the page where ppl can upload pictures, the first picture will have a comment box under it with a wrapped in div comment_id_1 and every other comment that goes to that picture will be div comment_id_1, then the next uploaded picture will be comment_id_2 and so on, the comments will be uploaded to the database and put back in the right order by selecting all comments WHERE picture id=$picture_id and comment_id = $comment_id order by time DESC, so that on 1 page they all line up with the right pictures. so each comment div will need a unique comment_id, hope that explains it a bit better, im really struggling to understand how to go about this,

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            so far that’s good, but you have to do that on the server side (i.e. in PHP). JavaScript doesn’t help you there.

            besides, when you submit the form (make a comment) the form/div ID is not sent back.

            you can for instance put the comment and picture ID as URL parameter in the form action
            Last edited by Dormilich; Nov 8 '10, 03:24 PM.

            Comment

            • luke noob
              New Member
              • Aug 2009
              • 69

              #7
              sorry i understand what your saying i made a mistake, i would like to change the out putted div class="comment-10" on comment.class.p hp, the form id on index.php doesnt need to be changed, sorry ignore the form on index.php, that is just to show where the form is submited from and i have made changes and got rid of the form id now

              Comment

              Working...