Skip to content Skip to sidebar Skip to footer

Javascript/jquery- Parsing Through All Elements Of A Radio/check Box- How To Get Text Value Of Each Element

I am trying to parse through a checkbox/radio button. As an example let us consider the html code for a radio button below-- Lunch-

Solution 1:

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.

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

Then you can get the text:

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

EDIT:

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

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 = newArray();
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()];
}) 

Solution 2:

.text() is not applicable for those elements who don't have close tag. e.g. <INPUT> <IMG> If you read the documentation of .text() it is clearly written that The .text() method cannot be used on form inputs or scripts.

I'm not sure what you exactly wanted to be shown but giving value attribute will show a text next to Radio Button. Thats how it works. I'm not sure why you want another extra text after that. But if thats the case then solution suggested by @Vikk is right.

Post a Comment for "Javascript/jquery- Parsing Through All Elements Of A Radio/check Box- How To Get Text Value Of Each Element"