On one part of my website, I have a text label, a text input box and a label behind the box (the label specifies the unit). I want these to be visible/invisible depending on whether a radiobutton is checked.
The html part is currently as follows:
<span id="txtLabelInFronOfBox">Some text</span>
<input id="textBoxInput" size="3" class="numeric" pattern="[0-9]+" type="text">
<span id="txtUnit">A</span>
The reason why I’m using the span tag here and not simply just type the text, is that I need to have some ID for the text, to access it from the Jquery part. Here’s the Jquery part:
$('#rbtMyRadioButton').change(function() {
if ($('#rbtMyRadioButton').is(':checked')){
$('#txtLabelInFronOfBox, #textBoxInput, #txtUnit').css('display', 'block');
}
});
The reason why I’m using ‘display’ and not ‘visible’/’invisible’ is that I want the space these controls occupy to disappear when they are not visible. This works fine, except that for some reason this creates a line shift after each control, i.e. when I check the radio button, these controls appear, but there is a line shift after txtLabelInFronOfBox, one after textBoxInput and one after txtUnit.
Any suggestions to what I can do to not get these line shifts?
Initially I just created a paragraph around all these controls, gave the paragraph an ID and accessed the ID from the Jquery. Then I checked the code of my page on an html validator, and it said that this was not according to the HTML5 standard. That’s a pity, because that worked exactly like I wanted.
By “line shift” I assume you mean that each element starts on a new line. This is happening because you are setting
display: blockand by default block elements start on a new line.You could instead say:
“inline” is the default for spans and inputs. If you set
displayto an empty string then it should fall back to the default as specified in your stylesheet or (if not specified) the default for the element type (“inline” in this case).Regarding wrapping the elements in a paragraph and that not being valid html5, try using a div element instead.
Rather than setting
displaydirectly yourself, try jQuery’s.show()and.hide()methods:Demo: http://jsfiddle.net/nnnnnn/Hmrnq/1/ (thanks to Amar for creating the starting fiddle)