Home > Software design >  How to disable a input field according to another select field value in bootstrap/crispy?
How to disable a input field according to another select field value in bootstrap/crispy?

Time:10-01

I'm trying to deactivate existing_name fields based on values that selected on action field I'm using crispy and rendering option for action field from models.py

action = models.CharField(max_length=30,
                              choices=[('add', 'Add'), ('delete', 'Delete'), ('modify', 'Modify'),
                                       ('rename', 'Rename')])

I had check all same question on Stackoverfllow and all suggested to deactivate it by script with changes happen action fields

{% extends "KPI_App/base.html" %}
{% load crispy_forms_tags %}

{% block content %}
<form action="" method="post" autocomplete="off" >
    {% csrf_token %}
        <div class="row">
            <div class="col-md-4 id='1'">{{form.action|as_crispy_field}}</div>
        </div>
        <div class="row">
            <div class="row id='existing_name' " >{{form.existing_name|as_crispy_field}}</div>


    <div class="row">
        <div class="col-md-8">
            <button type="submit" class="btn btn-success btn-block btn-lg"><i class="fas fa-database"></i> Submit</button>
        </div>
        <div class="col-md-4">
            <a href="{% url 'KPI_list' %}" class="btn btn-secondary btn-block btn-lg">
                <i class="fas fa-stream"></i> Back to List
            </a>
        </div>
    </div>
</form>
{% endblock content %}
<script>
    $(document).ready(function(){
  $("select[name='action']").on('change',function(){
    if($(this).val()=='1'){
      $("input[name='existing_name']").prop("disabled",false);
    }else{
      $("input[name='existing_name']").prop("disabled",true);
    }
  });
});
</script>

I can't assign id for these class and use it it script

CodePudding user response:

Assuming your form input ids are the django default: id_action and id_existing_name.

function toggleAction() {
    if ($('#id_action :selected').text() == "Modify") {
        $('#id_existing_name').prop('disabled',false)
    }
    else {
        $('#id_existing_name').prop('disabled',true)
    }
}

$(document).on('click change', '#id_action', function() {
    toggleAction()
})

$(document).ready(function() {
    toggleAction();
});
  • Related