0

I have a some simple code igniter PHP code that I wish to validate to ensure that only 10 chars max can be typed in the Text area. I wish to use JavaScript for the validation. How can I integrate the both?

Below shows the PHP/codeigniter and rough javascript code that I am going to use.

Can I add the javascript as a 3rd parameter in the echo form_textarea method as described here?

PHP:

echo form_textarea('age',set_value('age',0));

JavaScript:

<script language="javascript" type="text/javascript">
function limitText(limitField,limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}
</script>

So would the following work? :

$js = 'onKeyDown="limitText(age,10)"';

echo form_textarea('age',set_value('age',0),$js);
2
  • what html code does echo form_textarea('age',set_value('age',0),$js); produce? Commented Feb 17, 2015 at 10:55
  • Just something to think about: What if the user has JavaScript disabled? It's handy to use both Server-Side and Client-Side Validation. Commented Feb 17, 2015 at 12:30

2 Answers 2

1

Instead, pass the value and the onKeyDown in the second argument. You could even include maxlength that works with text areas so you don't need to use your JavaScript function.

$options = array(
  "value" => 0,
  "onKeyDown" => "limitText(age, 10)",
  "maxlength" => 10 //only include if you want this instead of javascript
);

echo form_textarea('age', $options);
Sign up to request clarification or add additional context in comments.

6 Comments

thanks, however where do I put the javascript function within my code, Is it within the php tags?
No, you'd put it in the view, so in the html between the <body> tags. @user9991110000
can it not be put between the php tags, by using echo, e.g. <?php echo '<script> function()......</script>; ?>
It can be. @user9991110000
Your JavaScript doesn't do anything other than what maxlength does. Just use maxlength.
|
0

You can do this only with HTML:

  <textarea maxlength="50">
    Some text
  </textarea> 

This will work only on HTML5 supported browsers.

using javascript: html:

<textarea onchange="myFunction()"> </textarea>

javaScript:

<script>
function myFunction() {
    var x = document.getElementById("mySelect").length;
    if (x.length < 3) {
      alert("Some error msg!");
    }

}
</script>

To validate using codeIgniter take a at form validation documentation.

Comments

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.