I have a list of users registered to the application, for the admin there is an option to delete any user registered. I have the list being populated from the database with PHP.
So every one of the users in this list gets a tr row in this table that has all the users in it. At the right column I have a button which only the admin sees on this table of users, and he can delete that specific user by clicking on that 'delete' button.
I would like that before deleting occurs, which is working fine, there should be a pop up alerting to the admin asking "Are you sure you would like to delete "blank" from the system?" with blank having the name of the user the admin clicked the delete button by.
Now I do have the name of the user in a hidden input field attached to the delete button, in other words I am getting a name coming out in that sentence, the problem though is that the same name of the first person on the list is showing up when I click on any one of the delete buttons on the users list. So to clarify although the deleting is happening to the correct user, so it doe's delete the user I would like to delete, the name in the confirmation alert is showing always with the name of the first user.
I believe this is a problem with the way I am writing the jquery code, so any assistance with this would be greatly appreciated, I am sitting on this for a while already trying to find an answer online for this.
So to sum it up in short:
I have a couple of "forms" on the page (i.e. meaning "delete" buttons that causes a "form" with hidden input information of the user that we would like to have deleted, is sent to the back-end in order for the back-end to know which user to delete.)
The delete function is working just fine - deleting the desired user.
However the alert function is not populating the desired message to the admin, since the name of the user in the message doe's not change from user to user, and it's grabbing always the name of the first user on the users list.
Here is the code for the users list:
<table class="table table-striped table-bordered">
<thead class="dark_grey">
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>User Level</th>
<th>Actions</th>
</thead>
<tbody>
<?php
foreach ($user_rows as $row)
{
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td><a href='/ci/user/user_profile/?={$row['id']}'>{$row['first_name']} {$row['last_name']}</a></td>";
echo "<td>{$row['email']}</td>";
echo "<td>{$row['created_at_time']}". " " ."{$row['created_at_date']}</td>";
if($row['user_level'] != '9')
{
$row['user_level'] = 'normal';
echo "<td>{$row['user_level']}</td>";
}
else
{
$row['user_level'] = 'admin';
echo "<td>{$row['user_level']}</td>";
}
echo "<td class='last_td'>
<form class='float_left' action='/ci/user/edit_user' method='post'>
<input type='hidden' name='email' value='{$row['email']}'/>
<input class='btn btn-success' type='submit' value='Edit' />
</form>
**<form class='delete' action='/ci/user/delete_user' method='post'>
<input type='hidden' name='email' value='{$row['email']}'/>
<input type='hidden' name='name' value='{$row['first_name']} {$row['last_name']}' />
<input class='btn btn-danger' type='submit' value='Delete' />
</form>**
</td>";
echo "</tr>";
}
?>
</tbody>
</table>
Here is the jquery code:
<script type="text/javascript">
$(document).ready(function () {
$('.delete').submit(function () {
var name = $('input[name="name"]').val();
alert("Are you sure you would like to delete " + name + " from the system?");
return false; //I just have this here so the delete didn't take place when testing the alert function.
});
});
</script>
So I know somehow I need to have the alert on the current clicked (".delete") but when I tried using $(this) it didn't really work. Very possible I was using it wrong.
If someone can show me the right way to write the jquery to be able to get the current clicked "delete" button's hidden input name value in the message that would be great!
Thanks in advance for your help!
You need to make your selector specific like $(this).find('input[name="name"]').val().
Try:
$('.delete').submit(function(){
var name = $(this).find('input[name="name"]').val();
alert("Are you sure you would like to delete " + name + " from the system?");
return false; //I just have this here so the delete didn't take place when testing the alert function.
});
When you do $('input[name="name"]').val() it matches more than one input name=name so jquery method val() will return the value of only the first element in the collection, and hence the behavior that you are seeing.
here is a snippet from val() from jquery code
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0]; //<--- It just takes first element in the collection
if ( !arguments.length ) {
if ( elem ) {
...........
I think I just finally found an answer to my question:
Here is the jquery code that worked:
<script type="text/javascript">
$(document).ready(function(){
$('.delete').submit(function(){
var name = $(this).find('input[name="name"]').val();
alert("Are you sure you would like to delete " + name + " from the system?");
});
});
</script>
I got the answer after finding this post:
jQuery get value from hidden input in column
Thanks for your help stackoverflow! :)
Related
I have been racking my brain trying to get a very particular function to work. It seems simple but I just cant figure it out. I am looking to basically get a txt file and allow someone to type in a certain id into an input box that upon the user clicking "delete" will remove only the targeted DIV id.
I have tried wrapping a PHP file around a form with no success, as well as putting the PHP directly into the submit button but nothing has worked, can anyone point me in the correct direction?
I have looked for other post here but nothing seems to be exactly what im looking for or I am wording it incorrectly. This is essentially how I want it to look:
<form action='delete.php' method='post'>
<input name='idinput' type='text' value='Enter The Certain ID Value You Want To Remove'>
<input type='submit' name='submit' value='Remove'>
</form>
Not sure about the text file bit but to remove an element from the DOM, well, you can't do this in PHP without reloading the page and apssing in some extra data na dusing some logic to not display that element...
You need to use JavaScript... or with JS with jQuery
$(function(){
$('input[name="submit"]').on('click', function() {
var val = $('input[name="idinput"]').val();
$('#or.IDorCLASSNAME_' + val).remove(); //If Id Input val is 3 this gives #or.IDorCLASSNAME_3
});
});
jQuery: https://api.jquery.com
jQuery Remove: https://api.jquery.com/remove/
jQuery DOM Removal: https://api.jquery.com/category/manipulation/dom-removal/
Tutorial: https://www.w3schools.com/jquery/jquery_dom_remove.asp
I was able to do this by placing a form that is inserted within the txt info im submitting:
<form action='delete.php' method='post'>
<input type='hidden' name='random' id='random' value='".$random."'>
<button type='submit' value='report'></button>
</form>
And also by adding this to the delete.php page:
<?php
$random = $_POST['random'];
$original = "<div id='".$random."'>";
$replacement = "<div id='".$random."' class='hidden'>";
$str = file_get_contents('submissions.txt');
$str = str_replace("$original", "$replacement",$str);
file_put_contents('submissions.txt', $str);
header('Location: index.php');
?>
Is it possible to get the button ID? I have accumulated forms and I wanted to get the button clicked using the unique ID. The following scripts I used:
echo("<table><tr>
<td id=\"i\"><img src='presentations/uploaded_files/$name.png' alt='animal' width='50px' height='50px'/></td>
<td id=\"n\">$name</td>
<td id=\"d\">$dsc</td>
<td id=\"t\">$type</td>
<td id=\"g\">$grade</td>
<td id=\"b\">
<form enctype=\"multipart/form-data\" action=\"admin_update_animal.php\" method=\"POST\"><input type=\"submit\" value=\"Update\" name=\"update\" id=\"$name\"/></form></td>
</tr></table>");
I used the following when any of the button clicked:
if (isset($_POST['update'])) {
$f=trim($_POST['update']);
}
But I wanted to get which button clicked using its unique ID assigned.
I am very glad for a help. Thanks.
You cannot directly read the id of a control because name is passed to the server side script via any methods. You can use hidden input fields whose value can be the id of the button. This lets you know the id of the button in the server side.
This can be done as:-
<script type="text/javascript">
function createField(id)
{
var x = document.getElementById("hide");
var y = "<input type='hidden' name='iddetector' value='"+id+"'/>";
x.innerHTML = y;
return;
}
</script>
//maintain other stuffs here and now
<input type="submit" id="uniqueid" name="submit" value="submit"onClick="createField('uniqueid');return true;"/><br>
<div id="hide"></div>
You can detect the id of the button i the sever side as:-
<?php
$idButton = isset($_POST['iddetector'])?$_POST['iddetector']:NULL;
echo "The id of the button clicked is ".$idButton;
?>
What is passed via POST is the name of the control, not the id. To capture the ID you would be better off using JavaScript before submit.
The point is that you may have multiple controls in different places in the page with the same name (but different IDs) that perform the same task (like submit).
I have created a form in which I have 2 text fields and one File field. I have added Javascript on 'text' fields. If user left 'text' fields and press submit button, All Fields are RequiredFont turns red, I want to turn it red as well when user doesn't upload any Image. I have tried various ways but its not working. Kindly tell me the way of doing it.
<script type="text/javascript">
function myFunction()
{
var category_name = document.forms["insert"]["sub_category_name"].value;
//var image = document.forms["insert"]["file"].item();
var error = document.getElementById("error");
if(category_name=="" )
{
error.style.color="Red";
return false;
}
else
{
//message.innerHTML="Data Inserted!";
}
}
</script>
PHP code
<?php
echo "
<form name='insert' action='sub_categories.php' method='POST' onSubmit='return myFunction()' enctype='multipart/form-data'>
<table class='gridtable' border=2 bordercolor='#CCCCCC' cellpadding='10'>
<tr>
<th>
Sub-Category Name: </th><td> <input type='text' name='sub_category_name' ></td></tr>";
echo "
<tr>
<th>
Image1:</th><td> <input type='file' name= 'file' ></td></tr>
";
Thanks
Just get your file input by id and check if it's value is empty :
if(document.getElementById('file').value=='') {//something here }
Your best, easiest bet is to use JQuery as follows:
$("input[type='file'][name='file']").filter(function (){
return !this.value
}).length;
The reason you cannot use ':empty' is because ':empty' matches when an element does not have any descendants. Input elements cannot have descendants, thus your 'input' will always evaluate ':empty' as true.
I have this chunk of code, which is displayed on a user's journal page. They can add an entry and they have the option to delete an entry once it's on the page.
Ill show the code with some comments and then explain the problem.
// Figures out how many recent posts to display
$posts = $config_journalposts + 1;
if($noposts!=1) {
// Gets the data from the query
while(($row = mysql_fetch_array($journalquery)) && ($posts > 1)) {
// For each of the posts that were gathered, display the following:
echo '<table border="0" width="100%">
<tr>
<td colspan="2" style="vertical-align:bottom;">
// Display the title as a link to be used as a permalink
<p class="fontheader">'.$row['title'].'</p>
</td>
</tr>
<tr>
// Show the o-so-important content
<td width="100%" style="vertical-align:top;padding-left:10px;">
'.$row['content'].'
</td>
</tr>
<tr>
// Show the date
<td style="font-size:8pt;padding-top:10px;">'.$row['date_day'].'/'.$row['date_month'].'/'.$row['date_year'].'</td>';
// Checks if the current user is the owner of the journal or an admin
if($_SESSION['user']==$pageowner || $_SESSION['user_rank']=='Admin') {
echo '<td align="right">
// FOCUS POINT
<form method="POST" id="deljournal">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
// A delete button that executes a bit of Javascript
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal()" />Delete</button>
</form>
// END FOCUS POINT
</td>';
}
echo '</tr>
</table>
<hr>
';
$posts --;
}
Here is the Javascript that gets triggered on the button press
function delete_journal() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
// Submits the form
$("#deljournal").submit()
}
}
This javascript triggers the forum in the PHP code above which reloads the page and triggers this at the very top of the page, before the tag
if(($_POST['delete_id'])) {
// Gets the post ID from the hidden forum tag
$deleteid = addslashes(strip_tags($_POST['delete_id']));
// Deletes the row that has the ID of the hidden form
mysql_query("DELETE FROM `gamezoid_accounts`.`journal_$pageowner` WHERE `id`='$deleteid'");
}
Now, for the problem. In the while loop, this form gets repeated over and over. What happens is that upon pressing the delete button, it triggers the form that has the ID "deljournal". Since all of them have the ID "deljournal" it does the one at the top of the page. Trying to embed the post ID into the form ID breaks the code because the mysql_query doesn't know that the delete function has been triggered in the first place.
Any way around this?
Reason why I'm using Javascript as a trigger is for the confirmation popup in case anyone askes.
Anyways, thanks heaps for reading this far!
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
and on server side u should use
$delete_values= implode (',',$_POST['delete_id']);
Found a solution.
I have changed the form to be
<form method="POST" id="deljournal_'.$row['id'].'">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
</form>
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal_'.$row['id'].'()" />Delete</button>
by adding the journal entry ID into the ID of the form and the onClick function. The javascript is just below it outside the table cell and looks like:
<script type="text/javascript">
function delete_journal_'.$row['id'].'() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
$("#deljournal_'.$row['id'].'").submit()
}
}
</script>
where the entry ID has been added to the function name and form ID tag. By putting the Javascript into a while loop and not into an external file, it can be manipulated with the loop to have the same values.
It is a bit messy and will slightly increase load times + execution times but it was the quickest way that I could find.
Hope this helps anyone else who has been having a similar problem.
I have a html table(grid) which displays a few records for me.I want it to be editable, i.e user can edit the values and save them on pressing enter.
My table is something like this.I display records dynamically using php.
<a class="grayBucketBtn noMargin none" id="unpublish" href="#.">Unpublish</a>
<a class="grayBucketBtn" id="publish" href="#.">Publish</a>
<a class="grayBucketBtn" id="delete" href="#.">Delete</a>
<a class="grayBucketBtn" id="modify" href="#.">Modify</a>
<?php while ()//loop through ?>
<tr>
<td class="tableRadioBtn"><input type="checkbox" class="checkRowBody" id="checkRowBody" name="check"/></td>
<td class="tableShape">Round</td>
<td class="tableCarst">0.30</td>
<td class="tableColor">j</td>
<td class="tableClarity">SI1</td>
<td class="tableDimension">4.35x4.33x2.62mm</td>
<td class="tableDeptd">60.3%</td>
<td class="tableTablePer">60.3%</td>
<td class="tablePolish">Excellent</td>
<td class="tableSymmetry">Excellent</td>
<td class="tableCut">Very Good</td>
</tr>
<?php } ?>
Each row(tr) has a check box associated.If I check the check box,I get a edit button.When I click on the edit button,the selected row will turn into editable.So I want a function on the edit button,
$("#modify").click(function(){
//check if only one check box is selected.
//make it editable.
//save the content on pressing enter of the edited row.
});
I went through some questions but did not get a solution as most suggest some plugins which don't meet my requirements.So,some help would be useful.
Thanks for the time
This should cover turning them from text to inputs and back to text
$('#modify').click(function(){
$.each($(".checkRowBody:checked"),function(){
$.each($(this).parent('td').parent('tr').children('td:not(.tableRadioBtn)'),function() {
$(this).html('<input type="text" value="'+$(this).text()+'">');
});
});
});
$('input[type="text"]').live('keyup',function(event) {
if(event.keyCode == '13') {
// do $.post() here
$.each($('input[type="text"]'),function(){
$(this).parent('td').html($(this).val());
});
}
});
When using checkboxes the user assumes more than one can be selected, if you want only one each time then just use radio buttons
I can't give you a complete solution but I can give you a direction:
First change the markup like this:
<tr>
<td class="tableRadioBtn"><input type="checkbox" class="checkRowBody" id="checkRowBody" name="check"/></td>
<td class="tableShape">Round<input class="hidden" value="Round" name="shape"/></td>
<td class="tableCarst">0.30 <input class="hidden" value="0.30" name="tableCarst"/></td>
...
//Do the same for all the columns
</tr>
Define the hidden class to display:none so all the inputs are hidden.
Once the user clicks a row, you remove the text of all the td elements and remove the hidden class from all the inputs:
$(".tableRadioBtn").click(function(){
//find the parent tr, then find all td's under it, empty the text and remove hidden class
$(this).closest('tr').addClass('editable').find('td').each(function(){
$(this).text('').removeClass('hidden');
});
});
//set a keypress event to detect enter
$(document).keypress(function(){
//if enter was pressed , hide input and set text
if(e.which == 13) {
var $editable = $('.editable');
$editable.find('input').addClass('hidden');
$editable.find('td').each(function(){
//set the text back
$(this).text($(this).find('input').val());
});
//post data via ajax.
}
}
Please note that i haven't tested this code so there might be some mistakes there, but this is a possible solution.
UPDATE:
In order to detect if more than one checkbox is checked use this:
if ($(':checked').length > 1){//do something}
So you want to make your selections and then invoke an action on the checked rows?
$('#delete').click(function() {
$.each($('.checkRowBody:checked').parent('td').parent('tr'),function() {
// probably want to carry out a $.post() here to delete each row using an identifier for the rows related record.
//I suggest applying an id or other attribute to the tr element and using that to pass a value with your $.post() data.
$(this).hide();
});
});