Home > Enterprise >  Change innerHtml of div according to value of model item in view .NET6 EF6 Razor Pages No MVC
Change innerHtml of div according to value of model item in view .NET6 EF6 Razor Pages No MVC

Time:06-30

Change innerHtml of div according to value of model item in view .NET6 EF6 Razor Pages No MVC

I am trying to have a due date optional in a todo list. Since date fields are not nullable/required, I set the default due date to 09/09/9999. That date represents a todo that does not have a due date. What I want is to have the innerHtml of that due date display "None" if the due date is 09/09/9999.

My code however shows "None" in the due date div in the table of only the first row, regardless of the date.

enter image description here

Here is the javascript code

function hideDueDate () {
const dueDateDiv = document.querySelector('#due-date');

if (dueDateDiv.innerHTML = "09/09/9999") {
    dueDateDiv.innerHTML = "None";
    }   
}

hideDueDate();

And here is the view.

    <tbody>
         @*READ*@
            @foreach(var obj in Model.ToDo)
            {
             <tr>
                <td width="10%">@Convert.ToString(string.Format("{0:MM/dd/yyyy}", obj.CreateDate))</td>
                <td width="20%">@obj.Name</td>
                <td width="40%">@obj.Description</td>
                <td width="10%">
                    <div id="due-date">@Convert.ToString(string.Format("{0:MM/dd/yyyy}", obj.DueDate))</div>
                </td>
                <td width="20%" >
                    <div >
                    <input asp-for="@obj.Complete"  type="checkbox" readonly="readonly" />
                    </div>
                </td>
                <td>
                    <div  role="group">
                    <a asp-page="View" asp-route-id="@obj.Id" >
                        <i >&nbsp;View</i>
                    </a>
                    <a asp-page="Edit" asp-route-id="@obj.Id" >
                        <i >&nbsp;Edit</i>
                    </a>
                    <a asp-page="Delete"  asp-route-id="@obj.Id" >
                        <i >&nbsp;Delete</i>
                    </a>
                    </div>
                </td>
             </tr>
            }
    </tbody>

CodePudding user response:

1.document.querySelector('#due-date') can only get the first matched element. You need use .each().

2.The condition should be dueDateDiv.innerHTML == "09/09/9999".

Change your code like below:

function hideDueDate () {
    $('div #due-date').each(function() {
        if(this.innerHTML=="09/09/9999"){
            this.innerHTML= "None";
        }
    });
}
  • Related