How to find a label with a specific attribute and its value

I have a page layout like this

<input id="name" class="mandotary" type="text">
<label for="name">Name must be entered</label>

<input id="code" class="mandotary" type="text">
<label for="code">Code must be entered</label>

Now I want to hide the label element when the page loads. If he lost focus, and the value is zero, then the label must be indicated otherwise the label must be hidden. I tried this

var inputElementArray = $("input.mandotary");
$.each(inputElementArray, function(index, element){

    var id = $(element).attr("id");
    var label = $("label").attr("for", id);
   // label.hide();

    $(element).focus(function(){
        var next = $(element).next();
        $(element).next().hide();
    }); //end of focus()

    $(element).blur(function(){

        // get value of text area
        var text = $(element).val();
        if (text == "") {
            var next = $(element).next();
            $(element).next().show();
        } //end of if

    }); //end of blur()

}); //end of $(document).ready(fn)

But the line

var label = $("label").attr("for", id);

Give me both tags. I just want a label for which the attribute value is id (name or code). I get the name or code as id in var id . But he finds and leabes. How can I find a label for which the attribute value is equal to my input element identifier?

thank

+3
source share
3 answers
var label = $('label[for="' + id + '"]');
// But it can be done simply with:
var label = $(element).next('label').attr("for", id);

Notes and best signs:

Your code uses jQuery for no good reason:

var id = $(element).attr("id");
// Can be simply:
var id = element.id;

jQuery each :

var inputElementArray = $("input.mandotary");
$.each(inputElementArray, function(index, element){

:

$("input.mandotary").each(function(index, element){
    //...
}):
+10

   : $('# id select'). prev ('label');   :

<label for="my_input">Text of label</label>
<input type="text" name="" id="my_input" value="" />
<script type="text/javascript">
    var labelText = $('#my_input').prev('label').html();
</script>
0

The problem with your code is just a tag selector. You can improve your code further by "caching" jQuery elements in private variables so as not to trigger a selector for every function call.

var inputElementArray = $("input.mandotary");
$.each(inputElementArray, function(index, element){

    // the local variables 'label' and 'input' are an enclosed
    // references to the corresponding  INPUT and LABEL jQuery objects

    var input = $(element);
    var label = $("label[for=" + input.attr("id") + "]");

    label.hide();

    input.focus(function() {
        label.hide();
    }); //end of focus()

    input.blur(function(){
        if(!input.val()) { label.show(); }
    }); //end of blur()

}); //end of $(document).ready(fn)
-1
source

All Articles