erik.c
erik.c

Reputation: 1362

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:

<div id="mDiv>
<input type="text" class = "class1>
<input type="hidden"/>
</div>

and the script is something like that:

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

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

The problem is that this way the $(this) is the Window instead of the element with class1, I am quite new to javascript so it might be something really easy but how should it be handled?

Thanks!

Upvotes: 0

Views: 135

Answers (4)

Thomas
Thomas

Reputation: 212

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

Upvotes: 1

Mritunjay
Mritunjay

Reputation: 25882

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

Upvotes: 1

Satpal
Satpal

Reputation: 133453

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

Upvotes: 2

Volune
Volune

Reputation: 4339

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.

Upvotes: 1

Related Questions