Javascript and Asp.net mvc help

Asked

Viewed 782 times

3

In my project I have a field that is the Status of a certain occurrence. That is, if it is pending or solved. I made a javascript function that , by clicking the input field that is in readonly mode, changes the background. I mean, if the value from inside the input is Solved, the input turns green, and if the input value is Pending turns red.

What happens is that it works well, but I have a problem: this function is only done in the first occurrence of the input. I have an index, and it has a foreach to iterate over all the database data related to occurrences, IE, I have several inputs on the status.

What happens is that the function is only executed in the first occurrence of the list, the rest does not happen anything.

Another thing is, I wanted that when saving or editing the occurrence, when returning to index to show, the function was already applied, without the user needing to click or hover over. It was automatic, I mean, if the input value is Pendant, it turns red, if the value is Solved turns green.

I wonder if someone could help me ?

View(where all the code is)

@*@model IEnumerable<CEF01.Models.Ocorrencia>*@
    @model PagedList.IPagedList<CEF01.Models.Ocorrencia>
        @using PagedList.Mvc;
       <link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
   <style>
       #Status {
           text-align: center;
             }

        .resolvido {
    background-color: green;
    font-family: 'Times New Roman';
    color: white;
           }

         .pendente {
    background-color: red;
    font-family: 'Times New Roman';
    color: white;
        }
       </style>

        @{
          ViewBag.Title = "Index";
     }


       @Html.ActionLink("Criar uma nova ocorrência", "Adiciona", null, new { @class = "btn btn-primary" })
              @Html.ActionLink("Lista de Alunos", "Index", "Alunos", null, new { @class = "btn btn-primary" })

             <span class="pull-right">
            @using (Html.BeginForm("Index", "Ocorrencias", FormMethod.Get))
            {
    <p>
        Busca Aluno: @Html.TextBox("busca")
        <input type="submit" value="Procurar" class="btn btn-info" />
    </p>
           }

           </span>

            <table class="table">
             <tr>
    <th>
        @*@Html.DisplayNameFor(model => model.Aluno.Nome)*@
        Nome do Aluno
    </th>
    <th>
        @*@Html.DisplayNameFor(model => model.Tipo)*@
        Tipo
    </th>
    <th>
        @*@Html.DisplayNameFor(model => model.Causa)*@
        Causa
    </th>
    <th>
        @*@Html.DisplayNameFor(model => model.Descricao)*@
        Descrição
    </th>
    <th>
        Status
    </th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Aluno.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Tipo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Causa)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Descricao)
        </td>
        <td>
            @*@Html.DisplayFor(modelItem => item.Status)*@
            <input type="text" name="Status" id="Status" value="@Html.DisplayFor(modelItem => item.Status)" readonly onmousemove="trocaCor()" />
        </td>
        <td>
            @Html.ActionLink("Editar", "Edita", new { id = item.Id }) |
            @* @Html.ActionLink("Details", "Details", new { id=item.Id }) | *@
            @Html.ActionLink("Remover", "Remove", new { id = item.Id })
        </td>
    </tr>
        }

        </table>
          <br />
              Pagina @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) de @Model.PageCount
        @Html.PagedListPager(Model, pagina => Url.Action("Index", new { pagina, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

       @section Scripts {
@Scripts.Render("~/bundles/jqueryval")

<script>
    function trocaCor() {
        var troca = document.getElementById("Status");
        if (troca.value == "Pendente") {
            $("#Status").addClass("pendente");
        }
        if (troca.value == "Resolvido") {
            $("#Status").addClass("resolvido")
        }
    }
</script>
      }
  • 1

    It would be nice to have a more descriptive title of the real problem. And separate paragraphs. It makes it easier for people to read, understand what you want and help.

  • Please use http://www.jsfiddle.net to enter your code.

  • @Bigown Improved ? The title is because I think so looks better. I do not know a title that I was well suited with the problem, in case you want to edit my question, you can feel free. I just wanted some help to resolve this impasse. I think it’s a simple thing.

2 answers

4


If you want javascript to interact with all objects use classes. By Id only one will be affected.

Add the Status class

<input type="text" name="Status" id="Status" class="Status" value="@Html.DisplayFor(modelItem => item.Status)" readonly onmousemove="trocaCor()" />

Script to load to index to show already the correct color:

<script>
$(document).ready(function() {
    $('.Status').each(function(){
        if ($(this).val() == "Pendente") {
            $(this).addClass("pendente");
        }
        if ($(this).val() == "Resolvido") {
            $(this).addClass("resolvido")
        }
    });
});
</script>

There’s an option you don’t even need Javascript for. It’s css only and you don’t need the tbm class. It’s enough: http://jsfiddle.net/JH2tG/

<style>
    input[value=resolvido] { background-color: green }
    input[value=pendente] { background-color: red }
</style>
  • Poxa didn’t work that way. He didn’t even change color.

  • Press F12 in the browser and see in the console what was the JS error that helps you.

  • It even loads the code, but does not apply the function. But not any error.

  • You can make all the direct call from JS also without calling in input. I noticed that you are using onmousemove to call the function, have other better ways to do.

  • It is. I don’t want the user to have to click or move the mouse. I want that when loading the page, according to the input value, the function is already applied. And how would you do it ? This class you mentioned as I would make it ? Because I put it here and it didn’t work. I even have the style I want on the page, ta lá lá !

  • This way you can replace your code with my second JS example. When loading the page (Document.ready) it scans all objects (each) one by one with the Status class checks the values and adds the class.

  • This class he would add would be the one in the right javascript code ?

  • The Voce class adds direct input. <input type="text" name="Status" id="Status" class="Status"... jquery uses it to find the object. You were previously doing with the ID, but ID jquery subunderstands that it is unique and only handles the first record.

  • I got this error here with your code: 'Uncaught Referenceerror: trocaCor is not defined Occurrences:121 onclick'

  • If successful remove from the input also this onmousemove.

  • If you want to apply this only when loading the page you have to leave only that second js q posted. You must also remove onmousemove="trocaCor()"

  • Brother, it worked right ! That’s how you put it !

  • 1

    Blz. Any doubt only to post there.

  • Too quiet !

Show 9 more comments

4

If you want to color the input Depending on the status when loading the page, you can make a jquery selector for this. In his input, you are using id="Status", This is invalid, we cannot have multiple elements with the same id, change the id="Status" for class="status", see in the example:

HTML of the view:

<input type="text" name="status" class="status" value="Pendente" readonly />
<input type="text" name="status" class="status" value="Resolvido" readonly />

Jquery

$(document).ready(function(){
    $("input[value='Resolvido'].status").addClass('resolvido');
    $("input[value='Pendente'].status").addClass('pendente');
});

Example: Jsfiddle

  • Very top also your expensive solution ! It was well worth !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.