Refresh html Editable table on adding new rows - Bootstable - javascript

I use the boostable plugin to edit HTML rows inline on runtime. The plugin is on https://www.jqueryscript.net/table/Editable-Tables-jQuery-Bootstrap-Bootstable.html. The problem is now when I want to dynamically add new rows to the table, I am not able to re-initialize the table or refresh so as to make all rows Bootstable(editable)
After adding /assets/plugins/editable/bootstable.js">
The following code is the one I use ti initialize the table
$('#tbl_deposists').SetEditable({
columnsEd: "1",
onEdit: function() {},
onDelete: function() {},
onBeforeDelete: function() {},
onAdd: function() {}
});
The following code is the one I use to add extra rows on runtime
$("#add_deposit").click(function(){
var name = $("#deposit_name").val();
var amount = $("#deposit_amount").val();
var markup = "<tr><td>" + name + "</td><td class='text-right'>" + amount + "</td></tr>";
$("#tbl_deposists tbody").append(markup);
});

I will suggest this . The initialize will look like below, you can set the button. This will automatically add the new row. You can add your other settings like columnsEd while initializing, but the example show how can you tell bootstable which button to use to add new rows.
$('#tbl_deposists').SetEditable({ $addButton: $('#add_deposit')});
button can look like this
<button class="btn btn-info" id="add"><span class="glyphicon glyphicon-plus-sign"></span>Add</button>
EDITED :
I tried this and looks like this works. You can actually put the html for last TD and everything will work, I mean edit, delete etc.
$("#add_deposit").click(function(){
var name = $("#deposit_name").val();
var amount = $("#deposit_amount").val();
var markup = "<tr><td>" + name + "</td><td class='text-right'>" + amount + "</td><td name='buttons'><div class='btn-group pull-right'><button id='bEdit' type='button' class='btn btn-sm btn-default' onclick='rowEdit(this);'><span class='glyphicon glyphicon-pencil'> </span></button><button id='bElim' type='button' class='btn btn-sm btn-default' onclick='rowElim(this);'><span class='glyphicon glyphicon-trash'> </span></button><button id='bAcep' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowAcep(this);'><span class='glyphicon glyphicon-ok'> </span></button><button id='bCanc' type='button' class='btn btn-sm btn-default' style='display:none;' onclick='rowCancel(this);'><span class='glyphicon glyphicon-remove'> </span></button></div></td></tr>";
$("#tbl_deposists tbody").append(markup);
});

Related

Fields breaking after Upgrade to JQuery 3.5.1

