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
when I check the console, my variable is set appropriately and shows as intended, but when I go like this after setting it
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?
I am trying to validate some fields server side before actual submission I was doing this to set the variable
myVar=$('#myVarFormID').val();
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);
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?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I suspected I couldnt mix jQuery with javascript so when I set the variable withThis does not make sense - jQuery is JavaScript - anything you set with one is available in the other.
document.getElementById('myVarFormID ').value instead of the previous jquery code it worked
To access the underlying Dom element from a jQuery object all you need to do is provide an index
var element = $('#someid');
Then element[0] is the same as document.getElementById('sASKER
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('m yVarFormID ').value will solve the issue.
https://jsbin.com/poqiteh/edit?html,js,console
Outputs:
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>
function test(myval) {
console.log(myval);
}
$(function() {
var myval = $('#myVarFormID').val();
test(myval);
})
Outputs:
somevalue
what is this by the way? #myVarFormID