报错:.val() is not a function,请求分析解决(附HTML与JS代码)
Hey there, let's break down why you're hitting that .val() is not a function error and fix it up quickly!
What's Causing the Issue?
In your _certain.each() loop, when you access _certain[index], you're getting a raw native DOM element—not a jQuery-wrapped object. The .val() method is exclusive to jQuery elements, so calling it on a plain DOM node throws this error.
Easy Solutions
Here are a few straightforward fixes, ordered from most efficient to most explicit:
1. Skip the Loop Entirely (Cleanest Approach)
jQuery has a built-in way to grab the value of the checked radio button without manual looping. Use the :checked filter:
var espece = $('#espece'); var poil = $('#poil'); var _certain = $('[name="certain"]'); // Directly get the value of the selected radio button var certain = _certain.filter(':checked').val();
This is the most efficient method—no need to iterate through every radio button yourself.
2. Use $(this) in the Each Loop
Inside the each() callback, this refers to the current DOM element. Wrap it in $() to turn it into a jQuery object, then safely call .val():
var espece = $('#espece'); var poil = $('#poil'); var _certain = $('[name="certain"]'); var certain = null; _certain.each(function() { if ($(this).is(':checked')) { // Check if current element is selected certain = $(this).val(); // Now we can use .val() without errors } });
3. Wrap the Native Element in jQuery
If you prefer to keep using the index-based approach, wrap _certain[index] in $() to convert it to a jQuery object:
var espece = $('#espece'); var poil = $('#poil'); var _certain = $('[name="certain"]'); var certain = null; _certain.each(function(index, element){ if(_certain[index].checked){ certain = $(_certain[index]).val(); // Wrap native element in jQuery } });
All three methods will resolve the error—pick the one that fits your coding style best!
内容的提问来源于stack exchange,提问作者jayensen

