0

Example I have 10 textbox and each has the same attribute with different value, say for example they have an attribute data-same with different value and I have something like this in my code
$('#test').each(function(){ $(this).val(); });
and I want to filter the result using the attribute of each textbox. How would I do it? I was thinking on doing something like this
$('#test').each(function(){ $('[data-same="val1"]',this).val(); });
but I'm not sure about it.

5 Answers5

1

Use attr()

$('#test').each(function(){
     var attributeValue = $(this).attr('data-same');
     //do whatever you want with the value
});

Also, your code indicates you have the same ID for multiple elements. Avoid that and use classes or attributes instead.

$('[data-same]').each(function(){
         var attributeValue = $(this).attr('data-same');
         //do whatever you want with the value
    });

See Why is it a bad thing to have multiple HTML elements with the same id attribute?

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0
$('#test').each(function(){
    $(this).val($(this).attr("data-same") );
});
Ram G Athreya
  • 4,892
  • 6
  • 25
  • 57
Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32
0

Ok If my assumption is correct you want to get all the textbox with same attribute then below code will work and I would suggest keep an unique id: to each elements and you can try with classname instead say class="test":

var sameTextBox=[];
$('.test').each(function(){ //change this selector to class
     if($(this).attr('data-same')=="somevalue") //otherwise you can try 
     //if($(this).data('same')=="somevalue")
     {
          sameTextBox.push($(this));
     }
});
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

Try with map method to get all the textbox values.

$(function(){
   var textBoxValues = $('input[data-same]').map(function(){
   return this.value
   }).get()
})

Hope this helps you...

John R
  • 2,741
  • 2
  • 13
  • 32
0

you can use jQuery filter method.

$(".test").filter(function(){ 
  if(parseInt($(this).attr('data-same')) == "somevalue")
   return $(this);
});

Note: Use class name for group of elements, and id for a single element.

sudhansu63
  • 6,025
  • 4
  • 39
  • 52