I have a problem that make me stuck for a couple days.
I use laravel 7 and jax, and yajra datatables and i want to make page edit which show data by id from database.
before this i use popup modal to create and edit data, but for this i want to make another page for create and edit, so i would direct to another page like this
"/pegawai/edit/{{ $p->pegawai_id }}". so when i click button edit there are direct to page edit.
for page create and function delete is ok, but i stuck at edit.
this my controller to get list
public function getList(Request $request){
$data = Cms::all();
$canEdit = Auth::user()->can($this->permissions["edit"]);
$canDelete = Auth::user()->can($this->permissions["delete"]);
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row)use($canEdit,$canDelete){
$btn = '';
$canEdit ? $btn .= "<a href='/console/cms/editData'>
<button
type = 'button'
class = 'btn btn-warning btn-sm'
onclick = 'editData(this)'
idData = '".$row->id."'
title = '".$row->title."'
slug = '".$row->slug."'
meta_title = '".$row->meta_title."'
meta_desc = '".$row->meta_desc."'
description = '".$row->description."'
>Edit</button></a>":'';
$canDelete ? $btn .= '<button
type = "button"
class = "btn btn-danger btn-sm"
onclick = "deleteData(this)"
idData = "'.$row->id.'"
>Delete</button>
':"";
return $btn;
})
->rawColumns(['action'])
->make(true);
}
this function at blade
function editData(attribute){
resetError();
resetForm();
var id = $(attribute).attr('idData');
var title = $(attribute).attr('title');
var slug = $(attribute).attr('slug');
var meta_title = $(attribute).attr('meta_title');
var meta_desc = $(attribute).attr('meta_desc');
var content = $(attribute).attr('description');
tinymce.get("description").setContent(content);
var cms_file = $(attribute).attr('cms_file');
$("#id").val(id);
$("#title").val(title);
$("#slug").val(slug);
$("#meta_title").val(meta_title);
$("#meta_desc").val(meta_desc);
$('#description').val(description);
$('#cms_file').val(cms_file);
}
Use the code below:
$canEdit ? $btn .= "<a href='/pegawai/edit/".rawurlencode($row->id)."' class='btn btn-warning btn-sm'>Edit</a>";
if you are using the jquery, you need to add event delegation from the body because the element is coming from ajax. maybe use
$('body').on('click','.yourBtnClassname',function(e){
});
see this Image
Related
I want to delete an item from the Firebase real-time database by clicking the button in JavaScript. I get data from the database directly in the frontend. When I click the Delete button, the corresponding object should be removed from the database and the front end. I tried some logic functions and deleted a certain element from the database, but my HTML page did not update.
I have to refresh the page every time. How can I delete it in real-time?
Here is my complete code https://jsfiddle.net/waqasumer/x1ugL5yr/
function deleteTodo(e) {
const key = e.parentElement.parentElement.getAttribute('data-key');
firebase.database().ref('tasks').child(key).remove();
}
var main = document.getElementById("main-section");
function saveData() {
var todo = document.getElementById("todo-item");
if (todo.value === "") {
alert("Please enter task");
} else {
var key = firebase.database().ref('tasks').push().key;
var tasks = {
todo: todo.value,
key: key
}
firebase.database().ref('tasks/' + key).set(tasks);
document.getElementById("todo-item").value = "";
}
}
function getData() {
firebase.database().ref('tasks').on('child_added', function (data) {
var item = data.val().todo;
var key = data.val().key;
console.log(data.val());
var row = document.createElement("div");
row.setAttribute("class", "row");
row.setAttribute("data-key", key);
var col1 = document.createElement("div");
col1.setAttribute("class", "col text");
var task = document.createTextNode(item);
col1.appendChild(task);
row.appendChild(col1);
var col2 = document.createElement("div");
col2.setAttribute("class", "col");
var editBtn = document.createElement("button");
editBtn.setAttribute("class", "btn btn-success btn-circle btn-sm fa fa-pencil-square-o");
editBtn.setAttribute("onclick", "editTodo(this)");
col2.appendChild(editBtn);
row.appendChild(col2);
var col3 = document.createElement("div");
col3.setAttribute("class", "col");
var deleteBtn = document.createElement("button");
deleteBtn.setAttribute("class", "btn btn-primary btn-circle btn-sm btn-danger fa fa-remove");
deleteBtn.setAttribute("onclick", "deleteTodo(this)");
col3.appendChild(deleteBtn);
row.appendChild(col3);
main.appendChild(row);
})
}
getData();
function deleteAll() {
firebase.database().ref('tasks').remove();
main.innerHTML = "";
}
function deleteTodo(e) {
const key = e.parentElement.parentElement.getAttribute('data-key');
firebase.database().ref('tasks').child(key).remove();
}
Yes! As far as I saw, you have to refresh the page to get updated data. This is because you are using 'child_added' in your event listener which gets triggered only when a new child is added.
firebase.database().ref('tasks').on('child_added', function (data){})
You can just refer this and add value listeners to your function such that it retrieves data every time when the child gets changed.
https://firebase.google.com/docs/database/web/read-and-write#listen_for_value_events
EDIT
You can also delete a value using set() or update() method by passing null.
In this case, you can have a callback function. You can use this callback function to update your DOM.
<script>
function setSortMethod(param) {
var sortMethod = "#sortMethod";
var asecending = false;
var currUrl = "";
var currSort = "";
var outputUrl = "";
currSort = "sortMethod=" + param;
if ($('#filterPending')[0].checked == false {
outputUrl = (currSort);
}
window.location.href = "?" + outputUrl;
}
</script>
<button type="button" class="btn btn-link" id="action" onclick="setSortMethod('StartDate')" value="LeaveDate">
Leave Date
</button>
So I am trying to get this link button working to toggle between ascending and descending sorting order.
../Index?sortMethod=StartDate which sort the display data by
ascending order
../Index?sortMethod=StartDate_desc will sort the display data by
descending order
I have tried using a boolean variable toggle true/false but to no avail.
Backend c# code I already have the ViewBag with ternary
ViewBag.StartDate = sortMethod == "StartDate" ? "StartDate_desc" : "StartDate";
With switch case it will work if you manually key in the url.
But because right now I am reworking on the link button I changed from actionlink to bootstrap's button link, so I have to find some ways to get the "StartDate" parameter for this onclick="setSortMethod('StartDate') passed into setSortMethod function and try to toggle between StartDate or StartDate_desc.
Trying out razor syntax with ViewBag,
#{
string sortMethod = ViewBag.StartDate;
}
but I am not sure what can I do with this.
Try this One.
<button type="button" class="btn btn-link" id="action" onclick="setSortMethod('StartDate')" value="LeaveDate">
Leave Date
</button>
<script>
function setSortMethod(param) {
var sortMethod = "";
var asecending = false;
var currUrl = "";
var currSort = "";
var outputUrl = "";
currSort = "sortMethod=" + param;
window.location.href += "?" + currSort
}
</script>
I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.
HTML BUTTON
<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>
JS FUNCTION(W/ JQUERY)
function whoIsRdns(thisButton){
//Enable jQuery properties from the param of the HTML object
var btn = $(thisButton);
var test = btn.data('hi');
console.log('Value is ' + test);
}
Why would test return as null?
Shouldn't var btn = $("thisButton"); be var btn = $(thisButton); (without quotes)
Just a typo
$("thisButton") !== $(thisButton);
drop the quotes so you are not looking for an element with a tag name thisButton
var btn = $("thisButton");
needs to be
var btn = $(thisButton);
I need to pull, break down into an integer, and store in jQuery the second from last element with the class ".admin-product".
The id will be something like "admin-42" and I need that stored as the number 42.
The stored variable is sent through my AJAX handler and will be manipulated and put to use from there.
Here's my current code:
$(document).on('click', '.create-btn', function() {
var data = {'id':$('.admin-product:last').attr('id'),
'username':$('#ausername').val(),
'email':$('#aemail').val(),
'password':$('#apassword').val()};
ShowCreateLoadingScreen("Creating...");
AjaxHandler('library/ajax/ajax.admin-account-create.php', data, 'POST', true);
});
Any ideas?
EDIT:
Preferrably in this format, ish:
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
EDIT:
The following code stores the number as 2.
{'id':$('.admin-product:nth-child(-n+2)').attr('id').split("-")[1]
EDIT:
My mark-up is generated through a parser, the code it is here, basically rewrites the same line for as many times as there is still information in my database.
if($stmt->num_rows > 0) {
$stmt->bind_result($aId, $aUsername, $aPassword, $aEmail);
while($stmt->fetch()) {
$html .= file_get_contents(ROOT_LIB . 'html/admin-accounts/row-user.html');
$rowNumber = $aId;
$replace = array(
'userHere' => $aUsername,
'emailHere' => $aEmail,
'passHere' => ' ',
'IdHere' => $aId,
'buttonDisplay' =>
'<button type="button" data-id="'.$aId.'" name="edit" class="btn btn-info edit-product span6" title="Edit Account" value="Edit">Edit</button>
<button type="button" data-id="'.$aId.'" name="delete" class="btn delete-btn btn-danger span6" title="Delete Account" value="Delete">Delete</button>'
);
$parser = new Parser($replace);
$parser->ParseHtml($html);
}
It sounds like what you're interested in is the ID number of some DOM elements; in this case, the "ID number" is the suffix of the HTML ID of the element. So what I would do is construct a list of said ID numbers:
var idNums = $('.admin-product').toArray()
.map(function(domElt){
return Number(domElt.id.split('-')[1]);
});
Note that if there are any elements with class admin-product that don't have a properly formatted ID, it will result in an element with a value of NaN; you can use Array.prototype.filter to get rid of those if you wish.
Then its easy to get the penultimate (second-to-last) ID (with a safety in case there's only one element):
var penultimateIdNum = idNums.length>1 ? idNums[idNums.length-2] : null;
Demonstration: http://jsfiddle.net/3SvxB/
this is a very basic ancient way:
var elements = $('.admin-product');
var len= elements.length;
var element = elements[len-2];
var data= $(element).attr('id');
var id= data.split('-')[1];
You can simply do
var id = $('.admin-product:nth-last-child(2)').attr('id').split('-')[1];
update: fiddle
Give this a try:
var ele = $(".admin-product").length;
var id = $(".admin-product:eq(" + (ele - 3) + ")").attr('id').split('-')[1];
Let me know if it doesn't work.
I want to select the hidden box with jquery.
What i did.
In a web page number of forms exists. I want to select the individual form and its in b/w hidden box with jquery. my Javascript code is:
function replace_val(clickval)
{
var id = $(clickval).attr('id');
var valuer = $(clickval).attr('value');
var formid = $("statictext"+id).val();
$('input[type=hidden][name="packagesale"]').val(valuer);
$('input[type=hidden][name="pre_post"]').val('Postpaid');
alert(formid >'input[type=hidden][name="packagesale"]').val());
}
My HTML Code where this function call.
<input style="width:85px;" class="btn btn-danger" onClick="replace_val(this);" type="button" id="<?php echo $sno;?>" value="<?php echo $value;"/>
I think something is wrong in my alert box code....
Your selector is wrong inside the alert(). You should use:
function replace_val(clickval)
{
var id = $(clickval).attr('id'),
valuer = $(clickval).attr('value'),
formid = $("#statictext"+id);
$('input[type=hidden][name="packagesale"]').val(valuer);
$('input[type=hidden][name="pre_post"]').val('Postpaid');
alert(formid.children('input[type="hidden"][name="packagesale"]').val());
}
you also have error on line
var formid = $("statictext"+id).val();
will be
var formid = $("#statictext"+id).val();
//or
var formid = $(".statictext"+id).val();// if using class
Don't over use jQuery if possible try in pure javascript only
var id = clickval.id;
var valuer = clickval.value;