I have a comment text box in a loop that I need to apply some jQuery functions to.
- I need to resize the text box according to text entered.
- I need to check length of text. I do not want the user to enter more than 100 characters.
- I need the user to be able to press enter and that will submit the comment.
- I also need to submit the form without leaving the page.
I know how to do all functions individually. I would like to combine all the functions into one. Here is what I have:
<?php
$i = 0; //For the id of the textarea
while (/* Retrieve information from the database */)
{
$th_id = $row['th_id']; //id for the original comment/post.
echo "<form method='post'>
<input type='hidden' name='cb_id' value='".$th_id."' >
<textarea onkeyup='addcom()'
onkeydown='addcom()'
placeholder='Press enter to comment'>
</form>;
}
?>
And here is the JavaScript code:
<script type="text/javascript">
<!--
function addcom()
{
var ch,l;
ch = $('.addcom').val();
l = ch.length;
if (l == 30)
{
$('.addcom').css({'height':'40px'});
}
//More code until maximum number of characters is reached
else if(l >= 100)
{
ch = ch.substring(0, 100);
$('.addcom').val(ch);
}
}
-->
</script>
How do I retrieve the information for the textfield and the hidden input field? Also, how do I trigger the event that if keycode 13 is pressed then the form gets submitted?
(The above JavaScript code is changing all the textarea in the loop as I expected.)
I would create a jQuery plugin for the textboxes:
Then in your original loop you can just attach this plugin to your text boxes:
I didn’t test any code here, but the premise is sound.
If you do this kind of stuff a lot there is another jQuery plugin called jQuery UI which has a widget factory that is perfect for creating reusable widgets (or extensible plugins) using their framework.
Edit
I have created a JSFiddle Demo of the plugin.
I started off by modifying your HTML and removing the onkeyup and onkeydown events.
Old HTML:
New HTML:
Then I created the following jquery code:
The first section will create the plugin. I recommend renaming it so that it does not use the name
myPlugin. The plugin binds a keypress event to the textarea and performs your various actions.The second section locates all of the textarea elements and inits the plugin for each textarea.
NOTE:
I did not write all of the code for you to do the form submittal. If you need help with that, I would suggest creating another post on here asking specifically for help with that.