Is there better way for following HTML Blade & jQuery scenario - javascript

I have a page with a response where a few items in a key named "tables" are coded as JQuery DataTable. My Goal is to do CRUD Operation on the same page index.blade.php by using Bootstrap Modal.
On clicking the EDIT button, I wanted to get clicked-row data in jQuery <script> and then fill it into the form inside a Modal.
As I've just started out with this as my first project, after two days long RnD on here and Google, I've figured out a way to do it. The next task I'm going to do is get & post requests via Ajax. But before that, I want to make sure if this is a good way or do I need a particular change/improvement.
Following is my script tag & HTML button:
<a href="javascript:void(0);" class="btn btn-sm text-primary btn-icon editButton"
data-bs-toggle="modal" data-bs-target="#editModal" data-id="{{ $table->id }}">
<i class="bx bx-edit-alt me-1"></i>
</a>
<script type="text/javascript">
$(document).ready(function() {
$('#myTable').DataTable();
var tables = #json($tables);
// Edit Function
$('.editButton').on('click', function() {
// Picking the clicked table from the response
var table;
for (let index = 0; index < tables.length; index++) {
if (tables[index].id == $(this).data("id")) {
table = tables[index];
break;
}
}
// Filling the Modal Form
$('#name').val(table.name);
$('#seats').val(table.seats);
$('#status').prop('checked', table.status);
$('#editForm').attr('action', '/tables/' + table.id);
// Focuses on the Name Field
$("#editModal").on('shown.bs.modal', function() {
$(this).find('#name').focus();
});
});
});
</script>

Related

Laravel js DataTable: how do I assign a value from js back to the .blade?

I have these rows:
each row is being outputted by the DataTable plugin within app.js
my target is this particular value, ${row.category_id}
let TABLE = $('#categoryList').DataTable({
{ data: 'id', name: 'id', width: '10%', orderable: false, searchable: false,
render: (data, type, row) =>{
let html = "";
if(row.category_name && row.category_name.toUpperCase() !== "GENERAL"){
html += `<ul class="list-inline no-margin">`;
html += `<li class="list-inline-item">
<button type="button" value="${row.category_id}" class="edit_category btn btn-outline-secondary"><i class="fas fa-edit" aria-hidden="true"></i> Edit</button>
</li>`;
html += `</ul>`;
}
return html;
}
}
});
now I have this blade file, index.blade.php that is connected to app.js using:
<script src="{{asset('/modules/bbr-category-configuration/js/app.js')}}"></script>
What I need to resolve is the constant below:
#section('scripts')
<script type="text/javascript">
const SELECTED_CATEGORY_ID = 1;
</script>
#endsection
by default it is set as 1, but this needs to changed each time the 'Edit' button is clicked (refer to the screenshot). Once the button is clicked, I need to get ${row.category_id} and assign it to the const SELECTED_CATEGORY_ID. What is the correct way of doing this?
TLDR: how do I pass a value from .js back to .blade.php?
What I tried:
my first obstacle is to get the value from ${row.category_id} on click, but here is where I got stuck
$(document).on('click', '.edit_category', function () {
console.log(${row.category_id});
});
I cannot console.log (to test if I got the correct variable) outside the DataTable because it cannot be read, or do it inside toe columns because it is not the right syntax.
please feel free to ask for any clarifications.
First of all, if your variable's data will change during the process then it is not const it should be declared as let. You should know the difference between var let and const.
And you can use data-* attributes in the edit button so you can easily fetch the category_id when that button is clicked eg:
<button type="button" data-category=`${row.category_id}`class="edit_category">Edit</button>
Then on click event, you can get that data using
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).data('category');
});
You can fetch the value attribute of the button too using jquery. But generally, I don't use that. Or I haven't seen much usage of that too. You can try it like this too
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).value;
});

Passing the parameter via an automatically generated JavaScript link to the controller

I have a problem with passing the parameter via the link to the controller. The view in which I have a problem is to dynamically display the list of users, along with the possibility of searching for them. I did this part in js and it works fine. In this functionality in js I generate a link to the buttons, so that later, after pressing the button, you can save the selection in the database. Each link has an assigned user ID and user group ID. My problem is that when I press the button, nothing happens.
The following code represents the functionality described above. I would be very grateful for your help.
#if(ViewData[Enums.States.UserSelectWindow.ToString()].ToString() == "True")
{
<script type="text/javascript">
$("#UserlistCollectionId").css('height', $("#WindowUserSelectId").height() + 'px');
let users = #Html.Raw(Json.Serialize(UserModel.GetUsers()));
function Clear() {
$("#UserlistCollectionId").empty();
}
function FillAll(users) {
Clear();
for (user of users) {
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-action="AddUserToGroup" asp-controller="Settings" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
}
}
FillAll(users);
$("#SearchInputId").keyup(function () {
Clear();
let searchValue = $("#SearchInputId").val();
if (searchValue === "")
FillAll(users);
else {
for (user of users) {
if (user.name.includes(searchValue)) {
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
}
}
}
});
</script>
}
In the above code, automatic link generation is performed using JQuery as follows:
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
Unfortunately it doesn't work. In the inspection of the page you can see that the tag "a" does not have the attribute "href", only automatically puts all the code in quotes:
Screen of the html fragment in the browser
Firstly, you need read the doc about what does asp-route-{value} generate the url:
Any value occupying the {value} placeholder is interpreted as a potential route parameter. If a default route isn't found, this route prefix is appended to the generated href attribute as a request parameter and value
(/home/index?value=aaa). Otherwise, it's substituted in the route template. More explantion you could refer to the document.
Secondly, you do not specify the controller and action name, so the url will generate depending on your request url. That is to say, if the tag helper exists in Home/Privacy.cshtml, it will generate to:href="/home/privacy?value=aa".
Finally, Tag Helpers are interpreted. In other words, Razor must see them as actual tags in order to replace them. So what you did in js will not follow the tag helper generation principle, it's just a JS string. You need change the url like below:
<a class="btn btn-sm btn-success" href="/home/index?groupId=' +#Model.Group.Id+'&userId=' + user.id+'">Wybierz</a>
If the url matches the default route template, the url may like below:
<a class="btn btn-sm btn-success" href="/home/index/' +#Model.Group.Id+'/' + user.id+'">Wybierz</a>

