user2991761
user2991761

Reputation:

Accessing child elements with respect to checkbox

I have a list of User Details which option to select, as shown here - Fiddle, now I want to Get the selected Users and fetch corresponding Text-box values .

For getting selected users I have a simple jQuery:-

var selected = new Array();
$('.dummy-class ').click(function (e) {
    if (this.checked) {
        selected.push(this);
    } else {
        var index = selected.indexOf(this);
        selected.splice(index, 1);
    }
    console.log(selected);
});

Now, I got confused how do I select the elements lying inside.

//Access values of selected elements while saving and creating OBJECT
$('.SaveDetails').click(function () {
    console.log(selected);
    var tempArray = [];
    $.each(selected, function (index, value) {
        console.log($(this).find("input:first").attr("value"));//Its not working

        var temp = {};
        temp.FirstName = $(this).find("input:first").attr("value");"));//Its not working
        tempArray.push(temp);
    });
    console.log(tempArray);
});

Upvotes: 1

Views: 44

Answers (2)

prabeen giri
prabeen giri

Reputation: 803

If you trying to use inside $('.SaveDetails').click(function () handler then try this:

$('.SaveDetails').click(function () {
    console.log(selected);
    var tempArray = [];
    $.each(selected, function (index, value) {
        console.log($(this).closest('.panel').closest('.panel').find("input:first").val());//Its not working

        var temp = {};
        temp.FirstName = $(this).closest('.panel').find("input:first").val();"));//Its not working
        tempArray.push(temp);
    });
    console.log(tempArray);
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388326

You can find the .panel element in which the checkbox is present and then the input element with name first inside it.

var selected = new Array();
$('.dummy-class ').change(function (e) {
    if (this.checked) {
        selected.push(this);
    } else {
        var index = selected.indexOf(this);
        selected.splice(index, 1);
    }
    console.log(selected);
    var $panel = $(this).closest('.panel');
    console.log($panel.find('input[name="first"]').val())
});

You will have to make sure all the name fields have the name first

Demo: Fiddle

Upvotes: 1

Related Questions