stack
stack

Reputation: 841

Onclick function of button can not work in form.javascript jquery

In my code, onclick function of addDvcPeople() works fine without form. But once form added, the onclick function of addDvcPeople() works fail. Here is the code without form which works fine:

<div class="dvcOnShlv" id="dvcOnShlv">
<!--<form action="modify_idc_addDVC.php?act=add&table=IDC" method="POST">-->
  <table border="1px" cellspacing="0"  id="staTable">
  <tr>
    <h2 align="center">IDCtable</h2>
  </tr>
  <tr>
  <td style="width:15%" id="addDvcWorker">engineer<br /><input type="button" id="addDvcPeople" onclick="addDvcPeople()" value="addpeople"></td>
  </tr>
 </table>
<!--</form>-->
</div>

My addDvcPeople() code is:

<script>
 function addDvcPeople()
{
    alert("test");
}
</script>

Once "form" sentence is added, function addDvcPeople() did nothing. I don't know why.Who can help me ?

Upvotes: 1

Views: 38

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42304

The main problem that you have is that you have given your button the same ID as your function name. You need to ensure that these are different, or your function will always come through as undefined:

function addDvcPeople() {
  alert("test");
}
<form>
  <input type="button" id="addDvcPeople" onclick="addDvcPeople()" value="Button">
</form>

Here this is shown working with a different ID:

function addDvcPeople() {
  alert("test");
}
<form>
  <input type="button" id="addDvcPeopleID" onclick="addDvcPeople()" value="Button">
</form>

A secondary problem you'll encounter is that form submission has a default behaviour of actually submitting a form, even without a submit input, meaning that your form will disappear after the button is clicked:

function addDvcPeople() {
  alert("test");
}
<form>
  <button onclick="addDvcPeople()">Button</button>
</form>

To resolve this, you need to override the default form submission by passing through the event:

function addDvcPeople(event) {
  event.preventDefault();
  alert("test");
}
<form>
  <button onclick="addDvcPeople(event)">Button</button>
</form>

Note that in the above example, the page does not refresh, and the alert appears.

Hope this helps! :)

Upvotes: 2

Tran Audi
Tran Audi

Reputation: 607

You just do not set the duplicate id and function name

Upvotes: 1

Related Questions