Ashwani Tiwari Ashwani Tiwari - 3 months ago 8
Javascript Question

Pass button value attribute value in function which call onclick() function, button created dynamically

I am creating the table row dynamically.In each row ,I am also creating the button .Means every row have the button.On click the button I want to pass the value of the value attribute (value="'+patient.appointmentId+') in the function getAppointment().

<button type="button"
value="'+patient.appointmentId+' "id="cancel-appointment"
onclick = "getAppointment()" class="fa fa-remove btn-transparent">
</button>


Want this

<button type="button"
value="'+patient.appointmentId+' "id="cancel-appointment"
onclick = "getAppointment(patient.appointmentId)" class="fa fa-remove btn-transparent">
</button>

Answer

You can pass the value using this.value:

<button type="button"
    value="'+patient.appointmentId+' "id="cancel-appointment"
    onclick = "getAppointment(this.value)" class="fa fa-remove 
    btn-transparent">
   </button>

If the attribute is different you may use this.getAttribute("value").

function getAppointment(v) {
  console.log('value=' + v);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<button type="button"
        value="'1' "id="cancel-appointment"
        onclick = "getAppointment(this.value)" class="fa fa-remove btn-transparent">Button1
</button>
<button type="button"
        value="'2' "id="cancel-appointment1"
        onclick = 'getAppointment(this.getAttribute("value"))' class="fa fa-remove btn-transparent">Button2
</button>

Comments