jQuery - Find the next element which has a specific child - javascript

Lets say I have something like this:
<tr>
<td><input type="text" /></td>
<td>Somevalue</td>
<td><intput type="text /></td>
</tr>
I am in the event handler for a keypress in the first text box. I want to find the next td which has a text box in it if it exists using jQuery.

Something like this should work (assuming this is the input).
var next = $(this).parent().next("td > input[type='text']");

tj111's answer does not work for me.
May be that is because of newer version of jQuery. I came up with this:
var next = $(this).parent().nextAll().has("input[type='text']").first();

I don't know what is your selector, but if you need to select all inputs (type text). You can try this.
$(function(){
$(':input').each(function(){
$(this).keypress(function(){
$(this).next('input[type=text]').val('I\'m the next');
}) // end of keypress
}) // enf of each
}) // End of function
So, do not matter where you put more inputs, you can always take them.

Related

How can I select the Nth PreviousSibling in Javascript?

In Google Tag Manager it's quite easy to use the element, element classes, element parent classes to fire tags. Unfortunately in this case I want to scrape an element which is only available in the same .
So, when people click on the link "delete" (class=deleteItem) I want to scrape the url_product_id (in bold).
I've tried so much but can't figure out how to achieve this. I hope somebody can help me out.
<td align="center">
<span class="selquantity menosdis"></span>
<span class="selquantity plus"></span>
<input class="urlProductId" type="hidden" name="url_product_id" value="113293">
<input class="urlQuantity" type="text" name="url_quantity" value="1" readonly="readonly">
<br>
<a style="cursor: pointer" class="deleteItem">delete</a>
</td>
Assuming you are wanting to accomplish this within an event handler, you could use parentNode and querySelector to accomplish your goal:
var myClickHandler = function(event) {
var productId = event.target.parentNode.querySelector('. urlProductId').value;
// do stuff with productId
}
Or with jQuery:
$('.deleteItem').on('click', function() {
var productId = $(this).prev('.urlProductId').val();
});
This is similar to Rob's answer, but also takes into account if code is moved around into additional divs, etc.. Since people update their UI all the time. This should be more sustainable as the product matures. Of course you'll want to watch the .closest() call if you ever change to something like BootStrap data tables.
$(".deleteItem").on("click", function() {
var getClosestProdID = $(event.target).closest('td').find('.urlProductId');
// Just for display of the value
alert("Our closest selected value is: " + getClosestProdID.val());
});
JS Fiddle
Here is a jQuery method (modify and test on your own), and you could do this in a GTM Custom Javascript variable:
function(){
var ce = {{Click Element}}; // get the clicked element
if ($(ce).length > 0){
return $(ce).closest('td').find('.urlProductId').attr('name');
}
return undefined;
}
The premise here being that your elements are all nested under the <td> element, and all you're doing is taking the clicked element and scraping for the element you're interested in.

Get td value from specific tr (with mouse hover)

My problem is js sortable table that I also using mouse hover for it.
The problem is when I resort my table the hover url is not updating and I looking for how I can get for specific tr I selected the value of first td.
I tried with different variations such as:
$this.find('td:eq(0)')
or with
getElementById("trselect")
nothing works.
I use it with both mouse hover and probably looking for something like:
document.location.href = "details/" + $('tr').find('td:first-child').text();
Pure JavaScript Solution
There are a bunch of jQuery answers but no jQuery tag so I'm offering a pure JavaScript solution for you. Installing a large library for this simple task seems pointless.
You can assign the row to a Javascript variable like this, and look for mouseover.
To get the first TD's content, you can use a function like this:
function getFirstTdContent(row) {
elem = row.children[0];
alert(elem.textContent); // Do whatever you want to do with the content here
}
To call it, declare your row like this:
<tr onmouseover='getFirstTdContent(this);'>
<td>This should be returned</td>
<td>This should not be returned</td>
</tr>
Try something like this with jQuery:
Add jQuery library:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
Add jQuery code to get value of first TD:
<script>
$(document).ready(function(){
$('tr').mouseover(function(){
var valueOfTd = $(this).find('td:first-child').text();
alert(valueOfTd); // Do here what you want with the value.
document.location.href = 'http://www.google.com/'+ valueOfTd;
});
});
</script>
Looks like you're using jQuery...
Try this:
http://jsfiddle.net/cF63Q/
$(function(){
$('#myTable tr').hover(function(){
console.log($(this).find('td').first().html());
});
});

Change input/textarea stylesheet on element focus (click) using javascript / jquery

