Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the next label in jQuery?

Tags:

jquery

How to select the label with class="date" and id="z" here from my position?

<td style="width:300px;height:40px;" id="pricePanel">
    <div id="class">
        <label class="priceNumber" id="label">test</label>
        <div class="no" hidden="hidden">
            <input type="text" id='priceNumber' class="text" style="text-align:center;" onkeypress="if(event.keyCode==13)" value='@item.Cost.ToString()' />
        </div>
    <div>
</td>
<td id="x">
    <label class="date" id="z">@date</label>
</td>

My position is here in textbox block in my jQuery code:

$(".text").live("keypress", function (event) {
        //Here I want to change the text of the label with class="date" and id="z"
    });

Note:In the main code I have a loop and unfortunately there is some of the labels with the same class and id and because of this I want to select the label after the textbox that I have changed its text.

like image 717
Hamid Reza Avatar asked Dec 27 '22 07:12

Hamid Reza


2 Answers

use $(this) reference to get the current position.. parents('td') to move to <td>..next() to get the next <td> and find to get the label try this

 $("div.no").on("keypress",".text", function (event) {
   $(this).parents('td').next().find('#z').text();
});

HOWEVER since you have id in the label...using it directly as a selector is better performance wise and faster..

 $(".text").on("keypress", function (event) {
   $('#z').text();  // $('label.date').text();
});
like image 73
bipen Avatar answered Jan 11 '23 06:01

bipen


You can use closest() to reach the parent td of text then use next() to reach next td and find() label with given class. You probably have repeated structure and use same id with more then one element is prohibited so use class with label. If you do not have repeated structure then use id straight away.

Live Demo

You are not close the first div in the first td also.

Html

<table>
    <tr>
        <td style="width:300px;height:40px;" id="pricePanel">
            <div id="class">
                <label class="priceNumber" id="label">test</label>
                <div class="no">
                    <input type="text" id='priceNumber' class="text" style="text-align:center;"
                    onkeypress="if(event.keyCode==13)" value='@item.Cost.ToString()' />
                </div>
            </div>
        </td>
        <td id="x">
            <label class="date" id="z">@date</label>
        </td>
    </tr>
</table>

Javascript

$(".text").live("keypress", function (event) {
    $(this).closest('td').next('td').find('.date').text("your text");
});

If you do not have repeated block and have single then directly use id.

$(".text").live("keypress", function (event) {
    $('#z').text("your text");
});

Live is deprecated use on if it is possible.

like image 29
Adil Avatar answered Jan 11 '23 04:01

Adil