How to get the dynamic id by its name - javascript

I am having a table with so many rows which is also having a button in each row , so I put its Id dynamically like id=#gunDetails.SerialNo(for each row its different) and its name I gave as name="popoverselect" So now I want to get this dynamic Id . How can i get it I need the Id in my popup which will open when I click on that button.
I have tried `
var getVal = $('[name="popoverselect"]').attr(id);
but its not working, any help will be appreciated.
Edit
<td class="text-center">
<div class="btn-group">
<i class="fa fa-pencil"></i>
</div>
</td>
This is my button which will show the popover so when I am trying
var getVal = $('[name="popoverselect"]').attr("id");
I am only getting the id of my first row
`

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<button id="1593" onclick="alert($(this).attr('id'))">Button 1</button>
</td>
</tr>
<tr>
<td>
<button id="1678" onclick="alert($(this).attr('id'))">Button 2</button>
</td>
</tr>
</table>

You can select element by name like this
$("[name='popoverselect']");//select all elements with name equal to 'popoverselect'
$("[name*='popoverselect']");//select all elements with name contains 'popoverselect'
$("[name^='popoverselect']");//select all elements with name start with 'popoverselect'
And to get id use $("[name='popoverselect']").attr("id");
so for your example .attr(id) JQuery will look to id as variable witch not defined
var id = "id";
$("[name='popoverselect']").attr(id);//this will work

Related

Why i am not able to fetch table data in AJAX ? Everytime i fetch req_id from table it's gives me undefined value in Console.log

