You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错:.val() is not a function,请求分析解决(附HTML与JS代码)

Fixing the ".val() is not a function" Error in Your Radio Button Code

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:53:19