Hide a DIV based on the value of a field

Asked

Viewed 114 times

1

Good afternoon, guys! I’m trying to hide a DIV in my code based on the value a field on my site returns. If its value is contained in "Accident", the DivAcidente must be displayed. If any other value is returned, it remains hidden.

I tried to do this with Javascript, but the script only runs when I make some changes to this Dropdown, and by default it is already loaded. I’ll leave the specific part of the code, and my JS.

@* Script para controle dos campos de um RTA tipo Acidente *@
<script type="text/javascript">
    $(document).ready(function () {
        ////Chama o evento após selecionar um valor
        $('#OrigemAnomalia').on('change', function () {
            if (this.value == 'Acidente') {
                $(".DivAcidente").show();
            }
            else {
                $(".DivAcidente").hide();
            }
        });
    });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">

        <div class="DivAcidente" style="display:none;">
            @Html.LabelFor(model => model.HoraOcorrencia, htmlAttributes: new { @class = "control-label col-md-2", style = "font-size: 14px" })
            <div class="col-md-3">
                @Html.EditorFor(model => model.HoraOcorrencia, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                @Html.ValidationMessageFor(model => model.HoraOcorrencia, "", new { @class = "text-danger" })
            </div>
        </div>

        @Html.LabelFor(model => model.OrigemAnomalia, htmlAttributes: new { @class = "control-label col-md-2", style = "font-size: 14px" })
        <div class="col-md-3">
            @Html.DropDownListFor(model => model.OrigemAnomalia, listOrigem, new { @class = "form-control" })
            @*@Html.EditorFor(model => model.OrigemAnomalia, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })*@
            @Html.ValidationMessageFor(model => model.OrigemAnomalia, "", new { @class = "text-danger" })
        </div>

    </div>

4 answers

0

You have to assign the id to that dropdown, like this:

@Html.DropDownListFor(model => model.OrigemAnomalia, listOrigem, new { @id="OrigemAnomalia", @class = "form-control" })
  • It’s still not working. Apparently the ID is already assigned with the model name, since this same script works on another page that the user needs to select the option.

  • What is the default value? It may vary? If it is always the same why not also show by default the respective div and only hide if the dropdown changes?

0

Try calling the event function when pressing.

<script type="text/javascript">
    $(document).ready(function () {

        var toogleDivAcidente = function () {
            if (this.value == 'Acidente') {
                $(".DivAcidente").show();
            }
            else {
                $(".DivAcidente").hide();
            }
        };

        $('#OrigemAnomalia').on('change', toogleDivAcidente);

        toogleDivAcidente();

    });
</script>
  • Still no results. I have to touch the dropdown and select "Accident" again for the Div to appear

0

The ideal in this case is to print style="display:none" before rendering html with the programming language you are using according to the model value and use your js script only for future changes in the client-side field.

But if you want to do it with javascript only, just fire the event change right after the Switch declaration in the field (and you can do this with chaining).

See the example below:

 jQuery(document).ready(function ($) {
    ////Chama o evento após selecionar um valor
    $('#OrigemAnomalia').on('change', function () {
        if (this.value == 'Acidente') {
            $(".DivAcidente").show();
        }
        else {
            $(".DivAcidente").hide();
        }
    }).trigger('change'); // <-- dispara o evento change no campo
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="form-group">
  <div class="DivAcidente" style="display:none;">
	Conteudo da div aqui
  </div>
</div>

<div class="col-md-3">
	<select class="form-control" id="OrigemAnomalia">
		<option value="Acidente" selected="selected">Acidente</option>
		<option value="Valor1">Outra Origem</option>
		<option value="Valor2">Qualquer Valor</option>
	</select>
</div>

Reference

0

You can call the .change() after the .on():

$(function(){
   $('#OrigemAnomalia').on('change', function(){
      $(".DivAcidente")[this.value == 'Acidente' ? 'show':'hide']();
   }).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="DivAcidente">
   DivAcidente
</div>
<select id="OrigemAnomalia">
   <option value="Acidente">Acidente</option>
   <option value="2" selected>opção 2</option>
   <option value="3">opção 3</option>
</select>

The .change() will trigger the event change in the .on() as soon as the DOM is loaded. In the above example I simplified the switching of methods .show() and .hide() using a ternary operator to avoid repeating code.

Browser other questions tagged

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