0

This is the code I'm trying to get working.

            var inputText = $('<input>', {
                type: 'text',
                name: id,
                onclick: function() {
                    $('#' + nextQuestion).show();
                }
            });

However, when I inspect the DOM and the resulting jQuery object, the onclick method is null. Do I have the syntax wrong?

Your permanent name DOM object

PatPeter
  • 394
  • 2
  • 17

2 Answers2

2

Based on these two answers What's the difference between "click" and "onclick" when creating an element with jQuery?, .prop() vs .attr()

An attribute value may only be a string whereas a property can be of any type.

Therefore, onclick creats an attribute and value should be string that refers to a function.

var inputText = $('<input>', {
       type: 'text',
       name: id,
       onclick: "somefunction()"
 });

somefunction() {}

clickcreates a property on the element and value should be an actual function.

 var inputText = $('<input>', {
   type: 'text',
   name: id,
   click: function () { 
      $('#' + nextQuestion).show();
   }
});
Casper
  • 1,469
  • 10
  • 19
  • 1
    Thank you so much for the quick reply! This code stumped me last night on this project that I just want to get done already. I'm only on the JavaScript and haven't even gotten to the PHP/MySQL yet :'( – PatPeter Oct 15 '19 at 04:23
0

may be this way ?

var inputText = $('<input>', { type: 'text', name: 'something' });

inputText.onclick = function() { console.log('hello') }

console.log( inputText.onclick )
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40