Link to home
Start Free TrialLog in
Avatar of weekapaug
weekapaug

asked on

Using Jquery Input Element in Javascript Function

I have a form that posts via javascript / jquery / ajax

I am trying to validate some fields server side before actual submission I was doing this to set the variable

myVar=$('#myVarFormID').val();

Open in new window


when I check the console, my variable is set appropriately and shows as intended, but when I go like this after setting it
nextFunction(myVar);

Open in new window


The function thinks the variable is [htmlInputElement]

I dont understand why the output shows fine but the script function wont take it in.  Is there something extra I need to do to pass this form element into a different function?
Avatar of HainKurt
HainKurt
Flag of Canada image

need full code, or jsfiddle.net demo (or html from browser)

what is this by the way? #myVarFormID
ASKER CERTIFIED SOLUTION
Avatar of weekapaug
weekapaug

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Julian Hansen
I suspected I couldnt mix jQuery with javascript so when I set the variable with

document.getElementById('myVarFormID').value instead of the previous jquery code it worked
This does not make sense - jQuery is JavaScript - anything you set with one is available in the other.

To access the underlying Dom element from a jQuery object all you need to do is provide an index
var element = $('#someid');

Open in new window

Then element[0] is the same as document.getElementById('someid')
Avatar of weekapaug
weekapaug

ASKER

figured it out
Further to Julian's comment, it should be noted that there is an error in the asker's code (that's not posted) as the code in the question does work when taken on its own.  In other words, it is wrong to assume that document.getElementById('myVarFormID').value will solve the issue.

https://jsbin.com/poqiteh/edit?html,js,console

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>

  </head>
  <body>
    <form action="">
      <input type="hidden" value="somevalue" id="myVarFormID"/>
    </form>
  </body>
</html>

Open in new window


function test(myval) {
  console.log(myval);
}

$(function() {
  var myval = $('#myVarFormID').val();
  test(myval);
})

Open in new window


Outputs:
somevalue

Open in new window