0

Please be aware that this is not a duplicate off : Event binding on dynamically created elements?

Not long ago I was struggling with Jquery dynamic event binding but finally got it to work. The syntax I was using was :

$(document.body).on("change", "#registerF > input,  #registerF > select", function () });

#registerF = Id of the form.

input, select = The elements.

And everything was working fine until believe it or not, i decided to change all my links in my site with a variable for better portability.

Was:

http://example.com/path/to/file.php

Became :

var host = "http://example.com";
host + '/path/to/file.php';

All the sudden my jquery dynamic element triggering went off so I looked at it.

I have changed it for :

 $(document.body).on("change", "#registerF * ", function () {});

And it is working but in a weird way.

The event get triggered and this is where it gets weird:

 $(document.body).on("change", "#registerF * ", function () {
  var field_id = ($(this).attr("id"));  <--- is defined
  alert(field_id);  <-------------------- display the id
  var container = ['#' + field_id + "_ck", '#' + field_id + '_err'];
  var data_type = ($(this).attr("data-type")); 
  var value = document.getElementById(field_id).value; <--- ERROR point here
  alert(value) <----- display the good value as being defined

The script is working. the values are interpreted as they should yet I get this error in the console


Uncaught TypeError: Cannot read property 'value' of null

(anonymous function) @ Script.js:254

m.event.dispatch @ jquery.js:4670

r.handle @ jquery.js:4338


My Jquery version is from : https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js

have changed it to 1.12 and still the same.

So I'm totally blown here. How van the value get sent if its undefined!?

Community
  • 1
  • 1
MadeInDreams
  • 1,957
  • 4
  • 28
  • 44

1 Answers1

1

You are doing a lot of extra work to get the id, pass it to another dom search to look for the element again, and then get value after that search when this is already available in the event handler and is the element

Can simplify this down to

$(document.body).on("change", "#registerF :input ", function () {
   alert(this.value);    
});

I have no idea what you are trying to do creating the array container

charlietfl
  • 164,229
  • 13
  • 110
  • 143