Hallaghan
Hallaghan

Reputation: 1941

Hide Textbox Field and Label associated with it

This is probably a pretty pointless question but I reckon it would be useful for many of us.

In this case's scenario, I would like to be able to hide a textbox and its label all in one go, without having to select both element and hiding them individually.

<label for="a">some text:</label>
<input type="text" class="text" id="a" />

So, for the above case, would it be possible to use a simple jQuery command to hide them both together?

Upvotes: 8

Views: 27707

Answers (4)

Emil
Emil

Reputation: 8527

if you want to reuse the hiding, you can create a function similar to:

function hideTandem(id){
    $('#' + id + ', label[for=' + id + ']').hide();
}

and call it by supplying the id of the input

hideTandem('a');

Upvotes: 2

Jason Gennaro
Jason Gennaro

Reputation: 34855

You could do this

$('label[for=a], input#a').hide();

http://jsfiddle.net/jasongennaro/dYFMU/

[ ] selects the attribute. In this case we are targeting a for attribute that equals a.

At the same time, we use a , to make another selection, the input with an id=a.

EDIT

Also, if you needed to do this for multiple labels and inputs you could put the label and id in an array as follows:

<label for="a">some text:</label>
<input type="text" class="text" id="a" />

<br />

<label for="b">some text:</label>
<input type="text" class="text" id="b" />

<br />

<label for="c">some text:</label>
<input type="text" class="text" id="c" />

js

var a = ['a','b','c'];

for(var i=0; i<a.length; i++){
    $('label[for=' + a[i] + '], input#' + a[i]).hide();
}

http://jsfiddle.net/jasongennaro/dYFMU/1/

Upvotes: 22

Frug
Frug

Reputation: 448

Find the input however you want, and then you can find its ID using

var myInputBoxID = $(some selector).attr("id");

You can then reference the label by using the following syntax to catch the label's for attribute:

$("label[for=' + myInputBoxID + ']").hide();

You can probably nest things nicely so you don't need to store anything as a variable, and instead run through a "for each" on all the results of your input box selector. But anyway the key is finding the ID and then using that to find the label with label[for=...]

Upvotes: 2

Brandon
Brandon

Reputation: 69973

The simplest way would probably be to just wrap them in a div and hide that instead.

<div id="hidethis">
  <label for="a">some text:</label>
  <input type="text" class="text" id="a" />
<div>

$("#hidethis).hide();

Upvotes: 1

Related Questions