问题
How can i get the ID of an input box that contains a certain class value
ex:
<input id="first" class="failed" />
<input id="last" class="failed" />
<input id="city" class="failed" />
<input id="state" class="failed" />
I want to alert all the ID that contains the class failed after pushing a button or a command.
回答1:
I want to alert all the ID that contains the class failed after pushing a button or a command.
Use class selector to get elements with particular class. You can use each() to traverse all the element. Bind the click event to button, you can use button id in id selector to bind the event.
Live Demo
Html
<input id="first" class="failed" />
<input id="last" class="failed" />
<input id="city" class="failed" />
<input id="state" class="failed" />
<input type="button" id="btn" value="click" />
Javascript
$('#btn').click(function () {
$('.failed').each(function () {
alert(this.id);
});
});
回答2:
You can use .map() to get an array of ids
var ids = $('.failed').map(function(){
return this.id
}).get();
console.log(ids);
alert(ids)
回答3:
use each jquery
$('.failed').each(function(e){
var id=$(this).attr('id');//find each id
});
回答4:
$.each($('.failed'), function () {alert ($(this).attr('id')); });
回答5:
var ids = []; //create an array
$('.failed').each(function(e)){ //iterate each class
ids.push($(this).prop('id')); //push their id to array
});
alert(ids);
回答6:
You could iterate through the inputs and do what ever you want with elements that have the defined class:
$("input.failed").each(function() {
console.log($(this).attr('id'));
});
回答7:
You can alert all ids
on button click
like this:
$("#btnid").click(function(){ //click on button
$('.failed').each( function () {
alert ($(this).attr('id')); //alert id one by one
});
});
来源:https://stackoverflow.com/questions/20626799/get-all-id-of-input-box-that-contains-a-class