Codeigniter Textarea的jQuery最小字符计数器
I'm struggling to get a minimum character counter to work with CI / jQuery. I want to be able to prevent form submission and display an alert if the user has entered too few chars. The form just submits as normal using the code:
function checktextarea(minLength) {
var textarea = jQuery('#field').value.length;
if(textarea < minLength) {
e.preventDefault();
alert('You need to enter at least ' + minLength ' + characters');
return false;
}
};
And in CI I have:
<?php $attributes = array ('onsubmit' => 'checktextarea(15)'); ?>
<?php echo form_open('controller/function', $attributes); ?>
// I know this is standard HTML
<textarea name="content" class="textarea_css" rows="10" cols="73" id="field"></textarea>
<?php echo form_submit('send', 'Submit Your Textarea'); ?>
<?php echo form_close(); ?>
Many thanks for any help!
You have a reference to an e
var, which isn't in the scope of your function. I'm assuming you're trying to cancel an event, but you should do that in your parent function.
The line e.preventDefault();
causes compile errors.
Next, you are accessing the value of the text area improperly, try jQuery('#field').val().length;
.
Finally, the line alert('You need to enter at least ' + minLength ' + characters');
is malformed, it should read alert('You need to enter at least ' + minLength + ' characters');
Added a fiddle, just for fun and proof: http://jsfiddle.net/TSbK8/7/
You're jQuery statement getting the length isn't quite right. Instead of var textarea = jQuery('#field').value.length;
try var textarea = jQuery('#field').val().length;
.