TheOrdinaryGeek
TheOrdinaryGeek

Reputation: 2323

Why isn't my element being emptied as expected?

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.

Upvotes: 1

Views: 50

Answers (5)

J-Americano
J-Americano

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

Steven
Steven

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

Nikola Yankov
Nikola Yankov

Reputation: 1304

Change the condition in the if to:

$('#searchName').val().length > 0

Upvotes: 0

PhilMaGeo
PhilMaGeo

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

WillardSolutions
WillardSolutions

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

Fiddle

Upvotes: 4

Related Questions