javascript - Getting a label's value using select's name tag -


i have system can output 0 or more select boxes , need add javascript/jquery validation. new writing jquery , stuck getting content of text label error message: here example of select boxes form:

<div id="prodoptions" class="sale">    <p class="eleventext floatleft">product options</p>     <div class="floatleft"><label for="colour">select colour</label>     <select name="colour">         <option value="" selected="selected">---</option>         <option value="blue">blue</option>     </select> </div> <div class="floatleft">     <label for="size">select size</label>     <select name="size">         <option value="" selected="selected">---</option>         <option value="small">small</option>     </select> </div> <div class="floatleft">     <label for="flavour">select flavour</label>     <select name="flavour">         <option value="" selected="selected">---</option>         <option value="cherry">cherry</option>     </select> </div> 

and here javascript function called on form submission (the alerts testing):

function validateoptions() {      selectlist = $('select').get();     message = "";      for(i=0; i<selectlist.length; ++i)     {              //alert(selectlist[i].name);             selector = "for[=\""+selectlist[i].name+"\"]";             alert(selector);             alert($(selector.value));             message += ($(selectlist[i]).prop('selected', true).val() == "") ? "please enter value \r\n" : "";      }      alert(message);   } 

your attribute syntax incorrect. selector should be

var selector = "label[for='" + selectlist[i].name + "']"; 

from there, should fetch label's .html(), rather .val()

also, labels should reference element id's, rather names. not clear how want message formatted. should able this:

function validateoptions() {      var message = '';      $('select').each(function() {        if($(this).val() == '') {           var label = $('label[for="' + $(this).attr('id') + '"]');           message += 'please select value for: ' + label.html() + '\n';        }     });      alert(message); } 

you format error message so:

function validateoptions() {     var emptyfields = [];     $('select').each(function() {        if($(this).val() == '') {           var label = $('label[for="' + $(this).attr('id') + '"]');           emptyfields.push(label.html());        }     });      if(emptyfields.length > 0) {        alert('please select value for:\n' + emptyfields.join('\n'));     } } 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -