FlyingCat
FlyingCat

Reputation: 14280

Detect how many times the users have click the button

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());
    }
}

Upvotes: 1

Views: 394

Answers (2)

Zuul
Zuul

Reputation: 16269

$('#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....

Upvotes: 1

karim79
karim79

Reputation: 342715

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);

Upvotes: 1

Related Questions