473,791 Members | 3,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

69 New Member
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 3511
Dormilich
8,658 Recognized Expert Moderator Expert
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
luke noob
69 New Member
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.p hp....

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 Recognized Expert Moderator Expert
is there any reason, why you would change the form ID on the client side?
Nov 8 '10 #4
luke noob
69 New Member
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 Recognized Expert Moderator Expert
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
luke noob
69 New Member
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
Nov 8 '10 #7

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

Similar topics

15
2560
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 Column B Column C data 4 radio buttons more data .... ... ... .... ... ...
4
9905
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 Form fields visible and not cleared. Also when I display the message I want the original form cleared in a different version of this page how can I clear the form completely when I display the data entered from the Response statements I do not...
2
2055
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 work at all- it kept submitting the form. I changed the submit button to a plain old button and it worked fine. Can anyone explain how the browser works with a javascript onClick event ona submit button? Does it automatically submit the form...
3
2914
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
5183
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 adding a contact form to it. I am comfortable with PHP, so have done the server side code in PHP. but I can't seem to get the button on my form to trigger my code. I've studied many tutorials about this, but none of them are close enough to my own...
2
1405
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 validate . i have written java script function in content page ,But when i click submit button it will execute server side code when java script function returns false . i dont know how to do in ASPnet 2.0 please help any body ....
1
2657
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 getting refreshed and the content in test area get vanished. How to retain the value on text area or how to avoid refreshing form on clicking image APPLY button.My button is <input type="image" src=/images/...> Pls. help regards, Kirthika
8
2120
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 click. This button is meant to increment once on every click, I dont want the user double clicking for every increment. Is there a way to make a button execute on every click? <input id="btnMoveUp" style="left: 465px; position: absolute; top:...
3
4239
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 information he entered and when user click confirm button only it should submit to the DB. Could you please tell me what is the best way? Do I need to use java script? How can I keep the form data after user click on submit button? <form...
3
5524
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
9669
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9517
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10156
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9030
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5435
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.