0

When editing a block, the Add Block form inserts input fields with data from the DB. New empty input text fields can also be added with a button on the same form.

The auto and manual insert codes are identical:

<script type="text/javascript">    
$(function(){
    // Auto insert inputs with values from DB
    var price = $('<td><?php echo $form->text('prices[]', $row['price'], ['class' => "decimals"]); ?></td>');
    // Manually insert inputs with the button
    $("#add").click(function() {
        var price = $('<td><?php echo $form->text('prices[]', '', ['class' => "decimals"]); ?></td>');
    });
    // Check if only numeric keys pressed
    $('.decimals').keydown(function (e) {
    ...
    });

Both auto and manually inserted inputs have 'decimals' class (verified in the browser console). The $('.decimals').keydown only allows numeric key presses, no letters.

But the problem is the 'decimals' class is only active, that is the keydown only works on the auto inserted inputs and it does NOT work on the manually inserted inputs, despite the latter having it.

Why is the 'decimals' class not recognised or the keypress not working on the manually added inputs?

[SOLVED]

Thanks to Keith, changing

$('.decimals').keydown(function (e) {

to

$('#build_table').on('keydown', '.decimals', function(e) {

worked!

PS. where <tbody id="build_table">

ref. http://api.jquery.com/on/ for more info on Delegated events

linuxoid
  • 1,415
  • 3
  • 14
  • 32
  • 1
    have you tried using $(document).on('keydown', '.decimals', function(){...}); – Keith Apr 30 '18 at 12:55
  • I've changed '$(function(){' to '$(document).ready(function() {' - no difference – linuxoid Apr 30 '18 at 13:06
  • when you look in developer tools, and put a breakpoint on it, its not even hitting? also did you try keypress instead of keydown? – Keith Apr 30 '18 at 13:07
  • no, nothing. But I've just noticed you've changed the 'on' function, not the global js function. So I've changed mine to '$(document).on('keydown', '.decimals', function(e) {' - and it works!!! Thank you very much! – linuxoid Apr 30 '18 at 13:10
  • great :) I couldn't tell you how many times i wrote it your way to start, only for it not to be recognized. If that happens, just change it to hit the document first, then add in your identifier afterwards with 'on' – Keith Apr 30 '18 at 13:11
  • but why does it work with auto add but not with manual add? – linuxoid Apr 30 '18 at 13:12
  • i could never find out why it works that way. Maybe because its using an ID instead of a class – Keith Apr 30 '18 at 13:13
  • can't be, both statements in auto and manual add are totally identical – linuxoid Apr 30 '18 at 13:15
  • yeah then i couldn't answer that question for yah – Keith Apr 30 '18 at 13:16

0 Answers0