Chris Harland
Chris Harland

Reputation: 476

Variable passed to Javascript returns NULL when added to Input Value

So, basically I am trying to pass a variable to a piece of javascript code and then in turn set this value as a hidden input value.

<img alt="" src="Image.jpg" style="width:50px" class="thisclass" title="Title" onclick="thisfunction('Text Here')" />

The value clearly passes okay as I am able to process it with a switch command successfully.

function thisfunction(thisvariable) {
    switch(thisvariable) {
        case 'Text Here' :

However, when I try to set the value of a hidden

<input type="hidden" name="ThisInput" value="N/A" />

document.getElementById("ThisInput").value = thisvariable;

I get the following error in the javascript console

Uncaught TypeError: Cannot set property 'value' of null

I have also tried

$('#ThisInput').val(thisvariable);

However this just seems to blank the value.

Upvotes: 1

Views: 69

Answers (3)

Danilo P&#225;dua
Danilo P&#225;dua

Reputation: 398

Try this:

<input type="hidden" name="ThisInput" id="ThisInput" value="N/A" />

<script>
  $('#ThisInput').attr('value',thisvariable);
</script>

Upvotes: 0

messerbill
messerbill

Reputation: 5629

you try to select the HTML element via ID.

<input type="hidden" id="ThisInput" name="ThisInput" value="N/A" />

use this and it should work

Upvotes: 0

Ben
Ben

Reputation: 9001

Looking at this part of your code:

<input type="hidden" name="ThisInput" value="N/A" />
document.getElementById("ThisInput").value = thisvariable;

document.getElementByID and $("#...") will find the ID of an element. "ThisInput" is the name - it has no ID set.

This would work:

<input type="hidden" id="ThisInput" value="N/A" />
document.getElementById("ThisInput").value = thisvariable;

Or if you want to keep it as a name attribute, use a jQuery attribute selector:

$("input[name='ThisInput']").val(thisvariable);

Upvotes: 3

Related Questions