Keypress action query using jQuery class attribute - javascript

I am implementing the view behavior using jQuery. I can input directly to the table td. I want to give an event when inputting to this td.
But the event is not recognized, what should I do?
Here is the code:
<div class="a">
<table class="tb">
<tr>
<td></td>
</tr>
</table>
</div>
<script type="text/javascript">
$(".a table tr td").on('keypress', function(event){
console.log(event);
});
</script>
It is an event required only on the page, so it is difficult to modify the common jQuery code that draws and enters the table.

Based on this:
A keypress event handler can be attached to any element, but the event
is only sent to the element that has the focus
So you need to have focusable element, see this to know what are the focusable element: Which HTML elements can receive focus?
If I have textbox in td everything going to be fine:
$(".a table tr td").on('keypress', function (event) {
console.log(event.key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="a">
<table class="tb">
<tr>
<td><input /></td>
</tr>
</table>
</div>

The below code works, so if it doesn't work in your case, that probably means that the <input> field is not yet added by your other "common" code, at the time you add the keypress listener.
So the solution should be to first add the <input> fields, and after that you execute your key handler code.
<div class="a">
<table class="tb">
<tr>
<td><input type="text"></td>
</tr>
</table>
</div>
Execute this AFTER the input fields have been added
$(".a table tr td").on("keypress", function (event) {
console.log(event.key);
});
Working example here: https://jsfiddle.net/081cL2xu/

Related

Activating td button using JavaScript

I have the following function, which is used to expand and collapse child tr rows from parent rows within a table, and also changes the text style of a tr to normal:
$( document ).ready(function() {
$('.parent').on('click', function(){
$(this).next('.child').toggle();
$(this).css('font-weight', 'normal');
<<< ADD COMMAND TO TOGGLE BUTTON HERE >>>
});
});
I also have the following hidden button within each tr, which I want to submit when a tr is clicked:
<button type="submit" name="read-button" formmethod="POST" value="{{ message.message_id }}" style="display: none;"></button>
Which command should I include alongside the JavaScript function, in order to achieve this? I believe it will be one of the following (provided by this answer), however I've only been using JS for a few days so I'm not sure how to include these in my code:
document.getElementById('read-button').submit();
changeAction('read-button','loginForm');
document.forms['read-button'].submit();
Sample html:
<form method=['POST']>
<table>
<tr class="parent">
<td>
<button type="submit" name="read-button" formmethod="POST" value="{{ message.message_id }}" style="display: none;"></button>
<a>Heres a cell</a>
</td>
<td>
<a>
Heres one more cell
<a>
</td>
</tr>
<tr class="child">
<td>
<a>
Some hidden info
</a>
</td>
<td>
<a>
More hidden info
</a>
</td>
</tr>
<table>
</form>
To answer the specific question of how to trigger a button within a td via clicking on the tr:
$('.parent').on('click', function() {
$(this).find("button").click();
that can be improved by giving the button a class (incase you add additional buttons in future), eg:
<button class='readbutton' ..`
then
$('.parent').on('click', function() {
$(this).find("button.readbutton").click();
In this scenario, it seems that you don't need a hidden button as you can call the functionality of the hidden button directly.
So rather than:
$("button").click(handleClick);
use
$('.parent').on('click', function() {
.. other functionality ...
handleClick();
as you're new to js, note the difference between handleClick and handleClick() - with () it calls the function, without it passes it as a function variable.
$("button").click(handleClick);
is the same as
$("button").click(function() { handleClick(); });
If you're trying to submit a form, then you would use $(form).submit() - but there's no form in the code as pointed out in the comments and an ajax call would seem more appropriate here than submitting a form.
Finally, consider using classes rather than setting the css directly as adding/removing classes it quite simple in jquery eg for your tr click event add:
$(this).addClass("selected").siblings().removeClass("selected");

jquery:Dialog box not poping in a dynamically generated table

I have created a struts2-jsp application,i want a dialog pop up whenever edit hyperlink in clicked,I am using Jquery to pop up a dialog when Edit hyperlink is clicked.
The problem is that Dialog box pops up only when the first edit is clicked,in the second and other edits which are generated dynamically when a record is added dialog box doesn't pops up.
The Jquery code is:
<script>
$(document).ready(function(){
$( "#todo" ).dialog({ autoOpen: false });
$( "#dialogLink" ).click(function() {
$( "#todo" ).dialog('open');
});
});
</script>
The code to dynamically generate the table is:
<div class="content">
<table class="todoTable" cellpadding="5px">
<tr class=even>
<th>TITLE</th>
<th>STATUS</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
<!--This will iterate through the todolist -->
<s:iterator value="gettodoList()" status="todoStatus">
<tr class="<s:if test="#todoStatus.odd == true ">odd</s:if> <s:else>even</s:else>">
<td><s:property value="title" /></td>
<td><s:property value="complete" /></td>
<!-- This will append the Id with the url -->
<td>
<a id="dialogLink" href="#">Edit</a>
</td>
<td><s:url id="deleteURL" action="deleteTodo">
<s:param name="id" value="%{id}"> </s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a>
</td>
</tr>
</s:iterator>
</tbody>
</table>
</div>
You need to use the .on() to set the event handler instead of the .click() as the latter will only attach the event on existing nodes while the first will attach it to existing nodes and new ones as well similar to how .live() used to work in earlier versions of jquery
take a look at http://api.jquery.com/live/
1) it is because you are using an id, use a class and it should work fine.
&
2) you should try to use on() for dynamically generated elements.

Disconnecting click event of parent node using jQuery

I have a <td> which contains a <span> tag. The td tag has a click event and the <span> tag has an id. On clicking the span, I want to disconnect the click event of the <td> tag. How do I do by referring to the span tag?
<Table>
<tr>
<td onClick="disconnectHandler();"><span id="testin">Hello</span></td>
</tr>
</Table>
This is what my JavaScript has :
function disconnectHandler()
{
alert("Hi Hello");
$("#testin").parent().unbind();
}
It keeps showing the alert box. What is wrong with this code?
Additionally, i want to attach the click event to it later too after removing it!
The first unbind scenario doesn't work, because of jQuery's event model. jQuery stores every event handler function in an array that you can access via $("#foo").data('events'). The unbind function looks just for given function in this array. So, you can only unbind() event handlers that were added with bind()
Reference.
Working fiddle.
You couldn't use unbind but you could remove the onclick attribute using prop():
function disconnectHandler()
{
alert("Hi Hello");
$("#testin").parent().prop('onclick',null);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td onClick="disconnectHandler();"><span id="testin">Hello</span></td>
</tr>
</table>
If you want to disable the click after first click it will be better to use one(), check the example below.
Description : one() Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Hope this helps.
$(function(){
$('body').one('click', '#testin', function(){
alert("Hi Hello");
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><span id="testin">Hello</span></td>
</tr>
</table>
This will bind a click event only once on the td element
$(document).ready(function() {
$('#testin').one('click', function(){
alert('Hello there');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><span id="testin">Hello</span>
</td>
</tr>
</table>
EDIT
The main difference between my answer and Zakaria's reside in the fact the he can add more span later on (if you use class instead of id that is).
$('body').one('click', '#testin', function(){}); Binds all #testin inside body to a click event.
$('#testin').one('click', function{}); Binds all #testin that are already on the document to a click event.
EDIT 2
to answer your question:
It keeps showing the alert box. What is wrong with this code?
You haven't binded an event to the td element, every time it is clicked it call a function name disconnectHandler().
function doSomething() {
alert('alerted')
}
function removeEvent() {
document.getElementById('doer').removeEventListener('click', doSomething);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="doer" onclick="doSomething()">Click me</p>
<p id="undoer" onclick="removeEvent()">Remove his event</p>
As you can see, the so-called event is part of his DOM. You are not removing the attribute, that is why it still call the function
this can also be tried
function disconnectHandler()
{
alert("Hi Hello");
$("#testin").parent().attr('onclick',"")
}

Get an element based on a change of another element (jquery)

I have the following code:
<tr class="my-field my-field-color-picker" data-name="background_colour" data-type="color_picker">
<td class="my-input">
<input type="text" class="wp-color-picker">
</td>
</tr>
<tr class="my-field my-field-wysiwyg" data-name="text_block" data-type="wysiwyg">
<td class="my-input">
<iframe>
<html>
<body id="tinymce" class="mce-content-body">
some text
</body>
</html>
</iframe>
</td>
</tr>
I am able to get the text input with class="wp-color-picker" thanks to another thread using $('tr[data-name="background_colour"] input.wp-color-picker')
When this text input has a change of value. I want to change the background color of <body>
<body> is inside an iframe inside a tr element with data-type="wysiwyg" which is on the same level as tr with data-name="background_colour"
It's a bit of a mess so I hope this makes sense.
jsFiddle: https://jsfiddle.net/rk3fcjkb/19/
You can do something like this
$(document).ready(function(){
$('tr[data-name="background_colour"] input.wp-color-picker').on('keyup', function(){
$(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css({
background: $(this).val()
});
});
});
Demo
PS: Accessing stuff inside iframe can get very nasty.
You need to get the iframe first and then from there go to the body tag:
$( ".wp-color-picker" ).keyup(function() {
$('tr[data-type="wysiwyg"] td iframe').contents().find("body").css("background-color","blue");
});
Fiddle Example
Note: For change to trigger you need to un-focus the input element, if you want it to do it right away change it on keyup instead.

jQuery closest button after input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need the name of the next button from the input feald, the button can be in different positions(in table, in div after table, etc.). Like a find next in quelltext.
http://jsfiddle.net/LF6pK/
HTML:
<table>
<tr>
<td>Benutzer:</td>
<td><input type="text" id="Benutzername" name="Benutzername"/></td>
</tr>
<tr>
<td>Passwort:</td>
<td><input type="password" id="Passwort" name="Passwort"/></td>
</tr>
<tr>
<td></td>
<td class="fr"><a href="#info" class="submit" onclick="login()">
<button>Login</button>
</a></td>
</tr>
</table>
JS:
$('input').keypress(function(event){
if(event.which==13){
event.preventDefault();
alert($(this).closest('button').html());
alert($(this).next('button').html());
}
});
The alert is always undefined.
EDIT:
Sure i can give the button a unique id but i have 1 page with 10 buttons and each 10-20 inputs. So i hope a easy way to call always the next and dont give alle buttons a uniqe id and a seperate funktion to all inputs.
EDIT2:
I meen with the name the innerHTML of the button.
EDIT3:
The table is not always around the inputs.
EDIT4:
Better example http://jsfiddle.net/LF6pK/7/ and i prefer a dynamic like next button solution.
Look, the problem is:
.closest() is used to call the closest PARENT.
.next() is used to call the next SIBLING, within the same parent of element.
How you should do it:
Use .closest() to call the CLOSEST PARENT that wraps the <input> AND the <button>.
As i can see in you HTML, the closest parent that wrap both is <table> tag. Then you have to use:
$('input').keypress(function(event){
if(event.which==13){
event.preventDefault();
alert($(this).closest('table').find('button').text());
}
});
Fiddle:
http://jsfiddle.net/LF6pK/5/
UPDATED:
var closest = $(this).closest(':has(button)') will find the closest parent that has a button
.parentsUntil(closest) will call all parents until the closest parent that has a button
.nextAll('button') will call the buttons that comes only next each parents
.first() will filter the first one that comes next
jQuery:
$('input').keypress(function(event){
if(event.which==13){
var closest = $(this).closest(':has(button)')
event.preventDefault();
alert($(this).parentsUntil(closest).nextAll('button').first().text());
}
});
Fiddle:
http://jsfiddle.net/LF6pK/9/
UPDATED [2]:
$('input').keypress(function(event){
if(event.which==13){
var closest = $(this).closest(':has(button)')
event.preventDefault();
if($(this).parentsUntil(closest).nextAll('button').length >= 1){
alert($(this).parentsUntil(closest).nextAll('button').first().text());
} else {
alert($(this).parentsUntil(closest).nextAll().find('button').first().text());
}
}
});
Fiddle:
http://jsfiddle.net/LF6pK/11/
It will give you text of the button.
$(this).parents().find('button').text()
OR
$(this).closest('table').find('button').text()
You have to make sure that every button has same wrapper class (no need to be direct parent).
<table class='wrapper'>
...
<tr>
<td>
<button></button>
</td>
</table>
<div class='wrapper'>
<input type='text'>
<button></button>
</div>
Then you can access it by this:
$('input').keypress(function(event){
if(event.which==13){
var button = $(this).closest('.wrapper').find('button');
event.preventDefault();
alert(button.text());
alert(button.text());
}
});
alert($(this).offsetParent().find('button').html());
http://jsfiddle.net/LF6pK/4/
Just position the element with relative or however you wish.
Have you considered using forms if you are just trying to perform an action on enter key press?
<form>
<table>
<tr>
<td>Benutzer:</td>
<td><input type="text" id="Benutzername" name="Benutzername"/></td>
</tr>
<tr>
<td>Passwort:</td>
<td><input type="password" id="Passwort" name="Passwort"/></td>
</tr>
<tr>
<td></td>
<td class="fr"><button>Login</button></td>
</tr>
</table>
</form>
<script>
$('body').on('submit','form',function(e) {
e.preventDefault();
// Do whatever with the inputs
});
</script>

Categories

Resources