Reputation: 2323
I'm sure this is very simple but I'm stuck.
I have an input, when a value is entered I would like to append this value to a <span>
element. Once the value is deleted from the input, I would like to also remove it from the <span>
element.
The issue i'm having is that the input value is removed, but the html 'Name' remains.
<input type="search" id="searchName" type="text">
<div id="searchFilter">
<p><span id="filterName"></span></p>
</div>
$('#searchName').keyup(function() {
if ($('#searchName').length > 0) {
$("#filterName").text('Name: ' + $('#searchName').val());
} else {
$("#filterName").empty();
}
});
Any help is appreciated.
Upvotes: 1
Views: 50
Reputation: 186
I would handle the 'search' and 'keyup' events to account for users clicking the 'x' and users typing in the field. See JSFiddle Example
$('#searchName').on('keyup', function() {
updateFilter(this);
});
$('#searchName').on('search', function(){
updateFilter(this);
});
function updateFilter(element){
if ($(element).val().length > 0) {
$("#filterName").text('Name: ' + $(element).val());
} else {
$("#filterName").empty();
}
};
Edit: Updated link to point at JSFiddle setup to use JQuery. Original link excluded that update.
Upvotes: 0
Reputation: 131
If you assign the keyup to the body element, not the input box itself then it will register the event and work -
$('body').keyup(function() {
if($('#searchName').length > 0) {
$("#filterName").text('Name: ' + $('#searchName').val());
} else {
$("#filterName").empty();
}
});
Fiddle link - https://jsfiddle.net/age3nyph/4/
Upvotes: 0
Reputation: 1304
Change the condition in the if to:
$('#searchName').val().length > 0
Upvotes: 0
Reputation: 551
With a few modif. it's ok :-)
$('#searchName').on("keyup",function() {
if ($('#searchName').val() != "") {
$("#filterName").text('Name: ' + $('#searchName').val());
} else {
$("#filterName").text("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="searchName" type="text">
<div id="searchFilter">
<p><span id="filterName"></span></p>
</div>
Upvotes: 0
Reputation: 2314
Evaluate the length of the val()
, not the element itself:
$('#searchName').keyup(function() {
if ($('#searchName').val().length > 0) {
$("#filterName").text('Name: ' + $('#searchName').val());
} else {
$("#filterName").empty();
}
});
Upvotes: 4