473,413 Members | 2,051 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

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

Expand|Select|Wrap|Line Numbers
  1.  
  2. <form id="10" method="post" action="">
  3.  
  4. <input type="text" name="name">
  5.  
  6. <input type="submit" name="submit" value="Submit">   
  7.  
  8. </form>
  9.  
  10.  
i am new to jQuery but my code is as follows....

Expand|Select|Wrap|Line Numbers
  1. $(function(){
  2.  var form_id = $("form").attr("id"); // output 10 
  3.  $("#submit").click(function(){      // onclick submit 
  4.    form_id = +1                      // increment by 1
  5.                                      // form_id = 2      
  6.       });
  7.     });
  8.  
This doesn't work as i think i need to set the id, or am i doing something completely wrong?
Nov 7 '10 #1
6 3434
Dormilich
8,658 Expert Mod 8TB
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
Nov 8 '10 #2
profile.php

Expand|Select|Wrap|Line Numbers
  1.  
  2. <div id="main" align="center">
  3.      <div id="addCommentContainer" align="left">
  4.     <p>Add a Comment</p>
  5.  
  6.     <form id="addCommentForm-10" method="post" action="">
  7.         <div>
  8.             <input type="hidden" name="name" id="name" />
  9.  
  10.             <label for="body">Comment Body</label>
  11.             <textarea name="body" id="body" cols="20" rows="1"></textarea>
  12.  
  13.             <input type="submit" id="submit" value="Submit" />
  14.         </div>    
  15.     </form>
  16. </div>
  17.  
  18.     <?php
  19. /*
  20. /    Output the comments one by one:
  21. */
  22.  
  23. foreach($comments as $c){
  24.     echo $c->markup();
  25.  
  26. }
  27. ?>
  28. <div id="showCommentsHere">   
  29.  
  30.  
  31. </div>
  32. </div>  
  33.  
submit.php....
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. // Error reporting:
  4. error_reporting(E_ALL^E_NOTICE);
  5.  
  6. include "database.php";
  7. include "comment.class.php";
  8.  
  9. /*
  10. /    This array is going to be populated with either
  11. /    the data that was sent to the script, or the
  12. /    error messages.
  13. /*/
  14.  
  15. $arr = array();
  16. $validates = Comment::validate($arr);
  17.  
  18. if($validates)
  19. {
  20.     /* Everything is OK, insert to database: */
  21.  
  22.     mysqli_query($mysqli,"INSERT INTO comments(name,url,email,body)
  23.                     VALUES (
  24.                         '".$arr['name']."',
  25.                         '".$arr['url']."',
  26.                         '".$arr['email']."',
  27.                         '".$arr['body']."'
  28.                     )");
  29.  
  30.     $arr['dt'] = date('r',time());
  31.     $arr['id'] = mysqli_insert_id($mysqli);
  32.  
  33.     /*
  34.     /    The data in $arr is escaped for the mysql query,
  35.     /    but we need the unescaped variables, so we apply,
  36.     /    stripslashes to all the elements in the array:
  37.     /*/
  38.  
  39.     $arr = array_map('stripslashes',$arr);
  40.  
  41.     $insertedComment = new Comment($arr);
  42.  
  43.     /* Outputting the markup of the just-inserted comment: */
  44.  
  45.     echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));
  46.  
  47. }
  48. else
  49. {
  50.     /* Outputtng the error messages */
  51.     echo '{"status":0,"errors":'.json_encode($arr).'}';
  52. }
  53.  
  54. ?>
  55.  
script.js...
Expand|Select|Wrap|Line Numbers
  1. $(document).ready(function(){
  2.     /* The following code is executed once the DOM is loaded */
  3.  
  4.     /* This flag will prevent multiple comment submits: */
  5.     var working = false;
  6.  
  7.     /* Listening for the submit event of the form: */
  8.     $('#addCommentForm').submit(function(e){
  9.  
  10.          e.preventDefault();
  11.         if(working) return false;
  12.  
  13.         working = true;
  14.         $('#submit').val('Working..');
  15.         $('span.error').remove();
  16.  
  17.         /* Sending the form fileds to submit.php: */
  18.         $.post('submit.php',$(this).serialize(),function(msg){
  19.  
  20.             working = false;
  21.             $('#submit').val('Submit');
  22.  
  23.             if(msg.status){
  24.  
  25.                 /    If the insert was successful, add the comment
  26.                 /    below the last one on the page with a slideDown effect
  27.                 /*/
  28.  
  29. $(msg.html).insertAfter('#addCommentContainer').hide().slideDown();
  30.                 $('#body').val('');
  31.             }
  32.             else {
  33.  
  34.                 /*
  35.                 /    If there were errors, loop through the
  36.                 /    msg.errors object and display them on the page 
  37.                 /*/
  38.  
  39.                 $.each(msg.errors,function(k,v){
  40.                     $('label[for='+k+']').append('<span class="error">'+v+'</span>');
  41.                 });
  42.             }
  43.         },'json');
  44.  
  45.     });
  46.  
  47. });
  48.  
