Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find label with particular attribute and its value

Tags:

jquery

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 page load first. If it has lose the focus and value is null then label should be shown else label should 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 the labels. I just want that label whose for attribute value is id(name or code). I get the name or code as id in the var id. But it finds both the leabes. How can i find that label whose for attribute value is equal to my input element id?

Thanks

like image 235
Basit Avatar asked May 02 '12 08:05

Basit


1 Answers

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

Notes and best parctices:

Your code overuses jQuery for no good reason:

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

And you can use the jQuery function each this way instead:

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

To be used on the direct elements:

$("input.mandotary").each(function(index, element){
    //...
}):
like image 193
gdoron is supporting Monica Avatar answered Oct 20 '22 18:10

gdoron is supporting Monica