views:

39

answers:

2

My codes in HTML:

<p><input type="text" class="txt" id="u" /><label for="u">user</label></p>
<p><input type="text" class="txt" id="p" /><label for="p">pass</label></p>

Javascript:

$(document).ready(function() {
    if( $('.txt').val() ) {
        //change st in related label tag
    }
});

How to do that? Please help me solve this issue. Thank you very much !

+2  A: 

You can do:

$("input.txt").focus() {
  $("label[for='" + this.id + "']").addClass("highlight");
}).blur(function() {
  $("label[for='" + this.id + "']").removeClass("highlight");
});

with:

label.highlight { background: yellow; font-weight: bold; }

While an input field has focus, its label (assuming it has one) is highlighted.

Edit: To traverse the inputs and do something with the labels:

$(":input[id]").each(function() {
  if ($(this).val() != '') {
    $("label[for='" + this.id + "'").each(do_something);
  }
});

function do_something() {
  // this refers to the label
}

or simply:

$(":input[id]").each(function() {
  if ($(this).val() != '') {
    $("label[for='" + this.id + "'").addClass("notnull");
  }
});

or you can go the other way:

$("label[for]").each(function() {
  var label = this;
  $("#" + $(this).attr("foo") + ":input").each(function() {
    if ($(this).val() != "") {
      $(label).addClass("notnull");
    }
  });
});
cletus
If you can use "this", I have solutions to the "parent" and "find". But I want to ask in this case can not use "this".
Tran Tuan Anh
What? You don't want to use this? Or can't? Why not?
cletus
When document is ready, I want check value of the inputs. If the value is not null, I will do somethings with my label tags. Thanks for reading.
Tran Tuan Anh
oh dear, that's what i wish. Thanks ^^
Tran Tuan Anh
+1  A: 

You can look for the labels first and find related text fields, like so:

$('label[for]').each (function () 
{
    var label = $(this), textfield = $('#' + label.attr('for') + '.txt');
    if (textfield.length && textfield.val ())
        doSomething (label);
});
K Prime
a nice solution. Thanks ^^
Tran Tuan Anh