javascript/jquery-解析单选框/复选框的所有元素-如何获取每个元素的文本值

javascript/jquery-解析单选框/复选框的所有元素-如何获取每个元素的文本值

问题描述:

我正在尝试通过复选框/单选按钮进行解析.

I am trying to parse through a checkbox/radio button.

作为示例,让我们考虑下面单选按钮的html代码-

As an example let us consider the html code for a radio button below--

<br/><br/>Lunch-
<input type="radio" name="lunch" value="pasta1" /> Pasta
<input type="radio" name="lunch" value="rissotto1" /> Rissotto
<br/>

现在我正在使用以下代码来获取屏幕上显示的文本值(例如"Pasta1")以及分配的值(例如"pasta1")-

Now I am using the following code to obtain both the text value shown on screen (eg "Pasta") as well as the value assigned (eg "pasta1")--

$(jQuery('input[type="radio"], input[type="checkbox"] ', $(element).parent('form'))).each(function() 
{
                    alert(" Text values =" + $(this).text());
                    alert(" actual values =" + $(this).val());
                                    ---SOME MORE CODE---
}

作为输出,虽然$(this).val()可以正常工作,但我使用$(this).text()时却没有任何价值.

As output, I am not getting any value when I use $(this).text(), although $(this).val() works fine.

如何获取单选按钮/复选框的每个元素的文本值...可以代替上面使用的$(this).text()使用的某些内容?还有其他获取文本值的方法(例如,上面的示例为"Pasta"或"Risotto")吗?

How do I get the text values for each element of a radio button/check box... Something that I can use in place of the $(this).text() used above? Is there some other way to obtain the text value (eg "Pasta" or "Risotto" for the example above)?

我认为您无法使用已有的HTML检索文本值.理想情况下,您应该创建标签元素来保存文本.例如

I don't think you can retrieve the text value with the HTML you have. Ideally you should create label elements to hold the text. e.g.

<input type="radio" name="lunch" value="pasta1" /> <label>Pasta</label>
<input type="radio" name="lunch" value="rissotto1" /> <label>Rissotto</label>

然后您可以获取文本:

$(this).next().text();

如果您无法更改HTML,这是一个肮脏的解决方法.

If you can't change the HTML, here is a dirty workaround.

假设在这些单选按钮周围有一个id为wrapper的包装元素(窗体或div),并且每个单选按钮都有唯一的值-

Assuming you have a wrapper element (form or div) of id wrapper around these radio buttons and each radio button has unique value-

/*
 * Create mapping between radio button values and texts
 */ 
var mapping = new Array();
var current_key = '';

$('#wrapper').contents().each(function()
{
   if(current_key)
   {
       mapping[current_key] = $(this).text();
       current_key = '';
   }
   if($(this).attr('type') == 'radio')
   {
       current_key = $(this).val()
   }
});  

然后,您可以轻松使用映射:

Then you can easily use the mapping:

$('input[type=radio]').each(function()
{
    text = mapping[$(this).val()];
})