I want to take req_id but everytime i fetch req_id from table it's gives me undefined in Console.log().Please see in table data req_id and yes the databse connection is okay i can see the value.I tried this both GET and POST method but still i get the same error.All i want is fetch req_id and show it in console.log as defined value
Thank You
<!-- main -->
<section class="pad-70">
<div class="container">
<p id="demo"></p>
<?php
$userQuery = $connection->Show($conobj, "requested_car");
if ($userQuery->num_rows > 0) {
echo "<table><tr><th>Req ID</th><th>Action</th></tr>";
// output data of each row
while ($row = $userQuery->fetch_assoc()) {
echo "<tr ><td id=req_id>";
echo (htmlentities($row['req_id']));
echo ("</td><td>");
echo ('<button onclick="confirmcar()" class="btn btn-lg btn-success">Confirm</button> <button onclick="MyAjaxFunc()" class="btn btn-lg btn-danger">Cancel</button>');
echo ("</td></tr>\n");
}
echo "</table>";
} else {
echo "0 results";
}
$connection->CloseCon($conobj);
?>
</div>
</section>
<!-- main -->
<script>
function confirmcar() {
var req_id = document.getElementById("req_id").value;
console.log(req_id);
}
</script>
So, going from your last edit, I removed the PHP and tried to simulate the HTML that would be generated with several rows.
Now several points remained:
You have missing quotes around your attribute value req_id, as in id="req_id". (Not a real issue as #Quentin pointed out on another answer, but let's keep things tidy for the sake of our eyes)
You're setting event handlers using on... html attributes, which is bad practice. Doing it with js addEventListener will help a lot solving your problem as you'll see below.
One of your problems is that you don't set a different id at each row for your <td>. If your ids are repeated, it probably means you should use a class instead. And setting different ids could have eased the process of selecting the right one on click. But it's not fatal so we'll go from here.
The code snippet below illustrates how you should proceed to get the value which is the inner text of the <td> with id "req_id" on the table row where the "Confirm" button was clicked:
Add an event listener for each of these buttons, and when a button's clicked:
climb up the DOM until you hit its parent <tr>
within this row, find the <td id="req_id"> by its id
read its innerText property
//When the DOM is fully loaded
window.addEventListener('DOMContentLoaded', _e => {
//Find all buttons with class btn-success
const buts = document.querySelectorAll('.btn-success');
//Add a click handler to each one
buts.forEach(button => {
//When the button's clicked
button.addEventListener('click', e => {
//Find parent <tr>
const tr = button.closest('tr');
//Find child with id req_id and get its text
const val = tr.querySelector('#req_id').innerText;
console.log(val);
});
});
});
<section class="pad-70">
<div class="container">
<p id="demo"></p>
<table>
<tr>
<th>Req ID</th><th>Action</th>
</tr>
<tr>
<td id="req_id">My Value 1</td>
<td>
<button class="btn btn-lg btn-success">Confirm</button>
<button class="btn btn-lg btn-danger">Cancel</button>
</td>
</tr>
<tr>
<td id="req_id">My Value 2</td>
<td>
<button class="btn btn-lg btn-success">Confirm</button>
<button class="btn btn-lg btn-danger">Cancel</button>
</td>
</tr>
<tr><td colspan="100">...</td></tr>
</table>
</div>
</section>
I'm using event window.DOMContentLoaded in order for my script to fire only after the DOM has been fully parsed from HTML. Else the buttons would not exist yet when trying to assign event handlers to them.

Replace ID for all tag after cloning node by javascript

I need to change all ID after cloning node below by javascript or jquery.
<table id="1">
<tr>
<td id="RM_1"><button type="button" onclick="duplicateFunction(1)"></td>
<td id="CL_1"><input id="[1][999]"/></td>
</tr>
</table>
when I clone node with ID = "1" I need to change 1 to 2 as in all ID tags below.
<table id="2">
<tr>
<td id="RM_2"><button type="button" onclick="duplicateFunction(2)"></td>
<td id="CL_2"><input id="[2][999]"/></td>
</tr>
</table>
Remark : The table id is unique id. I use simple number to explain the code.
update
When user click duplicate button. The duplicateFunction will be called.
now , I can change table id but I can't change inside.
function duplicateFunction(table_id){
var myTable = document.getElementById(table_id);
myClone = myTable.cloneNode(true);
var newTableID = Date.now();
myClone.id = newTableID;
document.getElementById("AddingSpace").appendChild(myClone);
}
because every tags have another features to do when user click.
that's the best way on this time.
Thank you in advance
This is an attempt along the lines suggested by Rory McCrossan. Instead of the individual ids of your elements inside the table I used shortened class names. The tables do not have actual ids but dataset attributes with id properties. This way it will not cause serious problems if ids should become double ...
My function calculates a newid on the basis of the number of already existing tables in the #addingspace div. This is not production ready either but probably less problematic than your original approach.
const $trg=$('#addingspace');
$(document).on('click','.RM button',function(){
let newid=$trg.find('table').length+2;
$trg.append(
$(this).closest('table').clone().data('id',newid) // set data-id
.find('.CL span').text(newid).end() // set span and return cloned element
)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table data-id="1">
<tr>
<td class="RM"><button type="button">duplicate</button></td>
<td class="CL"><input /> id: <span>1</span></td>
</tr>
</table>
<div id="addingspace"></div>

javascript: How to get each record id on data-id from foreach?

I have a category list table which gets records from foreach. Every row has delete button and this button has data-id gets id from the row. I also have a function which gets data-id. But there is a problem, I always get first record id.
like this
Source
Global.js:
function DeleteCategory() {
var Id = $("#Cid").attr("data-id");
alert(Id);
}
Index.cshtml:
<tbody>
#foreach (var item in Model)
{
<tr>
<td><span class="label label-success">#item.Id</span></td>
<td>#item.CategoryName</td>
<td>
#if (item.IsActive)
{
<b class="label label-success">Active</b>
}
else
{
<b class="label label-danger">Passive</b>
}
</td>
<td>Server updates and maintenance</td>
<td>Admin</td>
<td>
<button class="btn btn-default btn-sm" id="editId" onclick="" data-id="">Edit</button>
#*#Html.ActionLink("Delete","Delete", new {id=item.Id },new { onclick = "return confirm('Do you want to delete this row?')"})*#
<button class="btn btn-default btn-sm" id="Cid" onclick="DeleteCategory()" data-id="#item.Id">Delete</button>
</td>
</tr>
}
id attribute of an element must be unique on page. This means that 2 or more elements with same id are not allowed. Only first element with this id will be considered as a real element. You can use classes instead.
But in your case it is easier to pass itemId directly to your DeleteCategory function:
<button class="btn btn-default btn-sm" id="Cid" onclick="DeleteCategory(#item.Id)">Delete</button>
And modify it as:
function DeleteCategory(Id) {
alert(Id);
}
I agreed with above comment, the html attribute id is the culprit id="Cid" On any html page all the id should be unique. when you write $("#Cid") its search in DOM tree and always return first element found with this id. You have to generate dynamic id based on item.Id or you can pass the values as parameter in DeleteCategory() function. Hope It'll help.

JQuery table rows edit

I want to allow the user to click on the link (fa fa-pencil - acts as an edit row link) which is available at the end of each row, (and the rows are entered by the user, therefore have only written HTML code for the headings). When the user clicks on this only that particular row should be made editable to the user
and then clicking enter on the keyboard should change it back to non editable again. I am unsure how to write the JavaScript for this, my HTML is below
<div class = "Data">
<div class ="searchBar">
<input type = "search" name = "search" id = "search">
<i class = "fa fa-search"></i>
<button id = "delete">Delete Selected</button>
</div>
<table style ="width:95%" class = "Info">
<thead>
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date of Birth</th>
<th><i class = "fa fa-pencil"></i></th>
</tr>
</thead>
</table>
</div>
Please help, would be highly appreciated.
You should find out more about html attribute contenteditable=true. So you can do like that: $('your_th').attr('contenteditable','true');
Find out more about it here: http://www.w3schools.com/tags/att_global_contenteditable.asp

How to get a value of the closest td with class on button click?

I have table rows with data and buttons. http://codepen.io/leongaban/pen/nuIkd
Each button corresponds to each row, also when you click a button it changes class names from hide to un_hide the next step is to retrieve the text value of the td with class contact_name in the row that the clicked button belongs too.
Table structure:
<tr>
<td class="contact_name" style="padding: 7px 0;">
Name 1
</td>
<td>
<button class="btn_hide">Hide</button>
</td>
</tr>
<tr>
<td class="contact_name" style="padding: 7px 0;">
Name 2
</td>
<td>
<button class="btn_hide">Hide</button>
</td>
</tr>
Using this jQuery, it will get ALL text values of .contact_name in all the rows
var name = $('.contact_name').text();
So I tried this to get the text value of the 'closest' .contact_name td
var name = $(this).closest('.contact_name').text();
However that returns blank for me :(
How would you get the Name 1 value by clicking the first Hide button?
.contact_name is not parent from the clicked button.
var name = $(this).closest('tr').find('.contact_name').text();
Try,
var name = $(this).closest('td').prev('.contact_name').text();
Or
var name = $(this).closest('tr').find('.contact_name').text();
DEMO
var name = $(this).closest('tr').children('.contact_name').text();

Categories