Reputation: 4324
I have a piece of code where the user is able to add a new row into a table:
Below is the code:
var qnum = 1;
function insertQuestion(form) {
var $tr = $("<tr></tr>");
var $qid = $("<td class='qid'>" + qnum + "</td>");
var $options = $("<td class='option'></td>");
$('.gridTxt').each(function() {
var $this = $(this);
var $optionsText = $("<input type='text' class='gridTxt' readonly='readonly' /><span href='#' class='showGrid'>[Open Grid]</span>").attr('name', $this.attr('name')).attr('value', $this.val())
$options.append($optionsText);
});
$tr.append($qid);
$tr.append($options);
$('#qandatbl').append($tr);
form.numberOfQuestions.value = qnum;
++qnum;
$("#questionNum").text(qnum);
form.questionText.value = "";
}
What I want to do though is to only create a certain maximum number of rows. The maximum amount of rows that can be added has to match the number which has been posted from another page:
{$_POST['textQuestion']}
So for example if the number of the $_POST['textQuestion']
is 20, then no more than 20 rows can be created.
How can this be done?
Upvotes: 0
Views: 72
Reputation: 29160
If this JS is embedded in a PHP File, you can add a line to your JS function like
function insertQuestion(form) {
if (qnum>=<?php echo (int)$_POST['textQuestion']; ?>) return();
// the rest of your code
++qnum;
}
This will render as:
function insertQuestion(form) {
if (qnum>=20) return();
// the rest of your code
++qnum;
}
OR
If the JS is not embedded in your PHP, you will need to set the appropriate JS variable from within PHP ..perhaps like this...
<script type="text/javascript">
var maxRows=<?php echo (int)$_POST['textQuestion']; ?>;
</script>
then in your JS file...
function insertQuestion(form) {
if (qnum>=maxRows) return();
// the rest of your code
++qnum;
}
Upvotes: 1