Home > Software design >  Uncaught TypeError: Cannot read properties of undefined (reading 'preventDefault')
Uncaught TypeError: Cannot read properties of undefined (reading 'preventDefault')

Time:12-14

I trigger onchange attribute in input depending on a specific process. However, even if I "Event" as a parameter, I continue to get the error below. Also, alternatively, I tried Event.StopPropagation () and Return False but the problem is ongoing.

$(function () {
        test();
});

function test(obj) {

        var inputValue = parseInt($(obj).val());

        if (($(obj).val() < 0 || $(obj).val() > 100) && event.keyCode !== 46 // keycode for delete
            && event.keyCode !== 8 // keycode for backspace
        ) {
            event.preventDefault();
            $(obj).val(0);
        } else if (isNaN(inputValue)) {
            event.preventDefault();
            $(obj).val(0);
        }
}
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>

<div>
<input id="weightInput" type="number"   data-key="" data-guid="" onchange="test(this)" value="" />
</div>

CodePudding user response:

You need to pass event as an explicit argument to the onchange argument.

You also shouldn't call it from $(function() { }), since there's no event there.

function test(obj, event) {
  var inputValue = parseInt($(obj).val());
  if (($(obj).val() < 0 || $(obj).val() > 100) && event.keyCode !== 46 // keycode for delete
    &&
    event.keyCode !== 8 // keycode for backspace
  ) {
    event.preventDefault();
    $(obj).val(0);
  } else if (isNaN(inputValue)) {
    event.preventDefault();
    $(obj).val(0);
  }
}
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>

<div>
  <input id="weightInput" type="number"  data-key="" data-guid="" onchange="test(this, event)" value="" />
</div>

CodePudding user response:

You should be using jQuery's listener to handle the event that isnt defined in your current code. You should also use the events target as your object

/***This here**/
jQuery(document).on('change','#weightInput',test);
function test(event) {
        let obj = event.target
        var inputValue = parseInt($(obj).val());

        if (($(obj).val() < 0 || $(obj).val() > 100) && event.keyCode !== 46 // keycode for delete
            && event.keyCode !== 8 // keycode for backspace
        ) {
            event.preventDefault();
            $(obj).val(0);
        } else if (isNaN(inputValue)) {
            event.preventDefault();
            $(obj).val(0);
        }
}
  • Related