Reputation: 119
I have a form input which, when text gets typed into it, updates a div. This is what I use:
$('#CampaignTitle').keyup(function() {
$('#titleBar').text(this.value);
});
That works super except I'd also like the ability to hide the div (I know how to make it start off hidden) when there's no text in the form input.
In otherwords when someone types into the form input a div will appear and the text which is being typed into the input appears in the div. If the user clears the input again then the div dissappears.
Sorry I'm new to JS :)
Upvotes: 0
Views: 316
Reputation: 95528
Something like this should work:
$('#CampaignTitle').keyup(function() {
var $titleBar = $('#titleBar');
if(this.value.length == 0) {
$titleBar.hide();
}
else {
if($titleBar.is(":hidden")) {
$titleBar.show();
}
$titleBar.text(this.value);
}
});
It's a bit verbose and there are ways to make it a little less-verbose, but since you're still learning, I figured that this would give you a general idea of what's going on. The is(":hidden")
check can be omitted; that would run show()
on $titleBar
even if it is already visible.
Upvotes: 0
Reputation: 6955
$('#CampaignTitle').keyup(function() {
if (this.value){
$('#titleBar').text(this.value).show();
}
else {
$('#titleBar').hide();
}
});
Upvotes: 0
Reputation: 101483
Do a test to see if the text box value's length is greater than 0:
$('#CampaignTitle').keyup(function() {
if($(this).val().length > 0)
{
$('#titleBar').text($(this).val()).show();
}
else
{
$('#titleBar').hide();
}
});
The key line here being if($(this).val().length > 0)
.
Upvotes: 2
Reputation: 10606
Try this
$('#CampaignTitle').keyup(function() {
$('#titleBar').text(this.value).show();
if (this.value==''){ $('#titleBar').hide() }
});
Upvotes: 0