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.

有帮助吗?

解决方案

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);
    });
});

其他提示

You can use .map() to get an array of ids

var ids = $('.failed').map(function(){
    return this.id
}).get();

console.log(ids);
alert(ids)

use each jquery

$('.failed').each(function(e){
        var id=$(this).attr('id');//find each id 
});
$.each($('.failed'), function () {alert ($(this).attr('id')); });
var ids = []; //create an array
$('.failed').each(function(e)){   //iterate each class
    ids.push($(this).prop('id')); //push their id to array
});
alert(ids); 

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'));
});

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
  });
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top