Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Unable to get property 'value' of undefined or null reference

Tags:

javascript

I have below code and java script is throwing error "Unable to get property 'value' of undefined or null reference". What am I doing wrong ? below is the sample code I am trying to execute to validate one input field.

<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <meta content="text/html;charset=iso-8859-2" http-equiv="content-type" />

<script type="text/javascript">
 function validate_frm_new_user_request()
{
    alert('test');
    valid = true;

    if ( document.frm_new_user_request.u_isid.value == '' )
    {
        alert ( "Please enter your valid ISID Information." );
        document.frm_new_user_request.u_isid.focus();
        valid = false;
    }
return valid;   
</script>
</head>
<body
<form method="post" action="" name='frm_new_user_request' id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">
<center>
<table>
    <tbody>

        <tr align="left">
            <td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>
            <td>

<tr>
            <td align="center" colspan="4">
                <input type="image" src="images/button/btn_create_request.gif" border="0" ALT="Create New Request">

                </td>
        </tr>
    </table>
</form>
</body>
</html>
like image 437
Lord OfTheRing Avatar asked Sep 24 '15 18:09

Lord OfTheRing


2 Answers

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;
like image 77
Shockwave Avatar answered Jan 05 '23 01:01

Shockwave


You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value
like image 21
David Ferenczy Rogožan Avatar answered Jan 05 '23 02:01

David Ferenczy Rogožan