Skip to content Skip to sidebar Skip to footer

Get Value Of Sibling In Same Div

I would like to do a certain kind of logic for every item with a given class (the code is reused that why i dont work with id): the items are within the same div everywhere:

Solution 1:

You are very close, You just need to pass the function reference like

$(".class1").val(calcDefaultDate); //Notice removed ()

When you use () one is calling function.

DEMO


Solution 2:

You can try to give the element as an argument instead of trying to reach it with the this keyword:

$(".class1").val(calcDefaultDate($(".class1")))

function calcDefaultDate($element){
    var currDate = element.siblings('input[type=hidden]').val();
    if (currDate == "") {
        return new Date();
    }
    return currDate;
}

By the way, maybe you would prefer return new Date(+currDate); instead of return currDate;, this way the type of what your function returns is more consistent.


Solution 3:

There need to be some change in implementation.

Do it like bellow

$(".class1").each(function(){
    var currDate = $(this).siblings('input[type=hidden]').val();
    if (currDate == "") {
        $(this).val(new Date());
    }
 else
    $(this).val(currDate);
});

DEMO


Solution 4:

Try passing the div as an argument to your function:

$(".class1").each(function() {
    $(this).val(calcDefaultDate($(this)));
});

function calcDefaultDate(el) {
    var currDate = $(el).siblings('input[type=hidden]').val();
    if (currDate == "") {
        return new Date();
    }
    return currDate;
}

Or apply the function to each element:

$(".class1").each(function() {
    updateDefaultDate($(this));
});

function updateDefaultDate(el) {
    var currDate = $(el).siblings('input[type=hidden]').val();
    if (currDate == "") {
        currDate = new Date();
    }
    el.val(currDate);
}

Or pass all the elements to your function:

updateDefaultDate($(".class1"));

function updateDefaultDate(elements) {
    $(elements).each(function() {
        var currDate = $(this).siblings('input[type=hidden]').val();
        if (currDate == "") {
            currDate = new Date();
        }
        $(this).val(currDate);
    });
}

Post a Comment for "Get Value Of Sibling In Same Div"