Reputation: 741
I have a simple form called myForm
I'm making as an exercise to get better at Javascript and jquery. Inside my form I have a set of radio buttons that act as boolean values to show or hide other content (in this case, 2 div
s that contain a table).
I wanted to tidy up the code a bit using jquery selectors rather than the entire document.get
javascript way. I'm doing this inside an ASP.NET Core 3.1 MVC application if that matters.
The following code correctly grabs the value of my radio buttons
My view
<div class="form-group">
<input type="radio" asp-for="AssignExtension" name="AssignExtension" value='true' onclick="assignExtensionSelect('true')" /> Yes
<input type="radio" asp-for="AssignExtension" name="AssignExtension" value='false' onclick="assignExtensionSelect('false')" /> No
</div>
site.js
<script>
function assignExtensionSelect(extRequired) {
let formInput = document.getElementById("myForm");
//let formInput = $("#myForm");
console.log(formInput.AssignExtension.value);
if (extRequired) {
$('#ifassignextension').show();
$('#ifnotassignextension').hide();
}
else {
$('#ifassignextension').hide();
$('#ifnotassignextension').show();
}
}
</script>
The commented line is the one that won't work correctly. Why does the code return undefined
when I have formInput = $("#myForm");
but works as expected when I assign the variable using the document.getElementById
syntax?
Note: I have jquery already included in the view and other functions already using it, so this is not a dependency issue or jquery not being loaded.
Upvotes: 0
Views: 45
Reputation: 780688
You're trying to use DOM properties with jQuery objects. If you're using jQuery, you have to use its selectors and methods.
let formInput = $("#myForm");
console.log(formInput.find("[name=AssignExtension]:checked").val());
Upvotes: 2