Haseem hac
Haseem hac

Reputation: 31

Uncaught TypeError: Cannot read property 'value' of null

This my PHP code:

echo '<td>';
$r= $item['Rate'];
echo '<input  id="ratetb" onkeyup="clean(ratetb)" onkeydown="clean(ratetb)" name="ratetb" autocomplete="off" style="text-align:center" type="text" value="'.$r.'" >';          
echo '</td>';

and this is my JavaScript function:

function clean(e) {
    var textfield=document.getElementById(e);

    var replc=/[^0-9 .]/gi;

    textfield.value=textfield.value.replace(replc,"");
  }

when executes this i got error

Uncaught TypeError: Cannot read property 'value' of null

Upvotes: 0

Views: 1714

Answers (2)

Nick
Nick

Reputation: 43

Please check call function and be sure there is an item with id e because error says that textfield is null so cant be value of null object.

Edit: After change your question it must be onkeyup="clean('ratetb')"

Upvotes: 2

epascarello
epascarello

Reputation: 207521

you are not passing in a string

echo '<input  id="ratetb" onkeyup="clean(ratetb)" onkeydown="clean(ratetb)" 

should be

echo '<input  id="ratetb" onkeyup="clean(\'ratetb\')" onkeydown="clean(\'ratetb\')" 

better yet, pass in the object reference

echo '<input  id="ratetb" onkeyup="clean(this)" onkeydown="clean(this)" 

and change the function

function clean(textfield) {
    var replc=/[^0-9 .]/gi;
    textfield.value=textfield.value.replace(replc,"");
}

Or even better, do not use inline events.

Upvotes: 1

Related Questions