Reem
Reem

Reputation: 101

how to pass variable from html to js directly from onclick

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.

Upvotes: 1

Views: 217

Answers (2)

Manjunath
Manjunath

Reputation: 150

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

Upvotes: 0

nAviD
nAviD

Reputation: 3281

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>

Upvotes: 1

Related Questions