Greg Viv
Greg Viv

Reputation: 847

How to change custom attribute of table cell when event was caused by object inside that cell - jQuery

Let's say I have a table with input text in it, here is an example:

<table>
<tr><td customattribute="1"><input type='text' onchange='somefunction();'></td></tr>
<tr><td customattribute="2"><input type='text' onchange='somefunction();'></td></tr>
</table>

I have a function:

var myInput = something that would target td cell that is containing input causing onchange event
myInput.setAttribute('customattribute', $(this).val()); 

I want to change customattrubute of td that contains input that caused event to inputs value. How can I do that without assigning id's to those elements. how do i set myInput to "td cell that is containing input causing onchange event"

I understand I should use some combination of $(this) and perhaps $(this).find ?

Upvotes: 0

Views: 88

Answers (2)

Tree Nguyen
Tree Nguyen

Reputation: 1199

You can use the combination between .change() and .parent() to do it

This is the code

http://jsfiddle.net/mankinchi/m4g9czc4/1/

You use

$("input").change();

to set an event for every input. And use

$(this).parent();

to get the container

Upvotes: 2

Racil Hilan
Racil Hilan

Reputation: 25351

To select the <td>, use the .parent() function. However, since you are using HTML function, you will have to pass this to the function. Try this:

function somefunction(myInputBox){
  var myInput = $(myInputBox).parent()[0];
  myInput.setAttribute('customattribute', $(myInputBox).val());
  //this line is just for testing.
  alert(myInput.attributes['customattribute'].value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td customattribute="1"><input type='text' onchange='somefunction(this);'></td></tr>
<tr><td customattribute="2"><input type='text' onchange='somefunction(this);'></td></tr>
</table>

You can also use the jQuery myInput.attr() instead of the myInput.setAttribute(), so you don't have to use the [0] at the end of parent(). (see below).

Alternatively, you can bind the click event using jQuery instead of in HTML onchange='somefunction();'. This way you don't have to pass this. I personally prefer the HTML unless I need to bind it at run time for some reason. Anyway, it's up to you:

$("input").change(function() {
  var myInput = $(this).parent();
  myInput.attr('customattribute', $(this).val());
  alert(myInput.attr('customattribute'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td customattribute="1"><input type='text'></td></tr>
<tr><td customattribute="2"><input type='text'></td></tr>
</table>

Upvotes: 1

Related Questions