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

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());
});

Related

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

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.

Only one checkbox between two <td> at each <tr>

I have a code like this:
<tr>
<td>
<input type="checkbox" name="ordered[]" value="xxx"></input>
</td>
<td>
<input type="checkbox" name="inStock[]" value="yyy"></input>
</td>
</tr>
The code is repeated for each result in MySQL.
Also I'm using this code:
<script>
$('input[type="checkbox"]').on('change', function() {
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).siblings().prop('checked', false);
});
</script>
I need to select only one checkbox per row (per table tr). What should I change in javascript?
Thanks!
I think you need something like this
$( document ).ready(function() {
$('input[type="checkbox"]').on('change', function() {
var checkedValue = $(this).prop('checked');
// uncheck sibling checkboxes (checkboxes on the same row)
$(this).closest('tr').find('input[type="checkbox"]').each(function(){
$(this).prop('checked',false);
});
$(this).prop("checked",checkedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="checkboxes">
<tr>
<td>
<input type="checkbox" name="inStock[]" />inStock
</td>
<td>
<input type="checkbox" name="ordered[]" value="xxx" />ordered
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="inStock[]" value="yyy" />inStock
</td>
<td>
<input type="checkbox" name="ordered[]" value="xxx" />ordered
</td>
</tr>
</table>
I think what you are asking for is a RadioButton. Just give them different ids but the same name and you will be able to select just one of them.
Try applying selector based on element name:
$('input[name="ordered[]"]').on('change', function() {
Or you would probably want to add some other attribute to identify the specific element you wish to select.
Since you haven't specified which sibling, say you can grab the first element out of a jQuery object using first:
$(this).siblings().first().prop('checked', false);
You can also do
$(this).siblings(".bar").eq(0).text()
You can use the eq method to reduce the matched set of elements to one at a specific index:
If you use radio buttons and use the same name for all of them, you are only able to select one radio button at a time and the other ones gets uncheked and like our friend mentioned you need to include your <td></td> tags in <tr></tr>tags.

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.

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