0

In my file I have javaScript variable name 'testJava'

<script>
var testJava = 'script Test';
</script>

At the bottom of the page I have a checkbox. I need to add 'testJava' variable to the value of the checkbox.

<input type="checkbox" name="website[]" value= "I_WANT_TO_ADD_IT_HERE" />My Test<br />

value = "<script>document.write(testJava);</script>" doesn't work

Can anyone please tell me how to do this?

5 Answers 5

1
<script>
var testJava = 'script Test';
document.getElementById('checkbox_ID').value = testJava;
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

You should add an id tag to your <input> element to identify it:

<input type="checkbox" name="website[]" id="thecheckbox" />

Using jQuery, it's quite easy to change the value:

$('#thecheckbox').val(testJava);

To include jQuery, e.g. use the following script tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

1 Comment

I wanted to post an alternative solution. Now I've included instructions to include jQuery in my answer.
0

Try this:

var checkBox = document.getElementsByTagName("input")[0];
checkBox.value = testJava;

Note: this must be done within a window.onload event or in a script positioned after the checkbox HTML.

Comments

0

You can't directly do what you're asking, so just set the value after the fact:

<input type=checkbox id=cb1 ...> My Test
<script>
  document.getElementById('cb1').value = testJava;
</script>

Also, Java and JavaScript are not the same thing.

Make sure the <script> is after the <input>, or else that it's in a "load" or "ready" event handler.

Comments

0
<input type="checkbox" name="website[]" id="check_box" value= "I_WANT_TO_ADD_IT_HERE" />My Test<br />

in your script, after the dom ready,

document.getElementById("check_box").value("testJava");

Comments

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.