Link to home
Start Free TrialLog in
Avatar of alex4544
alex4544

asked on

Change substr input to lowercase by percentage of field

I have some javascript on a php page attached to an input field to change the letters to lowercase

what I want to do is only change the input to lowercase if a percentage (80%) of that field is capital letters

Attached current code which changes first letter to capital and rest to lowercase
<input type onblur="this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();"

Open in new window

Avatar of HonorGod
HonorGod
Flag of United States of America image

80% or more?  Or exactly 80%

Something like this perhaps?

<input type='text' onblur='lowerCheck(this)'>


<script type='text/javascript'>
  function lowerCheck( this ) {
    if ( this && this.nodeName == 'INPUT' ) {
      var text = this.value
      var up   = text.replace( /[^A-Z]/g, '' )
      var per  = ( up.length * 100 ) / text.length
      if ( per >= 80 ) {
        this.value = text.toLowerCase()
      }
    } else {
      alert( 'lowerCheck() - parameter error' )
    }
  }
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I also forgot to comment out line 6 which I used to tell me the current percentage value.  :-(
Avatar of alex4544
alex4544

ASKER

How can I apply this to multiple input fields - If i try it on a second input field it errors
error is
lowerCheck() - parameter error
The "onblur" event description identifies the field to be used:

<input type='text' onblur='lowerCheck(this)'>

The "this" keyword is used to identify the current (input) document element
At the moment I have:
<script type='text/javascript'>
function lowerCheck( obj ) {
    if ( obj && obj.nodeName == 'INPUT' ) {
      var text = obj.value
      var up   = text.replace( /[^A-Z]/g, '' )
      var per  = ( up.length * 100 ) / text.length
      alert( 'Please turn of CAPSLOCK!' )
      if ( per >= 20 ) {
        obj.value = text.toLowerCase()
      }
    } else {
      alert( 'lowerCheck() - parameter error' )
    }
  }
  </script>

in the Head and then on each field
onblur='lowerCheck(this)'

but the second field errors

What does the second tag look like?
<textarea name="message"  onblur='lowerCheck(this)'
Ah, that's the problem.  Your initial definition only specified

<input type='text' ...

not

<textarea ...

So, you could change the code slightly...
Change the line that looks like this:

if ( obj && obj.nodeName == 'INPUT' ) {

to be:

if ( obj && ( 'value' in obj ) ) {
Thanks for the grade & points.

Good luck & have a great day