comment.class.php....

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. require 'database.php';
  3.  
  4. class Comment
  5. {
  6.     private $data = array();
  7.  
  8.     public function __construct($row)
  9.     {
  10.         /*
  11.         /    The constructor
  12.         */
  13.  
  14.         $this->data = $row;
  15.     }
  16.  
  17.     public function markup()
  18.     {
  19.         /*
  20.         /    This method outputs the XHTML markup of the comment
  21.         */
  22.  
  23.         // Setting up an alias, so we don't have to write $this->data every time:
  24.         $d = &$this->data;
  25.  
  26.         $link_open = '';
  27.         $link_close = '';
  28.  
  29.         if($d['url']){
  30.  
  31.             // If the person has entered a URL when adding a comment,
  32.             // define opening and closing hyperlink tags
  33.  
  34.             $link_open = '<a href="'.$d['url'].'">';
  35.             $link_close =  '</a>';
  36.         }
  37.  
  38.         // Converting the time to a UNIX timestamp:
  39.         $d['dt'] = strtotime($d['dt']);
  40.  
  41.         // Needed for the default gravatar image:
  42.         $url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
  43.  
  44.         return '
  45.  
  46.             <div class="comment-10" align="left">
  47.                 <div class="avatar">
  48.                     '.$link_open.'
  49.                     <img src="image.jpg" />
  50.                     '.$link_close.'
  51.                 </div>
  52.  
  53.                 <div class="name">'.$link_open.$d['name'].$link_close.'</div>
  54.                 <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
  55.                 <p>'.$d['body'].'</p> 
  56.  
  57.                  <a href="#">Reply</a>
  58.  
  59.            </div>'; 
  60. }
  61.  
  62.     public static function validate(&$arr)
  63.     {
  64.         /*
  65.         /    This method is used to validate the data sent via AJAX.
  66.         /
  67.         /    It return true/false depending on whether the data is valid, and populates
  68.         /    the $arr array passed as a paremter (notice the ampersand above) with
  69.         /    either the valid input data, or the error messages.
  70.         */
  71.         require 'database.php';
  72.         $errors = array();
  73.         $data    = array();
  74.  
  75.         if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
  76.         {
  77.             // If the URL field was not populated with a valid URL,
  78.             // act as if no URL was entered at all:
  79.  
  80.             $url = '';
  81.         }
  82.  
  83.         // Using the filter with a custom callback function:
  84.  
  85.         if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
  86.         {
  87.             $errors['body'] = 'Please enter a comment body.';
  88.         }
  89.  
  90.         if(!empty($errors)){
  91.  
  92.             // If there are errors, copy the $errors array to $arr:
  93.  
  94.             $arr = $errors;
  95.             return false;
  96.         }
  97.  
  98.         // If the data is valid, sanitize all the data and copy it to $arr:
  99.  
  100.         foreach($data as $k=>$v){
  101.             $arr[$k] = mysqli_real_escape_string($mysqli,$v);
  102.         }
  103.  
  104.         // Ensure that the email is lower case:
  105.  
  106.         $arr['email'] = strtolower(trim($arr['email']));
  107.  
  108.         return true;
  109.     }
  110.  
  111.     private static function validate_text($str)
  112.     {
  113.         /*
  114.         /    This method is used internally as a FILTER_CALLBACK
  115.         */
  116.  
  117.         if(mb_strlen($str,'utf8')<1)
  118.             return false;
  119.  
  120.         // Encode all html special characters (<, >, ", & .. etc) and convert
  121.         // the new line characters to <br> tags:
  122.  
  123.         $str = nl2br(htmlspecialchars($str));
  124.  
  125.         // Remove the new line characters that are left
  126.         $str = str_replace(array(chr(10),chr(13)),'',$str);
  127.  
  128.         return $str;
  129.     }
  130. }
  131.  
  132. ?>
i would like to add a unique div id for every outputted comment..

i was thinking of adding something like this...

Expand|Select|Wrap|Line Numbers
  1. $('#addCommentForm').submit(function(){ // when submitted
  2.  
  3. var comment_id = $("form").attr("id"); // comment-10 
  4. var comment_id_split = str.split(-); // comment 10
  5. var comment_id_number = comment_id_split[1]; // 10
  6. 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
Nov 8 '10 #3
Dormilich
8,658 Expert Mod 8TB
is there any reason, why you would change the form ID on the client side?
Nov 8 '10 #4
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,
Nov 8 '10 #5
Dormilich
8,658 Expert Mod 8TB
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
Nov 8 '10 #6
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.php, 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
Nov 8 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

15
by: JR | last post by:
Hi. I hope someone out there who is more versed with JavaScript than I can help me with the following annoying problem. Here's the problem. I have a form with the following layout: Column A...
4
by: karenmiddleol | last post by:
I have the following form the user enters the From and to period and presses the Submit button and the form fields are cleared once the submit button is pressed. Is there a way I can keep the...
2
by: bbcrock | last post by:
I created a "cancel" button for my form at the clients' request, I accidentally copied a submit button and added an OnClick event- a very simple javascript.history function. It did not appear to...
3
by: Avi G | last post by:
Hi, how can i set a timer in VS2005 form that will click the button that is on the form every X time? THX
2
by: snowweb | last post by:
Hi, This is my first flash project! It would be great if someone could help me please. I have purchased a flash template which I have made some alterations to. My biggest alteration is that of...
2
by: dipesh10 | last post by:
I am doing one project with asp net 2.0 and c# ,i have master page and content page , in content page i have 10 text box and one submit button , when submit will click those text box need to...
1
by: Kirthikaiitm | last post by:
Hi, I have a image button (APPLY) On clicking apply button how to move the content from textbox to another textarea. I wrote the code in JScript. But once i click APPLY button the form is...
8
by: ShadowLocke | last post by:
Hi, I have an HTML button that i want to execute javascript on every mouse down that occurs. I'v tried using the onmousedown and the onclick events but the button only executes on every second...
3
by: ghjk | last post by:
I have a web page which is used to enter user data. In there I have 4 buttons named as "Submit, Confirm,Edit,Cancel". User should enter data and click "Submit " button. Then I want to display all...
3
by: newlearner | last post by:
Hi All I have an interview question What will happen if i click the submit button twice in a JSP. Will the second request be processed or not. Thanks new learner
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.