1

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.

1
  • 1
    I don't see id attribute... Commented Jul 24, 2015 at 10:57

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Sometimes you stare at something long enough and your brain just turns to mush. Thanks for this, but having added in the id as above the code is now blanking the value as per the jquery attempt.
Before the jQuery attempt, try putting console.log(thisvariable). What outputs to the console? It could be that thisvariable is in fact blank - try it with a constant, like $(....).val("Test"); and see what happens?
0

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

Comments

0

Try this:

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

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

2 Comments

Try place an id in your input tag: <input type="hidden" name="ThisInput" id="ThisInput" value="N/A" />
Thank You duellsy . Had forgotten the tags <script></script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.