JQuery:如何获得选中的单选按钮值? [英] JQuery: How to get selected radio button value?

查看:219
本文介绍了JQuery:如何获得选中的单选按钮值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将未选中的单选按钮的值默认为 0

How do I default the value of a non-selected radio button to 0?

我有以下HTML:

<input type="radio" name="myradiobutton" value="1" />1
<input type="radio" name="myradiobutton" value="2" />2
<input type="radio" name="myradiobutton" value="3" />3

我有以下代码来获取所选的值单选按钮

And I have the following code to get the value of the selected radio button

var radio_button_value $('input[name=myradiobutton]:radio').click(function() {var value = $(this).val();});

问题是,我想默认值 radio_button_value nothing ,则$ c>到 0 。我该怎么做?

Problem is, I want to default the value of radio_button_value to 0 in the event nothing is selected. How do I do that?

我基本上想做下面的pseduo代码(但这不起作用)

I basically want to do the pseduo-code below (but this doesn't work)

var radio_button_value $('input[name=myradiobutton]:radio').click(function() { 
if set
  return $(this).val();
else
  return 0;
});

更新

似乎对我的要求感到困惑。

There appears to be confusion on what I'm asking for.

页面加载时我想做什么(在用户有机会选择之前)一个单选按钮),我想要一个函数,它将为单选按钮值返回0。

What I want to do when the page loads (before a user has had a chance to even select a radio button), I want a function that will return 0 for the radio button value.

然后,一旦用户选择了一个单选按钮,该SAME函数将返回选择单选按钮的值。

Then, once a user selected a radio button, that SAME function will return the selected value of the radio button.

有意义吗?

推荐答案

$('input [name = myradiobutton]:radio:checked')将为您提供所选的单选按钮
$('input [ name = myradiobutton]:radio:not(:checked)')将为您提供未选中的单选按钮

$('input[name=myradiobutton]:radio:checked') will get you the selected radio button $('input[name=myradiobutton]:radio:not(:checked)') will get you the unselected radio buttons

使用此功能可以执行此操作

Using this you can do this

$('input[name=myradiobutton]:radio:not(:checked)').val("0");

更新:阅读完更新后我想我理解
你会想做这样的事情

Update: After reading your Update I think I understand You will want to do something like this

var myRadioValue;

function radioValue(jqRadioButton){
  if (jqRadioButton.length) {
    myRadioValue = jqRadioButton.val();
  }
  else {
    myRadioValue = 0;
  }
}

$(document).ready(function () {
  $('input[name=myradiobutton]:radio').click(function () {   //Hook the click event for selected elements
    radioValue($('input[name=myradiobutton]:radio:checked'));
  });

  radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});

这篇关于JQuery:如何获得选中的单选按钮值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