How to get value from r.fn.init (JQuery selector context) - javascript

Hi I try to receive a value from span from table like this:
function getValueFromSibling(this) {
var id = $(this).parent().siblings('span.childSibbling');
}
Table looks like this:
<tr>
<td>
<button type="button" onClick="getValueFromSibling()"></button>
</td>
<td>
<span class="childSibbling">100</span>
</td>
</tr>
But I receive something like this:
id = r.fn.init [prevObject: r.fn.init(1)]
I found that is simple form of:
var jQuery = function( selector, context ){
return new jQuery.fn.init( selector, context );
};
So there is the question. How to receive InnerHTML from <span>, or how to convert r.fn.init [prevObject: r.fn.init(1)] to value?
var result = id.val(); and var result = id.get(); dosen't work

First of all, this inside your function getValueFromSibling is in window scope pass this context when calling the function
onClick="getValueFromSibling(this)"
And there are few things missing like text() to get the text you want. Try one below
Better way (actually recommended way):
Html
<tr>
<td>
<button type="button" class="some-button"></button>
</td>
<td>
<span class="sibbling">100</span>
</td>
</tr>
Jquery
$(function(){
$('.some-button').click(function(){
var id = $(this).closest('tr').find('.sibbling').text();
// .closest() gets the closest tr parent .
// .find() finds the element with class 'sibbling' inside that `tr`
// .text() gets the text inside the element.
});
});

You should be able to get the text value by using
$("selector").text();