I have a table that is created using javascript based on what is put in a list. This works fine in Jquery 3.4, but when I upgrade to 3.5 I am seeing this break.
HTML
<h5>Questions</h5>
<table id="questionTable" class="table q">
<thead>
</thead>
<tbody id="qTable"></tbody>
</table>
<div id="questionDiv">
<input type="button" value="Add Question" onclick="AddNewQuestion()" class="btn btn-primary"/>
</div>
<hr />
<div id="questionDiv">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$(function () {
AddCurrentQuestions();
});
});
var table = document.getElementById("qTable");
var rowCount = table.rows.length;
var counter = rowCount.length;
function AddCurrentQuestions() {
var status = #Html.Raw(Json.Encode(Model.isNull));
if (status == false) {
#{ Model.QuestionList.Add(new Performance_Planning.ViewModel.QuestionViewModel.Questions());}
var questionItems = JSON.parse('#Html.Raw(Json.Encode(#Model.QuestionList))');
for (var i = 0; i < questionItems.length - 1; i++) {
var qItem = questionItems[i];
var questionDetail = qItem.Question;
//Create fields
var qTextCell = "<td><textarea id='QuestionList_" + i + "_Question' name='QuestionList[" + i + "].Question' class='Questions' /></td>";
var indexCell = "<td style='display:none'> <input name='QuestionList.Index' type='hidden' value='" + i + "' /></td>";
var removeCell = "<td align='center'><input id='btnDelLine'" + i + "type='button' value='Remove' onclick=\"removeRow('" + i + "')\" class='btn btn-primary' /></td>";
var newRow = "<tr id='qLineItem" + i + "'>" + indexCell + qTextCell + removeCell + "</tr>";
//Add row to table
$('#qTable').append(newRow);
//Add Values
$('#QuestionList_' + i + "_Question").val(questionDetail)
counter = i;
};
} else {
counter = 0;
AddNewQuestion();
}
};
function AddNewQuestion() {
#{ Model.QuestionList.Add(new Performance_Planning.ViewModel.QuestionViewModel.Questions());}
counter++;
//Create field
var indexCell = "<td style='display:none'> <input name='QuestionList.Index' type='hidden' value='" + counter + "' /></td>";
var qTextCell = "<td><textarea id='QuestionList_" + counter + "_Question' name='QuestionList[" + counter + "].Question' class='Questions' /></td>";
var removeCell = "<td align='center'><input id='btnDelLine'" + counter + "type='button' value='Remove' onclick=\"removeRow('" + counter + "')\" class='btn btn-primary' /></td>";
var newRow = "<tr id='qLineItem" + counter + "'>" + indexCell + qTextCell + removeCell + "</tr>";
$('#qTable').append(newRow);
};
function removeRow(id) {
var rowId = "qLineItem" + id;
var row = document.getElementById(rowId);
row.parentNode.removeChild(row);
};
</script>
}
What I end up seeing is that the remove button is treated as text in 3.5.1 but this doesn't occur with 3.4. I am unsure how to solve this issue or if I will need to figure out another way to write this page.
When I view the webpage and inspect the field I see it do the following:
<textarea id="QuestionList_0_Question" name="QuestionList[0].Question" class="Questions">
"</td><td align='center'><input id='btnDelLine'0type='button' value='Remove' onclick="removeRow('0')" class='btn btn-primary' /></td></tr></tbody></table>"
The textarea element should have a separate close tag. It is not allowed to self-close. So this is not valid HTML:
<textarea />
But this is:
<textarea></textarea>
Apparently, jQuery 3.5 is more strict in this. An inspection of the 3.5 changelog reveals that this is a consequence of the security fix they applied:
The main change in this release is a security fix, and it’s possible you will need to change your own code to adapt. Here’s why: jQuery used a regex in its jQuery.htmlPrefilter method to ensure that all closing tags were XHTML-compliant when passed to methods. For example, this prefilter ensured that a call like jQuery("<div class='hot' />") is actually converted to jQuery("<div class='hot'></div>"). Recently, an issue was reported that demonstrated the regex could introduce a cross-site scripting (XSS) vulnerability.
The HTML parser in jQuery <= 3.4.1 usually did the right thing, but there were edge cases where parsing would have unintended consequences. The jQuery team agreed it was necessary to fix this in a minor release, even though some code relies on the previous behavior and may break. The jQuery.htmlPrefilter function does not use a regex in 3.5.0 and passes the string through unchanged.
One can see how before 3.5, jQuery would actually change <textarea /> to <textarea></textarea> on the fly, thereby fixing the error you made. But now with version 3.5 jQuery no longer does that, and so your HTML remains invalid, leading to an unintended rendering where everything after <textarea /> ends up as content to that text area element.

Dynamic HTML buttons within the scope of Javascript ajax calls

