Skip to content Skip to sidebar Skip to footer

Nextsibiling Doesn't Work

this is a sample code of what I am doing. unfortunately the alert(nextElem.value) returns 'undefined' when I click the second checkbox to get the href of the link after it. do you

Solution 1:

Get the link's href with jQuery

http://jsfiddle.net/mplungjan/H9Raz/ :

$('form input:checkbox').click(function () {
 alert($(this).nextAll('a').attr("href"));
});

Because of the BRs we need the nextAll, surprisingly since I was using the next selector with an "a"

See here why it did not work: Cleanest way to get the next sibling in jQuery


Get the link's href with forms access and usage of ID - no jQuery

http://jsfiddle.net/mplungjan/fKE3v/

window.onload=function() {
  var chks = document.getElementsByName('checkThis');
    for (var i=0;i<chks.length;i++) {
        chks[i].onclick=function() {
            var id = this.id;
            var linkId="link_"+id.split("_")[1]
            alert(document.getElementById(linkId).href)
        }
    }
}
<form><div><inputtype="checkbox"name="checkThis"id="chk_1"value="http://www.google.com" />Check here<br/><ahref="http://www.google.com"id="link_1">click here</a><br><inputtype="checkbox"name="checkThis"id="chk_2"value="http://www.bing.com" />Check here<br/><ahref="http://www.bing.com"id="link_2">click here</a></div></form>

Forms access to get the next checkbox

<INPUTTYPE="checkbox"NAME="checkThis"value="http://www.google.com"onClick="validate(this.form)">Check here<BR><INPUTTYPE="checkbox"NAME="checkThis"onClick="validate(this.form)">Check here2<BR>
functionvalidate(theForm) {
    var chk = theForm.checkThisfor (i = 0; i <chk.length) ; i++) {
        if (chk[i].checked) {
            var nextElem = chk[i+1]; 
            if (nextElem) alert(nextElem.value);
        }
    }
}

Solution 2:

Your problem is that nextElem is the text node immediately after your checkbox, not the next checkbox; text nodes don't have value attributes. For example, try this:

functionvalidate() {
    for (i = 0; i < (document.f1.checkThis.length); i++) {
        if (document.f1.checkThis[i].checked) {
            var elem = document.f1.checkThis[i];
            var nextElem = elem.nextSibling;
            alert(nextElem);
            alert(nextElem.value);
        }
    }
}

Or, for your convenience:

http://jsfiddle.net/ambiguous/sUzBL/1/

Post a Comment for "Nextsibiling Doesn't Work"