The problem you are facing is that you don't want a sibling, you want a child of a sibling.
function getValueFromSibling(me) {
var id = $(me).parent().next().find('span.childSibbling').text();
console.log(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table>
<tr>
<td>
<button type="button" onClick="getValueFromSibling(this)"></button>
</td>
<td>
<span class="childSibbling">100</span>
</td>
</tr>
</table>
</body>
With this, first we do a .parent() to move us on the td element. Then, we move on the next td element with .next() and finally, recover the span.childSibbling with find('span.childSibbling').
Using the method .text() for recover the innerText of the node or .html() for the innerHTML of the node.
For the r.fn.init question, there is an excelent answer in this question.

Related

JavaScript returns undefined for parent and children element

I am trying to select the parent element of a clicked button, and find the child elements text of that parent element however it is returning undefined.
var add = document.getElementById("add").parentElement.nodeName;
I found how we can access the parent element's node name, but I can't select it's child element by id.
Currently I am trying to get attributes for selected elements and user alert() to display them, however it's not working as expected. The code below is what I currently have:
window.onload = function(){
add();
}
function add() {
var add = document.querySelector(".add").parentNode;
var id = document.querySelector(".id").innerHTML;
var name = document.querySelector(".std").innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td class='id'>1</td><td class='std'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td class='id'>2</td><td class='std'>Sonam</td><td class='add'>ADD</td>
</tr>
</table>
</body>
</html>
There are two issues here:
you should use document.querySelector() when selecting a single element, rather than document.querySelectorAll() which is used to select multiple elements
the innerHTML field should be used instead of innerHtml
Note that document.querySelector() returns the first selected element (if any), where as document.querySelectorAll() returns a NodeList containing selected elements.
Here's a working snippet:
window.onload = function(){
add();
}
function add() {
var add = document.getElementById("add").parentNode;
/* Use querySelector for single element, and use innerHTML */
var id = document.querySelector("#id").innerHTML;
var name = document.querySelector("#std").innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td id='sn'>1</td><td id='name'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td id='id'>2</td><td id='std'>Sonam</td><td id='add'>ADD</td>
</tr>
</table>
</body>
</html>
Hope that helps
id attribute value must be unique across your HTML. So if you want to have multiple elements with the same identifier use class, also you need to know the index of the element you are targeting.
visit this link for more info about id attribute
You have a typo, the correct attribute is innerHTML not innerHtml and as mentioned before you need to know the index of the element
window.onload = function(){
add();
}
function add() {
var add = document.getElementById("add").parentNode;
var id = document.querySelectorAll("#id")[0].innerHTML;
var name = document.querySelectorAll("#std")[0].innerHTML;
alert(id);
alert(name);
}
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>S.N.</th><th>Name</th><th>Action</th>
</tr>
<tr>
<td id='sn'>1</td><td id='name'>Riya</td><td id='del'>DEL</td>
</tr>
<tr>
<td id='id'>2</td><td id='std'>Sonam</td><td id='add'>ADD</td>
</tr>
</table>
</body>
</html>

How to extract value from table with mixture of html elements

I have a table which contains a combination of plain text, input textboxes, selects, and spans. I need to iterate through the table row by row and pull out the value in each cell. Within my table all <tr> have a particular css class.
$(".gridBody").each(function(rowindex){
$(this).find("td").each(function(cellIndex){
var cell = $(this).first()
})
In my debugger I can see what kind of object is being returned by $(this).first() but I can't find out how to get into its attributes. I have tried using jqueries html parser to turn it back into a dom element, but instead of getting, for example, a textbox, I get something like [[html inputtextbox]]. Most of the methods that work on regular dom elements are not working for me.
If I use $(this)[0].innerText it returns the correct value when the contents of the cell are plain text, but not when they are a form of input or nested in a span element. What I would really like to be able to do is get a regular html dom element back that I can then check the type of with $.is() and then vary much logic from there.
How do I get the first child element in a table cell as an html dom element that I can manipulate with jquery like any other dom element?
var collected = $("#myTable td").find("input, textarea, span").map(function(){
return this.value || this.textContent;
}).get();
console.log( collected ); // an array holding values or text
http://jsbin.com/zewixe/2/edit?html,css,js,console,output
If you want only the immediate children than use the right > selector
(">input, >textarea, >span")
Heres how I would do it:
<table>
<tr>
<td>
<h1>Some stuff.</h1>
</td>
</tr>
<tr>
<td>
<input type="text" value="1"/>
</td>
<td>
<input type="text" value="2"/>
</td>
</tr>
<tr>
<td>
<input type="text" value="3"/>
</td>
</tr>
<tr>
<td>
<input type="text" value="4"/>
</td>
</tr>
</table>
$(function() {
function getFormData(selector){
'use strict';
var formTypes = {
text: 'text',
radio: 'radio',
select: 'select'
},
values = [];
$(selector).children().each(function(idx, childNode) {
if (childNode.getAttribute('type') && formTypes[childNode.getAttribute('type')]) values.push(childNode.value);
});
return values;
}
alert(
getFormData('table tr td.someClass')
);
})();
http://codepen.io/nicholasabrams/pen/RaKGjZ

jquery click event for buttons having same id

I am having a table structure like this
<table>
<c forEach var="item" items="${manyItems}">
<tr>
<td id="item1"> ${item.data1} </td>
<td id="item2"> ${item.data2} </td>
<td> <button id="deleteButton"/> </td>
</tr>
</c:forEach>
</table>
Now I want to add a click event to the deleteButton
In my jquery is like this:
$(function() {
$('#deleteButton').click(function() {
var ele = $(this).parent();
/* fetch the other <td> siblings of the #deleteButton */
/* delete code goes here having an ajax query*/
});
});
This code is only deleting the 1st row of the table, but does not work on any other row.
I believe this is because we need to have distinct id's?
Kindly guide me to a good solution.
You are creating duplicate IDs, Identifiers in HTML must be unique and this is the expected behavior.
Use class, Here In example below I have converted deleteButton in to a CSS class so that we can use Class Selector (".class")
<button class="deleteButton"/>
Script
$('.deleteButton').click(function() {
var ele = $(this).parent();
});
Issue is the same ids for multiple elements in a single page. When this happens browser only looks for first instance of it and never goes ahead to look for another one, This is the reason one should understand that IDs should be unique per element.
change to class name instead:
<table>
<c forEach var="item" items="${manyItems}">
<tr>
<td class="item1"> ${item.data1} </td>
<td class="item2"> ${item.data2} </td>
<td> <button class="deleteButton"/> </td>
</tr>
</c:forEach>
</table>
and jquery:
$(function() {
$('.deleteButton').click(function() {
var ele = $(this).parent();
/* fetch the other <td> siblings of the .deleteButton */
/* delete code goes here having an ajax query*/
});
});
First think that, id is known unique, if u need to have click event for two button, u can use class for selecting the button, so try to follow the standards, id is unique selector and class is multiple selector.

How do I get an elements sibling in JQuery, in a function?

I am trying to set an element to have the same value as its sibling in JQuery.
I have a table with a number of fields in, and when I click an Edit button I want to copy the value of a label to it's neighbouring input field:
<table style="width:90%">
<tr>
<td>Start</td>
<td>
<span ID="lblSprintStart" class="staticField">01/01/2001</span>
<input class="editableField" id="sprintStart" />
</td>
</tr>
<tr>
<td>End</td>
<td>
<span ID="lblSprintEnd" class="staticField">02/02/2002</span>
<input class="editableField" id="sprintEnd" />
</td>
</tr>
</table>
<button id="editButton">Edit</button>
I can do it by targeting each individual element by ID:
$(function () {
$("#editButton")
.click(function (event) {
event.preventDefault();
editMode();
});
});
function editMode() {
$("#sprintStart").val($("#sprintStart").siblings(".staticField").html());
}
But I want to do it by class so all fields are updated. If I change the function to use the $(this) selector and do it by class it doesn't work:
function editMode() {
$(".editableField").val($(this).siblings(".staticField").html());
}
http://jsfiddle.net/QQLvX/1/
You can use .val( function(index, value) )
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
Code
$(".editableField").val(function(){
return $(this).siblings(".staticField").html();
});
DEMO
Use .each()
$('.editableField').each(function(){
$(this).val($(this).siblings(".staticField").html());
});

Loop through all checkboxes that are inside a div tag

I need to loop through all checkboxes that are inside a div tag with id #abc123
How can I do this?
$("#abc123").foreach( ???? )
Update
my html row looks like:
<tr>
<td><input .../> </td>
<td>234</td>
</tr>
I need to add the value of the <td> into the ID of the checkbox.
Would I just get the parent, then ancestor it somehow?
$("#abc123 input[type=checkbox]").each(function()
{
});
UPDATE:
Ok, Let'd see if I got this straight. Given:
<tr>
<td><input .../> </td>
<td>234</td>
</tr>
You want the result to be (effectively)
<tr>
<td><input id="abc234" .../> </td>
<td>234</td>
</tr>
$("td input[type=checkbox]").each(function()
{
var id = $(this).next("td").text();
$(this).attr("id", "abc"+ id);
});
$("#abc123 input[type=checkbox]").each(function() {
$(this).dosomething();
});
Use a onkeydown event... I recommend the tab key which is keycode "9"
$(document).keydown(function(e){
if(event.keyCode == '9'){
...
}
Inside the if statement you'll need a nested if statement that checks which element is in focus and then assigns focus to the next element like this :
document.div.id.focus();
You didn't label where #abc123 is in your code. Also, do the <td> tags have any identification? The following may work.
$("#abc123 input:checkbox").each(function(i) {
id = $(this).closest('td').next('td').text();
$(this).attr('id', id);
});
I am not sure how deep your <div id="abc123"> is in the <td> so I used the closest() method to get to the cell wrapper. If it is only 1 deep, i.e. there is no <div> as it appears in your code, then you can just use parent(). Good luck.

Categories

Resources