0

I have a site that appends a textbox to a div when the user clicks a button. The textbox works great. Now, I would like to generate a unique number for the id of each box. The following code is giving me 0 as the id of each box. I'm trying to get them to go 1,2,3,4...

Code:

<?php $x=0; ?> 

$("#add").click(function(){
    $('#boxes').append(<input type="text" id="<?php echo $x; $x++; ?>">);
});

2 Answers 2

1

PHP code is excuted earlier before the javascript code is executed. But in your code example you try to execute both at the same time. That is just not the case.

Instead of a PHP variable you need to use a javascript variable:

var x = 0;
$("#add").click(function() {
    $('#boxes').append('<input type="text" id="' + ++x + '">');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, there is no need for PHP in this circumstance. Javascript has similar variable, and 'counting' features
0

You can use PHP variable as base for your javascript variable or just plain javascript.

//note, $x can be anything e.g. 1
var boxID = '<?php echo $x; ?>'; 

$("#add").click(function(){
    //insert new box, increase boxID
    $('#boxes').append('<input type="text" id="'+boxID+'">');
    boxID++;
});

1 Comment

In this case, x must be an interger. If it will not be an interger, you need to wrap the php tag in quotes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.