0

I was trying to implement a javascript code in my django admin, I have two fields hard_drives(id is: id_hard_drives) and no_of_drives(id is: id_no_of_drives). So, I want no_of_drives to appear only if hard_drives has particular value, like in the example:

<script type="text/javascript">
    $("#id_hard_drives").change(function () {
        if($("#id_hard_drives").val()=="125"){
            document.getElementById("#id_no_of_drives").type=text
        } else {
            document.getElementById("#id_no_of_drives").type=hidden
        }
    });
</script>

But, I get an error:

Unexpected token < 

Update :

As per GSWV, i have updated the code, but it still used to show same error, so i removed <script> tags. The new code looks something like this :

(function($) {
   $(document).ready(function() {
       var hardDriveSelector = $("#id_hard_drives");
       hardDriveSelector.on("change", function(){
          if (hardDriveSelector.val() == "H") {
              document.getElementById("id_no_of_drives").type = text;
          } else {
          document.getElementById("id_no_of_drives").type = hidden;
          }
       });
     });
})(django.jQuery);

But the code is not being implemented on fly, the script dosen't do anything, do i need to use key up or something on id_hard_drives?

Dhruv Narang
  • 161
  • 1
  • 2
  • 11
  • Get an Editor with syntax hilighting and Linter. see: http://stackoverflow.com/questions/6803305/should-i-use-jslint-or-jshint-javascript-validation $(".#id_hard_drives").change(function(){ if($("#id_hard_drives").val() == 125){ document.getElementById("id_no_of_drives").type = text; } else { document.getElementById("id_no_of_drives").type = hidden; } }); – digitaldonkey Nov 05 '15 at 13:27
  • Welcome to Stack Overflow! I edited your question and remove Thanks and other sentences, because there are not unnecessary. – jezrael Nov 07 '15 at 14:46

2 Answers2

1

I have re-written the code for you. Hope this helps! :)

    $(document).ready(function() {
    $('#id_no_of_drives').hide();
    $("#id_hard_drives").change(function() {
        var driveID = $(this).val();
        if (driveID == '125') {
            $('#id_no_of_drives').show();
        } else {
            $('#id_no_of_drives').hide();
        }
    });
});
Sagar Gulati
  • 144
  • 8
-1

Below is your fixed code

1) $("#id_hard_drives") - no dot before #id_hard_drives

2) document.getElementById('id_no_of_drives') - no # before id_no_of_drives

<script type="text/javascript">
    $("#id_hard_drives").change(function() {
        if ($("#id_hard_drives").val() === '125') {
            document.getElementById('id_no_of_drives').type = text;
        } else {
            document.getElementById('id_no_of_drives').type = hidden;
        }
    });
</script>
Andrei Zhamoida
  • 1,457
  • 1
  • 20
  • 30