Have element hidden on default depending on dropdown
I have a form element, that is hidden or show depending on a dropdown element in my form. I've been able to change the visibility when the dropdown changes.
Here's my code right now:
$("select[name=post_category]").change(function(){
var id = $("select[name=post_category]").val();
if(id != 3){
$("dt#post_url-label").hide();
$("dd#post_url-element"开发者_C百科).hide();
}
else{
$("dt#post_url-label").show();
$("dd#post_url-element").show();
}
});
What I want is the fields to be hidden, unless the page loads with id=3 (so i can't just hide them with CSS), in that case the field has to be visible from the start. Right now, the field is always visible on pageload.
Any suggestions how I should go about this?
Try this:
$('select[name="post_category"]').change(function() {
$('dt#post_url-label, dd#post_url-element').toggle( +this.value === 3 );
}).change();
The idea is to trigger the change event immediately. You should be able to achieve that by using either triggerHandler('change')
or just change()
.
Live demo 1: http://jsfiddle.net/XE78E/
Live demo 2: http://jsfiddle.net/XE78E/1/
The 2. demo shows that the element is visible if the 3-rd option is preselected.
so why dont u check on page load if the id = 3 or not and use same logic to hide or show the element.
That code is javascript, right?
Call $("select[name=post_category]").change() on page load.
window.onload = function() { $("select[name=post_category]").change() }
or add it to your existing onload function.
精彩评论