views:

49

answers:

2

Hello guys. Just want to know if there is a way to detect how many times a user has clicked a button by using Jquery.

My main application has a button that can add input fields depend on the users. He/She can adds as many input fields as they need. When they submit the form, The add page will add the data to my database. My current idea is to create a hidden input field and set the value to zero. Every time a user clicks the button, jquery would update the attribute of the hidden input field value. Then the "add page" can detect the loop time. See the example below.

I just want to know if there are better practices to do this. Thanks for the helps.

main page

<form method='post' action='add.php'>

//omit
    <input type="hidden" id="add" name="add" value="0"/>
    <input type="button" id="addMatch" value="Add a match"/>
//omit

</form>

jquery

$(document).ready(function(){

    var a =0;       
    $("#addMatch").live('click', function(){
        //the input field will append //as many as the user wants.
        $('#table').append("<input name='match"+a+"Name' />");

        a++;

        $('#add').attr('value', 'a');  //pass the a value to hidden input field

        return false;
    });
});

Add Page

$a=$_POST['a']; //

for($k=0;$k<$a;$k++){
    //get all matchName input field
    $matchName=$_POST['match'.$k.'Name'];

    //insert the match
    $updateQuery=mysql_query("INSERT INTO game (team)
                                          values('$matchName')",$connection);

    if(!$updateQuery){
        DIE('mysql Error:'+mysql_error());
    }
}
+1  A: 

I'm a bit confused. After this:

$('#add').attr('name', 'a');  //pass the a value to hidden input field

shouldn't you actually store the value of a?

$('#add').attr('name', 'a').val(a);
karim79
Yes. I missed that. Thanks.and I should make it $('#add').attr('value', 'a').val(a);
Jerry
+1  A: 

$('#add').attr('name', 'a').val(a); ????

That's not correct, you should use:

$('#add').attr('value', a);
send the content of the "a" variable to the "value" property of element with ID "add"

I do believe that's what you want to do....

Zuul
I am not sure why, but your code create <input id='add' name='add' value='a'/>Thanks for the reply though. +1
Jerry
Hi, it's on production on several projects...are you sending the value to "a" variable correcty?var a = something;$("#add").attr("value", a);
Zuul