user2818060
user2818060

Reputation: 845

Cannot read property 'value' of null while accessing js variable in javascript

what i Need

html code

    <script>
     var p = "{{ page_param.asy_request | replace('&','&')}}";
     p = p.replace(/\&/g, "&");
     p = "{{ DomainDetect() }}/ajax?for=event_listing&ajax=1" + p;

   </script>

 <input type="hidden" name="mobilepage" id="mobilepage" value="'+p+'"/>

Accesing p variable in javascript code

   var mobile=document.getElementById("mobilepage").value;
   console.log(mobile);

Error

Uncaught TypeError: Cannot read property 'value' of null

Upvotes: 1

Views: 1271

Answers (3)

Christos
Christos

Reputation: 53958

Your html element hasn't id. Hence you can't select using the document.getElementById. If you want to fix this, you have to add this id, like below:

<input type="hidden" name="mobilepage" id="mobilepage" value=""/>

If you don't want to add an id and you want to leave this element as is, the you should use another method for selecting your element, document.getElementByName.

Below I have added a code snippet to see that it works.

alert(document.getElementById("mobilepage").value);
<input type="hidden" name="mobilepage" id="mobilepage" value="3"/>

Upvotes: 1

Ankit K
Ankit K

Reputation: 1326

Add id attribute to your input.

Upvotes: 0

Omri Aharon
Omri Aharon

Reputation: 17064

You're trying to get an element by ID, when you should be getting that element by name. Do:

 var mobile=document.getElementByName("mobilepage").value;

Either that, or change the name to be an ID on the HTML element:

<input type="hidden" id="mobilepage" value=""/>

Upvotes: 0

Related Questions