互联网技术 · 2024年2月12日

Jquery操作radio、checkbox、select的选中和获取选中值

在我们编写程序的时候,经常会对元素选中,或是获取选中的值,

在这篇文章中,我们介绍使用 Jquery 操作radio、checkbox、select选中及获取选中值,

获取选中的值时,我们使用 val() 来获取,

元素的选中 我们使用 attr 或 poro 来进行属性操作,

下面就是具体使用示例:

一、Radio 单选框

1、获取选中的值

$(“input[name=name名称]:checked”).val();

2、操作选中使用(attr 或 poro)

$(“input[name=sex]”).attr(“checked”, true); // 选中

$(“input[name=sex]”).attr(“checked”, false); // 取消选中

3、判断是否选中

// 选中为true,没选中为false

$(“input[type=radio]:eq(1)”).prop(“checked”);

$(“input[type=radio]:eq(1)”).is(“:checked”);

二、Checkbox 复选框

1、获取选中的值

$(“input[type=checkbox]:checked”).each(function(){

console.log($(this).val());

})

2、操作选中使用(attr 或 poro)

$(“input[type=checkbox]:eq(1)”).attr(“checked”, true); // 选中

$(“input[type=checkbox]:eq(1)”).attr(“checked”, false); // 取消选中

3、判断是否选中

// 选中为true,没选中为false

$(“input[type=checkbox]:eq(1)”).prop(“checked”);

$(“input[type=checkbox]:eq(1)”).is(“:checked”);

三、Select 下拉框

1、获取选中的值

$(“select option:selected”).text()

$(“select”).find(option:selected).text()

$(“select”).val();

2、操作选中使用(attr 或 poro)

$(“select option:eq(1)”).attr(“selected”, true); // 选中

$(“select option:eq(1)”).attr(“selected”, false); // 取消选中

3、判断是否选中

// 选中为true,没选中为false

$(“select option:eq(1)”).is(“:selected”);

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册