简体   繁体   中英

Button onclick is not working properly

I have an MVC application where I use more views , partial views .

In one partial view I have two buttons:

<button type="submit" id="btnSilviPrioInvoiceShow" class="btn btn-success" onclick="javascript:test()">@Resources.Common.ShowInvoice</button>
<button type="submit" id="btnSilviPrioInvoiceGenerate" class="btn btn-success btnSilviPrioInvoiceGenerate">@Resources.Common.Generate</button>

I need to put some logic in javascript when I click these buttons, but it seems the onclick event is not raised, it does nothing when I click the buttons.

The buttons are in a partial view, in the "parent" view I have added the code:

  $("#btnSilviPrioInvoiceGenerate").on("click", function (e) {
         e.preventDefault();
         console.log("asas");
            //var companyId = $('input[name=IssuerCompanyId]:checked').val();
            var action_url = '@Url.Action("GenerateInvoiceDamage", "TimberMonitor", new { Area = "", id = @ViewBag.Id })';
            window.location = action_url;
            this.disabled = true;
        });

I have tried to add this code inside the

 $(document).ready(function () {

I have tried to add to add outside the

  $(document).ready(function () {

from the "parent" view.

If I try to use the method that it is defined in the onclick event from the button,

function test()
{
    console.log("test");
}

I get the error that test is not defined . If I put the javascript code in the partial view it is working with

  $("#btnSilviPrioInvoiceShow").on("click", function (e) {

, but all the javascript code is in the "parent" view, so I thought it would be better to add there the javascript code. Can you advise?

Make your button like following:

<input type="button" id="btnSilviPrioInvoiceShow" class="btn btn-success" onclick="test()">@Resources.Common.ShowInvoice</input>
    <input type="button" id="btnSilviPrioInvoiceGenerate" class="btn btn-success btnSilviPrioInvoiceGenerate">@Resources.Common.Generate</input>

As you can see, this example works correctly, remove javascript: label

 $("#btnSilviPrioInvoiceGenerate").on("click", function(e) { e.preventDefault(); console.log("btnSilviPrioInvoiceGenerate clicked"); }); function test() { console.log("it is test function"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="submit" id="btnSilviPrioInvoiceShow" class="btn btn-success" onclick="test()">@Resources.Common.ShowInvoice</button> <button type="submit" id="btnSilviPrioInvoiceGenerate" class="btn btn-success btnSilviPrioInvoiceGenerate">@Resources.Common.Generate</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM