jQuery - get next element with same name as id of

2020-03-29 05:31发布

First off, I'd like to apologize for the horrid title there, but it was the best way I could think of summing up my issue.

Currently, I use a jQuery script that checks, on blur on an input:text, that the text value of the input is greater than a certain amount. If not, the input is highlighted red - but what I'd like to happen next, is to have a <p> in an adjacent column to have it's text changed.

My HTML looks like this:

<tr>
      <td width="15%"><label for="example">Hello world</label></td>
      <td width="70%"><input type="text" class="" id="example" value=""/></td>
      <td width="15%"><p name="example"></p></td>
 </tr>

And my jQuery/css is :

<style type="text/css">
    .fail{
        border:2px red solid;
    }   
    </style>

    <script type="text/javascript">
    /* Inline, onBlur validation 
    Text */
    $('input:text').blur(function() {
        if ($(this).val().length <= 2) {
            $(this).attr('class', 'fail');
            }else{$(this).attr('class', '');}
    });
    </script>

Is it possible, on blur to somehow call the next element with the same name as the selected input's id, and then change it's text? I know this must be a tough dynamic puzzle to solve, but it's something I really need.

In the past, I achieved the same effect by repeating the code for every element, but that's not really suitable here.

Thank you for any advice you can give me!

2条回答
甜甜的少女心
2楼-- · 2020-03-29 05:34

In the context of the blur callback:

$('[name="'+$(this).attr('id')+'"]').text('foo bar baz');
查看更多
女痞
3楼-- · 2020-03-29 05:53

zzzzBov is correct however it would be better to use a context to improve efficiency and/or a tagname. In addition add a variable that references $(this).

var $this = $(this);
$('p[name="'+$this.attr('id')+'"]', $this.closest('tr')).text('foo bar baz'); 

Edited after comment The difference between above and zzzzBov's answer is:

$('[name="'+$(this).attr('id')+'"]')  
// will start traversing the DOM starting at the beginning of the 
// document. Largest search.

$('p[name="'+$this.attr('id')+'"]')
// will first call getElementsByTagName and try to find a match, smaller search.

$('p[name="'+$this.attr('id')+'"]', $this.closest('tr'))
// will only search the contents of the closest('tr') tag 
// that is an ancestor of your input. Even smaller search.

Generally speaking being more specific with jQuery selectors can improve preformance. In addition using variable to store selected elements such as var $this = $(this); or var $myElement = $('#myElement') is more efficient than creating the same selectors over and over. Remember jQuery is as efficient as it can be with the selectors but it is up to you to use them to thier potential.

查看更多
登录 后发表回答