This is what I try to do, and I know this will take many hours to get the good looking UI.
$("input[type=text],textarea").bind("focus", function()![enter image description here][1] {
var $th = $(this).before("<div class='css-editor'><select class='font-family-select'> <option></option></select><select class='font-style-select'><option>italic</option></select><select class='font-size-select'></select></div>");
}).bind("blur", function() {
$('.css-editor').remove();
});
Above code is just a prototype. Redactor air mode http://imperavi.com/redactor/examples/air/ is the closest thing I can find on the net.
I wonder if there are currently any jQuery plugins or Javascript to do this?
<table style="width:100%" class="remark" cellspacing="0" cellpadding="0">
<tr class="invoice-cell-section">
<th colspan="6" class="invoice-cell-top">
**<input type="text" value="{_ Remark}"/>**
</th>
</tr>
<tr>
<td colspan="6" class="invoice-footer invoice-cell-bottom">
**<textarea class="invoice-remark static"></textarea>**
</td>
</tr>
</table>
You see input box with value Remark and empty Textarea up here.. I want when people click on it.. there is a stylesheet editor to edit only that textarea/input element...
For anyone just reading this question.. I know there is several way to add/enable this .css-editor to the DOM.... I see right to it now how to implement it if I need to code myself.. + better UI than select dropdown + hours of debugging... It like a small version of TinyMCE or CLEditor that works for single HTML element not the whole HTML in textarea.
I just want to know if there are any plugin/snippet that I can instantly use..
why not just:
$(document).on('focus', 'input[type=text],textarea', function(){
$(this).addClass('focused');
});
$(document).on('blur', 'input[type=text],textarea', function(){
$(this).removeClass('focused');
});
define a css class called focused and apply the style there.
hope that helps.
EDIT:
after better understanding of what you need, think about something like this.
create an invisible, floating (absolute positioned) panel- it will be the "css editor".
now, on every focus on an input, get to know it's location on document, and display the invisible floating css editor relatively. look at this idea:
$(document).on('focus', 'input[type=text],textarea', function(){
$('.css-editor').css({left: $(this).offset().left+'px', top: $(this).offset().top+'px'}).show();
});
$(document).on('blur', 'input[type=text],textarea', function(){
$('.css-editor').hide();
});
note that there's no need to remove and re-create this hidden element. you can create it once on DOM and manipulate it's position & visibility.
hope it's better :-)
No need to bind focus event on the textbox, it itself have the focus,focusin and focusout events attached in it. So you can simply use either .onfocus or you can also use .live function.
Using onfocus handler directly:
$("input[type=text],textarea").focus(function() {
var $th = $(this).before("<div class='css-editor'><select class='font-family-select'> <option></option></select><select class='font-style-select'><option>italic</option></select><select class='font-size-select'></select></div>");
});
Using Live event handler:
$("input[type=text],textarea").live("focus",function() {
var $th = $(this).before("<div class='css-editor'><select class='font-family-select'> <option></option></select><select class='font-style-select'><option>italic</option></select><select class='font-size-select'></select></div>");
});
You need to add function() {}
$("input[type=text],textarea").click(function(){
$(this).removeClass("your_old_class").addClass("your_new_class")
});

jquery to dynamically add table row with value upon entering text input using enter key

Okay .. this is my first question here. Very new with javascript, so hopefully I'd be treated nicely (crossing fingers) ... I have a html code down here:
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<br />
Enter Name:
<input type="text" name="name" id="name" />
I'm trying to have whatever value I enter in the input "name" to go directly as a new row in the html table attached with a running number (1,2,3,etc) in the "No." column using the "Enter" key instead of clicking on buttons. At the same time the value in "name" will be cleared and focused as to ready for the next value entrance.
Jeebison,
Being new to javascript I'm going to phrase this more as a tutorial than the exact answer.
First things first- What are the steps that need to occur to make this happen?
get the value of the input
detect the "enter" key press
insert a new row
set the row to the value of the input
Ok, now we've dissected each the problem into lots of small tasks. This makes it much easier to look for answers on each of the subsections of the problem?
Next- Do you know about javascript frameworks?
When writing javascript many browsers handle parts of the standard differently or certain parts aren't supported at all. As a result, writing javascript entirely by hand is not only cumbersome, but difficult to write cross-browser. Frameworks make development a lot easier and cleaner because they are built to handle the same functions across all browsers.
http://jquery.com -is my favorite and very easy to use so I will give you examples using that.
Ok, onto the coding.
First thing, we need to link the framework to the html page. If it's a small site or you're playing around I like to have google host the jQuery for me. Normally you might just download it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
To actually add code and make use of jQuery we need to add some script tags and wait for the DOM (Document Object Model)to be ready on the page.
<script type="text/javascript">
$(document).ready(function() {
// do stuff when DOM is ready
});
</script>
Now we need to select the element that we're trying to get data from. jQuery selectors are perfect for this. A simple example is grabbing an element by its "id" attribute.
In the case of the input we'll use "name". When referencing an ID in a selector, we always precede it with a #.
$('#name').val()
This will give us the value of the input. Now add another row.
Your table doesn't have an ID, but lets give it one.
<table id='numbers'>
add the html for the row
$('#numbers').append('<tr><td></td><td></td></tr>');
select the first column of the row we just added and add the number.
var rows = $('#numbers tr').length;
$('#numbers tr:last td:first').html(rows);
copy the value of the input to the second column
$('#numbers tr:last td:last').html($('#name').val());
remove empty the input
$('#name').val('');
Now to detect the keystroke we will attach a listener to the input and place all of this code inside.
$('#name').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$('#numbers').append('<tr><td></td><td></td></tr>');
var rowcount = $('#numbers tr').length;
$('#numbers tr:last td:first').html(rowcount);
$('#numbers tr:last td:last').html($('#name').val());
$('#name').val('').focus();
}
});
This looks good, except $('name') is making extra selections slowing down your code and its redundant inside of a function attached to that object. We can use $(this) instead of $('#name') inside of the listener which references the initial selection done by
$('#name').on('keyup', function(e) {
So we have -
<script type="text/javascript">
$(document).ready(function() {
$('#name').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$('#numbers').append('<tr><td></td><td></td></tr>');
var rowcount = $('#numbers tr').length;
$('#numbers tr:last td:first').html(rowcount);
$('#numbers tr:last td:last').html($(this).val());
$(this).val('').focus();
}
});
});
</script>
I'll throw you a bone here since this is pretty simple code (and you're new). Try this jsFiddle example.
HTML
<table width="500" border="1">
<tr>
<td>No.</td>
<td>Name</td>
</tr>
</table>
<br />
Enter Name:
<input type="text" name="name" id="name" />​
jQuery
var index = 1;
$('input[name=name]').on('keyup', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html(index);
$('table tr:last td:last').html($(this).val());
$(this).focus().select();
index++;
}
});​
Welcome to Stackoverflow.
If you're using jQuery, check out jQuery's API for detailed information about what functions are available. Your specific question seems to be around events - which you can learn more about here.
In short, you'll want to bind an event that delegates the result to another control. I suggest looking at the keyup function.
I hope that helps.
References:
http://api.jquery.com/
http://api.jquery.com/category/events/
http://api.jquery.com/keyup/

How do I get the cell value from a table using JavaScript?

<td> <input type="button" name="buton" id="x2" value="2" onclick="swap(id)";/> </td>
This is the button in a table when it is clicked it's id is passed as parameter to function "swap" as below:
function swap(x)
{
document.write(x);
}
It is successful in getting the id but not the value;when i am trying in this way:
function swap(x)
{
document.write(x.value);
}
The output is shown as undefined. Can you tell me how to get the cell value using the cell id?
I believe that what you are looking for is document.getElementById(x).value;
Also if you want the button just pass this to the function like this:
<button onclick="foo(this)"/>
I guess use jQuery for the purpose,it allows to traverse in DOM very easily.
<table id="mytable">
<tr><th>Customer Id</th><th>Result</th></tr>
<tr><td>123</td><td></td></tr>
<tr><td>456</td><td></td></tr>
<tr><td>789</td><td></td></tr>
</table>
If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:
$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
}
Essentially this is the same as the other solutions (possibly because I copypasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a < span >, provided you keep the class attribute with it.
By the way, I think you could do it in one selector:
$('#mytable .customerIDCell').each(function()
{
alert($(this).html());
});
If that makes things easier
Code will be more or less more reliable on cross bowser issue
z = document.getElementById(id); first, and then you should be able to use z.firstChild.textContent
You need to get the cell using var cell = document.getElementById(x). Then use cell.firstChild.nodeValue.
function swap(x)
{
var cell = document.getElementById(x);
document.write(cell.firstChild.nodeValue);
}
EDIT: Tested this on both FF3.5 and IE8 and it works.
If you are passing the id of the element you might want to use document.getElementById(x) to access it.

Categories