I'm currently populating an HTML table to display users. I use calls to an API to serve my user data to the table, and Javascript to append the row to the table. The last entry in each row features a delete button, which is supposed to pass user data as a $put to a separate API endpoint to delete the user of the corresponding row:
//Existing adhoc-users table.
var adhocUsersHtml = "<div><table class='table table-striped'><tr><th>Section</th><th>Role</th><th>First Name</th><th>Last Name</th></tr>";
$.each(json.sections, function (index, section) {
$.each(section.enrollments, function(index, user) {
if (user.adhocEnrollment == true) {
adhocUsersHtml += "<tr><td>" + section.sectionTitle + "</td><td>" + user.roleName + "</td><td>" + user.firstName + "</td><td>" + user.lastName + "</td>"
+ "<td><button id='delete' class='btn btn-default' data-style='height: 30px; margin-top: 0;'>Delete</button></td></tr>";
}
});
});
adhocUsersHtml += "</table></div>";
return adhocUsersHtml;
What's the best pattern for scoping 'this' with the delete buttons?
Should I put a custom attribute on the button that holds the user id for that row, and then add an onClick to all delete buttons that grabs the id and preforms the $put?
Is it possible to add an onClick function right after declaring HTML before appending it to the DOM with Javascript?
Put the user id into a data attribute on the delete button and add a single event handler to the table to handle all delete button clicks.
<button class='delete-user-btn' data-id="myUserId">Delete</button>
$("#myTable").on("click", ".delete-user-btn", function() {
var id = $(this).attr("data-id");
//delete code goes here
});
firstly, you are going to have many buttons so attribute id='delete' isn't appropiate
I will put class "delete" instead without userId and register onClick Listener after all buttons rendered
and since each row represent a user, i will put id on each row
<tr data-val="{userID}">
....
<td><button class='btn btn-default delete' data-style='height: 30px; margin-top: 0;'>Delete</button></td>
</tr>
<script>$('.delete').on('click', function(e) {
var tr = $(e.target).closest('tr'),
id = tr.data('val')
... do your code
})</script>

How to use a Bootstrap popover in a dynamic table

I am trying to implement the Bootstrap popover on my HTML page. I have a popup that is in an HTML table which I am building dynamically and I suspect I am not registering the event correctly.
My HTML:
$.each(JSON.parse(data), function (index, elem) {
var radioBtn = "<input type='radio' name='radOption' class='radio selectedOptionAdd' data-value='myData' />";
var popupContent = "TO DO MAKE A TABLE OF DATA";
var popupControl = "<a class='btn btn-lg btn-danger permissionPopUpButton' role='button' data-toggle='popover' data-trigger='focus' title='Dismissible popover' data-content='" + popupContent + "'>Dismissible popover</a>";
myTable += "<tr><td>" + radioBtn + "</td><td>" + popupControl + "</td></tr>";
});
In my document.ready I have the following statement:
// Originally tried this but this doesn't work
//$('[data-toggle="popover"]').popover();
$("body").on("click", ".permissionPopUpButton", function () {
$('[data-toggle="popover"]').popover();
});
Any advice on how to correctly register this event?
I found out that this will work.
$("body").on("click", ".permissionPopUpButton", function () {
$(".popover").css("width", "276px");
$('[data-toggle="popover"]').popover();
});
However I was missing the "tabindex='0'. Once I added that to my tag the popup started working!
var popupControl = "<a tabindex='0' class='btn btn-lg btn-danger permissionPopUpButton' role='button' data-toggle='popover' data-trigger='focus' title='I am a title' data-content='I AM CONTENT HEAR ME ROAR'>Dismissible popover</a>";

Links not working in IE and Firefox with jquery generated markup

