jQuery - get next element with same name as id of selected input

半世苍凉 提交于 2019-12-19 10:12:08

问题


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!


回答1:


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.




回答2:


In the context of the blur callback:

$('[name="'+$(this).attr('id')+'"]').text('foo bar baz');


来源:https://stackoverflow.com/questions/7734176/jquery-get-next-element-with-same-name-as-id-of-selected-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!