Is there any way to backtrack the button which called a function using onclick property from that function in javascript

I have been working recently on a project where I am adding rows to a table using AJAX , and one of the field is actually a button which will delete that row
$("#question-table").append(" <td class='hovy'> <button
class='btn btn-danger delete-button' onclick='jo()'> Delete</button> </td>");
I have tried jQuery, but it's not catching the button click event so I tried onclick property of a button to call a Javascript function, but the problem is how am I going to track the button that called this function in order to delete that row.
Thanks in advance!
var ajax = {row: 'some row data to render', id: '123'}; // your ajax response
// set the id of the row entry as a param of jo(); and then filter your model by it
var btn = $('<button> Delete</button>').on('click', function(){jo(ajax.id)});
$("#question-table").append(btn);
checkout MCV pattern and client state
Give this Fiddle a look and see if it helps you out:
$('#populateButton').click(() => {
for (var i = 0; i < 3; i++) {
$('#question-table').append(
$(`<tr id='row${i}'>`).append($(`<td id='td${i}''>`).append(`<button class='btn btn-danger delete button'>Delete Row ${i}</button>`).click(doDelete))
);
}
});
function doDelete() {
this.closest('tr').remove();
}
https://jsfiddle.net/2jcypdsn/

Dynamic attribute value element locator in Protractor

When I add a new button with some value it gets dynamically added into DOM. Non-Angular HTML element for this button is:
<li class="ui-state-default droppable ui-sortable-handle" id="element_98" data-value="2519">
25.19 EUR
<button type="button" class="btn btn-default removeParent">
<span class="glyphicon glyphicon-remove" aria-hidden="true">
</span>
</button>
</li>
Once I remove this button I want to check it is not present anymore. Element that I'm searching for is data-value="2519"and this could be anything I set, like for example 2000, 1000, 500, 1050,...
In page object file I have tried to use the following:
this.newValueButtonIsNotPresent = function(item) {
newValueButton = browser.element(by.id("containerQUICK_ADD_POINTS")).all(by.css('[data-value="' + item + '"]'));
return newValueButton.not.isPresent();
};
And in spec file I call this function as follows:
var twentyEurosButtonAttributeValue = '2000';
describe("....
it ("...
expect(predefined.newValueButtonIsNotPresent(twentyEurosButtonAttributeValue)).toBeTruthy();
I know this is not correct, but how I can achieve something like that or is there another way?
Stupid me, I found a simple solution. Instead dynamically locating an element I located the first on the list, which is always the one, which was newly added and then checked if it's text does not match:
Page object file:
this.newValueButtonIsNotPresent = function() {
newValueButton = browser.element(by.id("containerQUICK_ADD_POINTS")).all(by.tagName('li')).first();
return newValueButton.getText();
};
Spec file:
// verify element 20.00 EUR is not present
predefined.newValueButtonIsNotPresent().then(function(value) {
expect(value).not.toEqual(twentyEurosText);
});

How to insert Bootstrap drop-down values in database

i am using bootstrap for making a user form.
Now i need to insert selected drop-down value in database.
But i am facing two problems.
1) When i select any item from drop-down, it jumps to top of my screen in url because of href="#". When i removed "#", it started the page refresh on selection item.
2) How i target my drop-down list to insert any selected value in database using php.
My code is
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Select City
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Lahore</li>
<li>Islamabad</li>
<li>karachi</li>
</ul>
</div>
javascript code
$(document).ready(function() {
$(".dropdown-menu li a").click(function(){
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});
For the point 1 :
Since you have the # in the href the page scrolls up (i.e. navigating to the link target). You can prevent this event by adding event.preventDefault() in your code.
For Point 2: Since you said if you are able to get the value to your server side php code then you can proceed further you can make use of AJAX Post method. The final code would be
$(document).ready(function() {
$(".dropdown-menu li a").click(function(e){
e.preventDefault(); //this is the line which prevents the event
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
//this is the code to post the value to server
$.post("YourPHPMethod.php",{name: $(this).text()} ,function(response){
alert("Response from server: "+response);
});
});
You have to post it to a php. I do it with ajax like this.
Look: http://www.codesheet.org/codesheet/wOHDXFju
function postContent(cv) {
$("#myDiv").html('L O A D I N G ...').show();
var url = "/post.php";
$.post(url, {id: cv} ,function(data) { //contentVar is the variable in post.php
$("#myDiv").html(data).show();
});
}

Categories