dynamically created button and its own value - javascript

How to get data-index of clicked button:
var removePair = $("button[name=removePair]"),
tbody = $('tbody[name=tb-table]'),
function DrawHtml(list) {
var html = '';
for (var i = 0; i < list.length; i++) {
var o = list[i];
html += '<tr name="row-' + i + '">';
html += ' <td>';
html += ' <button name="removePair" data-index="' + i + '" class="btn btn-primary mx-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
html += ' </td>';
html += '</tr>';
}
return html;
}
$(tbody).on("click", removePair, function () {
console.log($(this));
console.log($(this).val());
console.log($(removePair));
});
The only way that I know to add event on dynamiclly added button is to attache it to parrent (tbody), and fire by dynamiclly created button removePair, but I dont know how to get clicked removePair for further logic.
this return tbody instead of removePair
thanks!!

You should pass the selector to .on() method instead of elements. As the elements are created dynamically hence $("button[name=removePair]") doesn't exists.
Use
removePair = "button[name=removePair]"
var removePair = "button[name=removePair]",
tbody = $('tbody[name=tb-table]');
function DrawHtml(list) {
var html = '';
for (var i = 0; i < list; i++) {
html += '<tr name="row-' + i + '">';
html += ' <td>';
html += ' <button name="removePair" data-index="' + i + '" type="button">' + i + '</button>';
html += ' </td>';
html += '</tr>';
}
return html;
}
//Create HTML
tbody.html(DrawHtml(5));
$(tbody).on("click", removePair, function() {
console.log($(this).text());
console.log($(removePair).length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody name="tb-table"></tbody>
</table>

Rather than name attribute use class instead
$('body').on('click', '.btn-primary', function (e) {
});

Related

JS variable not working in AJAX success

Fetched data from database with php and ajax, Everything is ok except note variable is empty.Can somebody find out the issue why note value is not going to display. How can i fix it.
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
var note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}
This is the output
database table
JSON output
{"groupData":{"id":"23","group_name":"Group B"},"results":
[{"id":"2","team_id":"4","team":"Team
B","player":"Deno","result":"14","note":"Lost"},
{"id":"3","team_id":"4","team":"Team
B","player":"Niob","result":"26","note":"Lost"},
{"id":"4","team_id":"4","team":"Team
B","player":"Skion","result":"76","note":"lost"},
{"id":"5","team_id":"5","team":"Team
C","player":"Bela","result":"47","note":"won"},
{"id":"6","team_id":"5","team":"Team
C","player":"yomi","result":"57","note":"won"}]}
You should set note value infront of cats[team].forEach(function(element) {}). Hope to help, my friend :))
success: function(response) {
var cats = {};
response.results.forEach(function(element) {
cats[element.team] = cats[element.team] || [];
cats[element.team].push(element);
});
var i = 0;
Object.keys(cats).forEach(function(team) {
let html = '';
// Append the category header
html = '<tr>';
html += '<td>' + team + '</td>';
html += '</tr>';
$('table').append(html);
var note;
// Loop through the results for this category
cats[team].forEach(function(element) {
var id = element.id;
var teamId = element.team_id;
var names = element.player;
var result = element.result;
note = element.note;
html = '<tr>';
html += '<input type="hidden" name="Id[]" value="' + id + '"/>';
html += '<input type="hidden" name="data[' + i + '][team_id]" value="' + teamId + '"/>';
html += '<td>' + names + '</td>';
html += '<td><input type="text" name="result[]" value="' + result + '"></td>';
html += '</tr>';
$('table').append(html);
});
// Append the textarea at the end of the results
html = '<tr>';
html += '<td><textarea placeholder="note..." name="data[' + i + '][Note]">' + note + '</textarea></td>';
html += '</tr>';
$('table').append(html);
i++;
});
}

Get table row value with jQuery/JS

I am trying to get table value names with the following code:
my table :
function CreateBlockDeployTableRow(data) {
return "<tr>" +
"<td>" + data.EnvTypeName + "</td>" +
"<td>" + data.AppTypeName + "</td>" +
"<td>" + deleteBtn + "</td>" +
"</tr>";
}
my button:
var deleteBtn = '<button class="btn btn-danger unblock-button btn-sm
glyphicon glyphicon-minus" type=button > </button> '
on click function:
function UnblockRequestHandler()
{
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler();
});
}
and here I want to send my Environment and Application to server side and take the value of the rows in the table , but the code is not working and not taking anything:
function sendUnblockDeploySubmitHandler() {
var $row = jQuery(this).closest('tr');
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML +
'<br/>';
alert(values);
});
console.log(values);
}
html code :
<div class="tbl-responsive">
<table id="blockDeployTable" class="table table-hover
requestsblockDeployTable" style="font-size: 0.8em; margin-top: 120px;
text-align:center">
<thead>
<tr>
<th>Environment</th>
<th>Repo</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Where am I wrong here I cannot understand?
You could just pass the click event through to the sendUnblockDeploySubmitHandler function:
$('.unblock-button').click(function () {
sendUnblockDeploySubmitHandler(event); // pass event to function
});
function sendUnblockDeploySubmitHandler(event) {
var $row = $(event.target).closest('tr'); // event.target is the button
var $columns = $row.find('td');
$columns.addClass('row-highlight');
var values = "";
jQuery.each($columns, function (i, item) {
values = values + 'td' + (i + 1) + ':' + item.innerHTML + '<br/>';
alert(values);
});
console.log(values);
}
I've put together a jsbin to show this working: https://jsbin.com/sosimudubi/1/edit?html,js,console,output
You are trying to access jQuery(this) in the sendUnblockDeploySubmitHandler() method but the this handle does not refer to the button element. I would suggest you to directly pass the callback function when you bind the click event.
function UnblockRequestHandler() {
$('.unblock-button').click(sendUnblockDeploySubmitHandler);
}
This way, you can access the corresponding button element using jQuery(this) in the sendUnblockDeploySubmitHandler()

Toggle animation on click

I would like to add a jquery toggle effect on my code which has HTML within my Javascript. Any advice?
GuessGame.prototype.createBoard = function(){
var html = '';
Object.keys(this.cards).forEach(function(key) {
html += '<div class="card" id="' + key + '"';
html += ` style='background-image: url(img/${key}.jpg)'`;
html += '>'
html += '<div class="front" ';
html += 'id="' + key + '">';
html += '</div>';
html += '</div>';
});
// Add all the divs to the HTML
document.getElementById('board').innerHTML = html;
In your example you're not really using the power of jQuery.
Here is a better approach.
GuessGame.prototype.createBoard = function(){
var board = $('#board');
Object.keys(this.cards).forEach(function(key) {
var card = $('<div class="card" id="' + key + '" style="background-image: url(img/${key}.jpg)"><div class="front"></div></div>');
// add onClick Event
card.on('click', function(e) {
card.toggleClass('toggled-class');
});
// append card to board
board.append(card);
});

Add a Click Event to elements added to the DOM

var myOP = '<div>';
for (var i = 0; i < op.length; i++) {
myOP += '<div>';
myOP += '<div id="myBTN-' + [i] + '">' + op[i]['Field1'] + '</div>';
myOP += '<div id="blah-' + [i] + '">' + op[i]['Field2'] + '</div>';
myOP += '</div>';
}
myOP += '</div>';
$("#myBTN-" + i).click(function () {
$('#blah-' + i).toggle("slow");
});
$('#container').html(myOP);
I'm trying to get the click function to fire on the elements i'm created w/ the above for loop. Can anyone point me in the right direction?
As long as the element is just a String, you won't be able to add a handler. You have to add the handler after $('#container').html(myOP);
You could try exploring the idea of event delegation. Using that, your could do something like:
$('#container').on('click', function(e){
e = e || event;
var from = e.target || e.srcElement, i;
if (from.id && /^mybttn/i.test(from.id)){
i = +((from.id.match(/\d{0,}$/)||[-1])[0]);
if (i>=0){
$('#blah'+i).toggle('slow');
}
}
});​
​Demo
Alternatively you could
$('#container').html(myOP);
$('div[id^="myBTN-"]').on('click',function(){
$('#blah-' + this.id.match(/\d{0,}$/)[0]).toggle("slow");
});
after you save the html into #container use this:
$('[id^="myBTN-"]', '#container').click(function () {
$(this).closest('[id^="blah-"]').toggle('slow');
});
jQuery's .on() method will bind to appended elements if used properly. http://api.jquery.com/on/
<div id="existingParent">
<!--<div class="added-later">Hi!</div>-->
<!--<div class="added-later">Hi!</div>-->
</div>
To listen for events on the added-later elements
$('#existingParent').on('click hover','.added-later', myFunction);
The method must be bound to an element that exists. $('body') can be used here, but at the cost of some performance I'd imagine.
Do something like this:
var myOP = '<div>';
for (var i = 0; i < op.length; i++) {
myOP += '<div>';
myOP += '<div id="myBTN-' + [i] + '">' + op[i]['Field1'] + '</div>';
myOP += '<div id="blah-' + [i] + '">' + op[i]['Field2'] + '</div>';
myOP += '</div>';
}
myOP += '</div>';
$(myOP).appendTo('#container').find('div[id^="myBTN"]').click(function () {$(this).next().toggle("slow")});
When you re trying to attach events added dynamically, a simple .click() won't do, you have to use on:
$("#newElementparent").on('click', "#newElement", function() {});
You'd do better to build the element on the fly:
var container = $('<div>');
for (var i = 0; i < op.length; i++) {
container.append(
$('<div>').append(
$('<div>').text(op[i]['Field1']).click(function() {
$(this).next('div').toggle("slow");
}),
$('<div>').text(op[i]['Field2'])
)
);
}
$('#container').empty().append(container);

get drop down box attributes

In the below i have a a div with employee names and ahave to assign a grade for them,my question is that i have get the empid for all the selected values in getgrade_values function.Using jquery how to get the ids of the drop down box with its value where the values are selected when on click of evaluate function
function getgrade_values(empid)
{
var ele='<select id="'+ empid +'" name="emp" style="width:40px;margin:0px 0pt;" >';
ele += '<option value=""></option>';
ele += '<option value="A">A</option>';
ele += '<option value="B">B</option>';
ele += '<option value="C">C</option>';
ele += '<option value="D">D</option>';
ele += '<option value="E">E</option>';
ele += '<option value="F">F</option>';
ele += '</select>';
return ele;
}
function sendparams(data)
{
if(data.status == 1)
{
var ele='<tr id="std"><td><b>Evaluate:</b></label> </td></tr>';
for(var l=0;l<data.emparr.length;l++)
{
ele += '<tr><td><div id="'+ data.emparr[l].id +'">' + data.emparr[l].name + "</td><td>" + getgrade_values(data.emparr[l].id) + '</div></td></tr>';
ele+= '<input type="button" value="Evaluate" onclick="evaluate();"';
}
}
var select = $('select[name="emp"]')
var empId = select.attr('id')
alert('empId = '+empId)
select.children('option:selected').each(function() {
alert('grade selected = ' + $(this).val())
})
DEMO : http://jsfiddle.net/hdTEP/
Currently, you will have 2 elements with id="<employeeId>". As ids should be unique across an entire page, you should consider appending the type of element you are representing, for example id="<employeeId>_gradeInput" for your grade dropdown. Next, for each user it seems like you have a button to submit a grade. I would call evaluate with the employee id associated with that button.
function getgrade_values(empid){
var ele='<select id="'+ empid +'_gradeInput" name="emp" style="width:40px;margin:0px 0pt;" >';
..//Remaining code
}
function sendparams(data) {
if (data.status == 1) {
var ele =
'<tr id="std">' +
'<td>' +
'<b>Evaluate:</b>' +
'</td>' +
'</tr>';
for (var l = 0; l < data.emparr.length; l++) {
var employeeId = data.emparr[l].id;
ele +=
'<tr>' +
'<td>' +
'<div id="' + employeeId + '_divContainer">' +
data.emparr[l].name +
'</div>'
'</td>' +
'<td>' +
getgrade_values(employeeId)
'</td>' +
'</tr>';
ele += '<input type="button" value="Evaluate"
onclick="evaluate(' + employeeId + ');"';
}
}
function evaluate(employeeId){
var gradeValue = $('#' + employeeId + '_gradeInput').val();
..//Your other evaluate code here
}

Categories