简体   繁体   中英

Getting the closest element in the form with javascript

I have the following two fields in a form:

<input type="button" value="Rep" id="rep" name="rep" style="width:50px" onclick="addRep()" />
<input type="hidden" value="<?php echo $comment_id; ?>" />

I need to get the value of the hidden field in the form. So I thought to use some function to call the hidden field field next to the button whenever it is triggered.

I need to get that hidden field specifically, that comes after the button pressed.

I cant use methods like getElementByID,,cause I generate many of those hidden fields and buttons with the same id.. (I generate them dynamically with php).

In theory, I think that I could get the context of the button pressed (after trapping its event) and then use some function to find the next element in the form..

But I am not sure how to do that!

另一种解决方案是将生成的ID存储在数组中(确保为所有内容都提供Id属性),然后使用该数组对元素进行索引。

Consider that you might have another element between your button and your hidden element. For example:

<input type="button" value="Rep" id="rep" name="rep" style="width:50px" onclick="addRep()"/>
<input type="text" id="someText" value="whatever"/>
<input type="hidden" id="someButton" value="anything"/>

In this case, you can target the hidden input element that is "closest" to the identified button by performing some checks:

var rootNode    = document.getElementById('rep'),
    currentNode = rootNode.nextSibling,
    closestHidden;

function check(node) {
  return node.nodeType === 1 && node.localName === 'input' && node.type === 'hidden'
};

do {
  if (check(currentNode)) {
    closestHidden = currentNode; break;
  }
} while (currentNode = currentNode.nextSibling);

alert(closestHidden.id);

You are not supposed to ever have more than one element on the page with the same ID. Classes can be repeated, but IDs should be unique.

You are on the right track with using the context of the button pressed. This type of thing is much easier if you use a framework such as jQuery. Jquery has many methods for traversing the DOM http://api.jquery.com/category/traversing/ one is next() which will find the next sibling element.

Using jQuery will also make it easier to move your javascript events out of the HTML, so instead of onclick="" you can assign events in a separate JS file, keeping markup separate from behavior.

To reliably get the next control in a form, you can iterate over the form's elements collection to find the subject element, then get the next one, eg:

function getNextControl(el) {
  var elements = el && el.form && el.form.elements;
  if (elements) {
    for (var i=0, iLen=elements.length; i<iLen; i++) {
      if (elements[i] == el) {
        return elements[i + 1];
      }
    }
  }
}

Now you can structure your HTML however you like, the above will return the next form control or undefined if there isn't one.

You can use jquery next() method.

If you want a pure javascript solution, See this post Get next/previous element using Javascript

best voted answer in that post is,

use the nextSibling and previousSibling properties:

<div id="foo1"></div> <div id="foo2"></div> <div id="foo3"></div>

 document.getElementById('foo2').nextSibling; // #foo3
 document.getElementById('foo2').previousSibling; // #foo1

However in some browsers (I forget which) you also need to check for whitespace and comment nodes:

 var div = document.getElementById('foo2'); var nextSibling =
 div.nextSibling; while(nextSibling && nextSibling.nodeType != 1) {
     nextSibling = nextSibling.nextSibling }

Libraries like jQuery handle all these cross-browser checks for you out of the box.

If you have a reference to the button, and you want the element after the button, you could use the property

nextSibling;

Make sure you avoid any text objects that comes from comments, line breaks or white spaces.

For a complete overview over the HTML Dom object take a look at http://www.w3schools.com/jsref/dom_obj_all.asp

Get a reference to the current button, eg the event's target property or just use this in the event handler. Then you'll find the node next to that button in the nextSibling property, but watch out: this is usually a whitespace text node. So use nextElementSibling instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM