tags:

views:

28

answers:

3

I have a bunch of textboxcontrol on my page all with class 'red'. On click of button, how can i retrieve all these values from textboxcontrol at same time in a variable? I also want to avoid empty controls.

i am trying this

var values=$('input[class="red"]') ??(what to put here)
function()
{
  return $(this).val()
}
);
+1  A: 
var values;
$('input[class="red"]').each(function(){
     values = ( $(this).val() ) ? values + $(this).val() : values;
});
cpharmston
+1  A: 

You can use the Traversing/map function:

var values = $('input.red').map(function () {
  var value = $(this).val() || null; // if value is '', null will be returned
    return $(this).val();
});

The values variable will be an array containing the all values of your inputs, excluding the empty ones.

If you want to get all the values in one string, you can join all the array elements by:

var stringValues = values.join(); // values separated by comma

Also, for matching elements with a determined class, you don't need to use the attributeEquals selector, you can simply use the .class selector as is on my example.

CMS
A: 

You can use the trim function to check for empty values and values containing more than 1 space.

$(document).ready ( function () {
    var strValues = "";
    $("[input[class='test']").each ( function ()
    {      
        if ( jQuery.trim ( $(this).val() ) != "" )
           strValues += $(this).val();
   });
   alert ( strValues );
});


<input class="test" type="text" value="a" />
<input class="test" type="text" value="   " />
<input class="test" type="text" value="b" />
<input class="test" type="text" value="c" />
<input class="test" type="text" value="d" />
<input class="test" type="text" value="e" />
<input class="test" type="text" value="f" />
rahul