adam
adam

Reputation: 378

Add onClick with self input parameter of a jQuery object?

Desired output in HTML:

<input onclick="someFunction(this)"/>

Attempt:

var input = $("<input/>");
input.attr("onclick", "someFunction(this)");
$("#body").append(input)

Result:

<input onclick="[object Object]"/>

I have tried using:

input.click({param: "this"}, someFunction);

I have also tried replacing "this" with "input". No luck.

jQuery is not a requirement, however I need this done dynamically. The above is just a sample, the actual object has more attributes.

Upvotes: 0

Views: 1161

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

You could create the listener in-memory instead of adding the handler as an attribute. This version lets you wrap your event target in a jQuery object ahead of the function call.

const someFunction = ($element) => {
  console.log($element.prop('class'));
}

const $input = $('<input>', { class: 'foo' })
  .on('click', (e) => someFunction($(e.target)))
  .appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But if you really need to add it as an attribute, you could do the following.

const someFunction = (element) => {
  console.log($(element).prop('class'));
}

const $input = $('<input>', { class: 'foo' })
  .attr('onclick', 'someFunction(this)')
  .appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Anton
Anton

Reputation: 2703

All is working from the box...

Here is example. Just click on input

var input = $("<input/>");
input.attr("onclick", "someFunction(this)");
$("#body").append(input);

function someFunction(obj) {
  $('#result').css('color', 'red');
  console.log(obj);
}

$('#result').text(input[0].outerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body id="body">
  <div>This is your code:</div>
  <div id="result"></div>
</body>

And you can also use pure jQuery. The $(this) is what you need.

var input = $("<input id=\"xxx\"/>");
input.click(function() {
  const theInput = $(this);
  console.log(theInput[0]);
});
$("#body").append(input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="body"></body>

Upvotes: 2

m1k1o
m1k1o

Reputation: 2364

Use arrow function, this will be inherited.

input.on('click', () => someFunction(this))

Upvotes: 1

Related Questions