javascript - Assign multiple selectors to variable based on which one exists -


i'm looping through container , looking possible elements exist. if 1 of elements exist, want assign jquery object element variable. have solution, i'm not sure if it's way go it.

html

<form> <div>     <label>first name</label>     <input type="text"/> </div>  <div>     <label>last name</label>     <input type="text"/> </div>  <div>     <label>location</label>     <select>         <option>usa</option>     </select> </div> </form> 

js

$(document).ready(function(){ var testnum = $('form').find('label').length; for(var i=0; i<testnum; i++) {     var currenttest = $('form').find('label').eq(i).parent().find('input').length ? $('form').find('label').eq(i) : false || $('form').find('label').eq(i).parent().find('select').length ? $('form').find('label').eq(i) : false;     $('html').append(currenttest.text() + '<br/>'); } }); 

edit: updated fiddle , problem

http://jsfiddle.net/pmtzb/1/

the way looping inefficient. should use .each() method, this:

$('form').find('label').each(function() {     var $label = $(this); // $label jquery object refers label element.       ... }); 

the way doing it, repeatedly calling .find() same selector.

update after question edited:

two things first:

  1. it helpful if stated elements wanted in words, not code. assume want <label> elements followed either <input> or <select>.
  2. you should use parentheses. looked up, , logical-or operator has higher precedence conditional operator, , conditional operator has right-to-left associativity. think need add parentheses statement looks this: (c1 ? a1 : a2) || (c2 ? b1 : b2). without parentheses, have equivalent of c1 ? a1 : ((a2 || c2) ? b1 : b2).

you try adding on k d suggested , concatenate jquery wrapped set:

$(document).ready(function() {      var $matchinglabels = $();      $('form').find('label').each(function() {         var $label = $(this);         if ($label.next().is('input, select')) {             $matchinglabels.add($label);         }     });      // @ point $matchinglabels holds labels want. }); 

you try using "prev + next" selector:

$(document).ready(function() {      var $matchinglabels = $('form').find('label + input, label + select').prev();  }); 

of course, if can't assume <input> , <select> elements follow <label> elements, have go first option , modify if-statement.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -