1

I want to send variables from html to javascript file onclick some button. Can I write something like:

onclick="xFunc(document.getElementsByName("x").value,document.getElementsByName("y").value,document.getElementsByName("z").value);"></p>

because the javascript inside html does not works! I try: <script> tag and <script type="text/javascript"> tag and <script language ="javascript"> tag and nothing works.

2 Answers 2

1

You must use single quote character instead of quote character.Also getElementsByName returns an array. Either you can choose one element from array depending of what you want to do or you can use getELementById.

// passing just one element of array
    <p onclick="xFunc(document.getElementsByName('x')[0].value,document.getElementsByName('y')[0].value,document.getElementsByName('z')[0].value);"></p>

// passing the whole array 
    <p onclick="xFunc(document.getElementsByName('x')[0],document.getElementsByName('y')[0],document.getElementsByName('z')[0]);"></p>


// Using getElementById
// in this case you must use Id attribute for your elements
//  <mytag  id="x"></mytag>
<p onclick="xFunc(document.getElementById('x'),document.getElementById('y'),document.getElementById('z'));"></p>
Sign up to request clarification or add additional context in comments.

Comments

0

Try any of the below:

If you want to get value from tag name.

onclick="xFunc(document.getElementsByName('x')[0].value,document.getElementsByName('y')[0].value,document.getElementsByName('z')[0].value)"

If you want to get value from tag id. i prefer this.

onclick="xFunc(document.getElementById('x').value,document.getElementById('y').value,document.getElementById('z').value)"

Note: Id is different from name

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.