1

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.

Fiddle link.

<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.

isherwood
  • 58,414
  • 16
  • 114
  • 157
TheOrdinaryGeek
  • 2,273
  • 5
  • 21
  • 47

5 Answers5

4

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();
  }
});

Fiddle

WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
0

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>
PhilMaGeo
  • 551
  • 6
  • 8
0

Change the condition in the if to:

$('#searchName').val().length > 0
Nikola Yankov
  • 1,264
  • 1
  • 15
  • 28
0

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/

Steven
  • 131
  • 8
0

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.

J-Americano
  • 188
  • 1
  • 10