0

Got a form field that's being checked by a function if value is numeric or not. After the returning the check, I need another function that is meant to pass an attribute value to the field.

Example:

  • FunctionA checks if value is numeric or not
  • FunctionB get a specific digit from FunctionA which is set as the attribute of the form field
  • If form field value is numeric, set the maxlength to 20
  • Else if it's not numeric, set the maxlength to 10

HTML:

<form method="post"  action="">

<input type="text" name="txt" onblur="numChk(this.value);" maxlength="getMax();" />

<p id="fmsg"></p>

<input type="submit" name="sub" />

</form>

Javascript:

<script type="text/javascript">
function numChk (num){
 //var num = num;
    if(!isNaN(num)){
          document.getElementById("fmsg").innerHTML = '<strong>' + num + ' is a number </strong>';
          getMax(maxVal) = 14;
    } else{
          document.getElementById("fmsg").innerHTML = '<em>' + num + ' is not a number </em>';
          getMax(maxVal) = 11;
    }

}

function getMax(maxVal){
    return maxVal;
}
</script>

Hope to get some help with this.

Vinay
  • 6,891
  • 4
  • 32
  • 50
Ous
  • 71
  • 1
  • 8

2 Answers2

0

I would try doing this...

Just call the function in your HTML without a parameter and add an ID:

<input type="text" name="txt" id="txt" onblur="numChk();" maxlength="getMax();" />

Then in your function, get the value of the input field:

function numChk (){
     //var num = num;
     var num = parseInt(document.getElementById("txt").value); //Get input field value

     if(!isNaN(num)){
         document.getElementById("fmsg").innerHTML = '<strong>' + num + ' is a number </strong>';
         getMax(maxVal) = 14;
     }else{
         document.getElementById("fmsg").innerHTML = '<em>' + num + ' is not a number </em>';
         getMax(maxVal) = 11;

     }

}
Tricky12
  • 6,752
  • 1
  • 27
  • 35
0

Demo: http://jsfiddle.net/Q7A32/

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

var inp = document.getElementById('myinput'),
    output = document.getElementById("fmsg");

inp.onkeyup = function() {
    var val = this.value;
    if(isNumber(val)){
        output.innerHTML = '<strong>' + val + ' is a number </strong>';
        this.maxLength = 14;
    }else{
        output.innerHTML = '<em>' + val + ' is not a number </em>';
        this.maxLength = 11;
    }
};

Note: To check if the string is numerical I use https://stackoverflow.com/a/1830844/1529630

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513