VansFannel
VansFannel

Reputation: 45921

Pass caller to a javascript function that allows me to use the .attr method

I'm developing an ASP.NET MVC 5 application with C#, .NET Framework 4.7 and jQuery 1.11.

function RequestCodes(button, poId) {
  button.attr("disabled", "disabled");

That code throws an error saying the object doesn't accept .attr method. I call this function:

<input type="button" value="@Resources.RequestMoreCodes" onclick="RequestCodes(this, @Model[index].ProductionOrderId);" />

Maybe it is better to pass the ID instead of the object.

How can I pass the caller as a parameter to disabled it?

Upvotes: 1

Views: 32

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because the button variable holds an Element object, not a jQuery object. To fix this, wrap it in $(). Also, to disable elements it's better to use prop() over attr().

function RequestCodes(button, poId) {
  $(button).prop("disabled", true);
});

That being said, you should avoid using the outdated on* event attributes. Attach unobtrusive event handlers instead. As you're already using jQuery you can do this:

<input type="button" class="your-button" value="@Resources.RequestMoreCodes" data-productionorderid="@Model[index].ProductionOrderId)" />
$(function() {
  $('.your-button').click(function() {
    var $button = $(this);
    var productionOrderId = $button.data('productionorderid');

    $button.prop("disabled", true);
  });
});

Upvotes: 1

Related Questions