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.
Asked
Active
Viewed 37 times
0
-
1It's unclear what you are trying to do..... else your code seems to be fine... – Bhojendra Rauniyar Jul 02 '15 at 03:38
-
so you mean i can use an attribute as a selector? – Jul 02 '15 at 03:40
-
Yes, you can use. You should have tried that. – Bhojendra Rauniyar Jul 02 '15 at 03:42
-
oh! thank you, I never thought that it was possible. – Jul 02 '15 at 03:43
5 Answers
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?
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