I'm writing a javascript app that dynamically generates buttons that lead users to links about different products.
They look like this:
The problem is when they're generated the links contained within them work in chrome but not in IE or Firefox.
Here's the HTML:
HTML
<div class="row">
<div class="button-class">
</div>
</div>
This is the code I use to generate them:
JQUERY
buttons: function(num) {
$(".button-class").html("<div class='text-center'><ul class='list-inline'><li><button class='btn btn-success'><a href=" + state.greens[num].website + " target='_blank'>Company Website</a></button></li> <li><button class='btn btn-success' data-toggle='modal' data-target='#myModal'>View the Label</button></li></ul></div>");
if (state.greens[num].link !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href=" + state.greens[num].link + " rel='nofollow' target='_blank'>Get It On Amazon</a></button></li>");
}
if (state.greens[num].review !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href=" + state.greens[num].review + " target='_blank'>Read The Review</a></button></li>");
}
},
buttons is part of an object called display and is called by display.buttons();
The two if statements check to see if certain types of links exist within a product's object and then appends them to the UL if the ydo.
The buttons generate correctly but they don't open up the links when clicked in Firefox and IE (maybe Safari but I haven't checked).
What's more confusing to me is that the html being generated looks semantically correct.
For example this is the html shown in the Firefox debugger that's not working:
Doesn't make sense to me.
If you want to go to a live version of the page you can see it here: superfood picker
Then go to the last section that reads "Click On A Product's Detail Page To Learn More" and looks like this:
Click on one of the products and it'll take you to the buttons that I'm talking about.
It's not semantically correct because you need to wrap in quotes the href
buttons: function(num) {
$(".button-class").html("<div class='text-center'><ul class='list-inline'><li><button class='btn btn-success'><a href='" + state.greens[num].website + "' target='_blank'>Company Website</a></button></li> <li><button class='btn btn-success' data-toggle='modal' data-target='#myModal'>View the Label</button></li></ul></div>");
if (state.greens[num].link !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href='" + state.greens[num].link + "' rel='nofollow' target='_blank'>Get It On Amazon</a></button></li>");
}
if (state.greens[num].review !== false) {
$(".button-class ul").append("<li><button class='btn btn-success'><a href='" + state.greens[num].review + "' target='_blank'>Read The Review</a></button></li>");
}
},
Note that's it's best if you change double quotes instead single quotes and viceversa.

how to create button dynamically and add the onclick event for html page

i have created one button in my javascript code, after clicking on this button it should go to the product.html
var outputb2 = "<p align=right>"+ "<input type=button value=productandservices onClick=window.location=product.html>" + "</input>" +"</p>";
$('#product').append(outputb2);
where product is the div id in the product.html.but when i click on this button product and services..its not going to this product.html.how can i do..?
I don't know why you are using javascript for this, unless you are sending some data with the click event. there is a simple html code to do what you want.
product and services
If you must use java-script try this
onclick="javascript:location.href='product.html#product'"
Check this out
<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices >" + "</input>" +"</p>";//added id
$('#product').append(outputb2);
$(document).ready(function()
{
$(document).on("click","#productandservices",function()
{
alert('clcik');
window.location='product.html';
});
});
</script>
or
Enclose filename in quotes '
<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices onClick=window.location='product.html' >" + "</input>" +"</p>";
$('#product').append(outputb2);
</script>
Probably you need some escape characters in your code, it will work
var outputb2 = "<p 'align=right'>"+ "<input type='button' value='productandservices' onClick='window.location=\"product.html?someParam=hi\"'>" + "</input>" +"</p>";
$('#product').append(outputb2);
var outputb2 = "<p align=right>";
outputb2 += "<input type='button' value='productandservices' onClick='window.location=product.html'>"
outputb2 += "</p>";
$('#product').append(outputb2);
var outputb2 = "<p align='right'><input type='button' value='productandservices' onClick='window.location=product.html'></input></p>";
$('#product').append(outputb2);
right syntax to use:
<input TYPE="button" value=productandservices onclick="window.location.href='http://www.wherever.com'">
Another option is to create a link in the button:
<button type="button">Link link</button>
Then use CSS to style the link and button, so that the link takes up the entire space within the button (so there's no miss-clicking by the user):
button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}
but the point of a link is to go to another page. So trying to make a button act like a link is the wrong solution. My suggestion is that you should use a link and style it to look like a button.
<a href="/page2>Continue</a>
Try this :
var outputb2 = "<p align='right'>"+
"<input type='button' value='productandservices 'onClick='window.location=\"product.html\"' />" +
"</p>";
$('#product').append(outputb2);
Add ' like this : onClick='window.location=\"product.html\"'
Live demo

Categories