0

I have a loop in my view and during the loop I want to pass the value to a jQuery and return the value back to the div.

View

@foreach (var item in Model){
    <p>@item.Title;</p>
    <div id="timeDisplay" onload="test(@item.DateTime);"></div>
}

jQuery

$(function () {
    function test(var datetime){
        $("#timeDisplay").html(datetime);
    }
});

The load function does work, what am I missing?

1
  • 1
    Your test function isn't accessible outside of $(document).ready(). Commented Mar 21, 2012 at 18:53

4 Answers 4

1

Move test outside of $(document).ready():

$(function () {
    // document ready stuff
});

function test(var datetime){
    $("#timeDisplay").html(datetime);
}

Instead of using the onload attribute, you would probably be better off using $(document).ready(). Also, please note that you have multiple divs with id timeDisplay - use a class instead.

 @foreach (var item in Model) {
    <p>@item.Title</p>
    <div class="timeDisplay" data-date="@item.DateTime"></div>
  }

$(function () {
    // document ready stuff
    $(".timeDisplay").each(function() { 
        $(this).html($(this).data("date")); 
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

I would use the data attributes for something like this:

 @foreach (var item in Model){
    <p>@item.Title;</p>
    <div id="timeDisplay" data-DateTime="@item.DateTime">
    </div>
  }

 $(function () { //anyone know how to do this without the temp?
   var $el = $("#timeDisplay");
   $el.html( $el.data('DateTime') );
});

Comments

1

You need quotes around your server data:

onload="test('@item.DateTime');"

Comments

1

You should not create multiple elements sharing the same ID as you are doing in your example.

Also, your Javascript doesn´t make any since. It would be great to know what you´re aiming for here. This would be enough to display the item property;

@foreach (var item in Model) {
    <p>@item.Title;</p>
    <div class="timeDisplay">@item.DateTime</div>
}

2 Comments

currently I have a js function that shows countdown timer when page loads. it generates targetDate and init() function gets executed.... It works fine e.g. >>targetDate = new Date("December 20, 2012, 13:00:00").getTime() / 1000; >>init(); but what I am trying to do is pass datetime via the loop and it should create its own countdown time, I hope it makes sense. thx
You can use a CSS class and create a jQuery function to generate the countdown for all elements with the class. See @jrummells answer where he´s using the data attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.