简体   繁体   中英

Specific javascript code only working with alert statement

So I have a drop down menu that's supposed to be populated by a Json object value. The code reads like this:

$("#sport").val(model.SportId);

Well, when I load the page, it doesn't work. The drop down list defaults to the default "None Selected" option. So I do a ghetto debug and I put an alert on model.SportId to see what's up.

And when I refresh the page...it works. The only thing that I did was

alert(model.SportId);

It brings up a pop up window that says "1" and then the drop down menu value goes to the option 'Major League Baseball' (which is the text of that option value). That's it. That's the only thing I changed. Putting the alert before that first line of code. If I put the alert after the code, it doesn't work. I have no idea why this is.

The viewmodel that the Json object is derived from has SportId as a nullable int. Could that have anything to do with it?

Edit:

Okay, so in my razor view, this is the javascript I have:

<script type="text/javascript">
$(document).ready(function () {
    var model=@Html.Raw(Json.Encode(Model.Title));
    var read=@Html.Raw(Json.Encode(Model));
    var sportsurl='@Url.Action("GetSports", "Titles")';
    var sportsteamsurl='@Url.Action("GetSportsTeams", "Titles")';

    TitleBasicEdit(model, read, sportsurl, sportsteamsurl);
});

And the javascript function titlebasicedit is:

function TitleBasicEdit(model, url, read, backurl, seasonsurl, autocompleteurl, urlforward, sportsurl, sportsteamsurl) {
if ((model.TitleTypeId == 3) || (model.TitleTypeId == 8)) {
    GetSports(sportsurl);
    SportsDependency(sportsteamsurl);
    alert(model.SportId);
    $("#sport").val(model.SportId);
    $("#sport").change();
    $("#hometeam").val(model.HomeSportTeamId);
    $("#awayteam").val(model.AwaySportTeamId);
}

It could be an issue related to an asynchronous task you perform while populating your options (like an ajax request). That could be the reason why the alert() works: it stops the execution oj javascript so that the task has enough time to be completed (anyway a link may be really appreciated).

edit: the GetSports() function could be that task;

I wonder if it is because model.SportId is a typeof === 'number' ..? Have you tried this? I don't know why it would work though, because jQuery should be smart enough to handle this:

$("#sport").val(model.SportId+'');

Also, try this:

alert($("#sport").length);
$("#sport").val(model.SportId);
alert($("#sport").length);

It could be that your javascript is executing before the HTML loads. The alert() may give it just enough time to load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM