xrcwrn
xrcwrn

Reputation: 5327

Key up event is not working

I have one text and one hidden input field. I want on removing value from input field if it is empty then hidden box value should be zero but this is not working.

$(document).ready(function () {
     $(document).on('keyup', '#placeByCountryName', function (e) {
         e.preventDefault();
         alert("hi");
         if (($('#placeByCountryName').val().length === 0) || ($('#placeByCountryName').val() === "")) {
             $('#placeByCountryId').val(0);
         }
     });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="hidden" name="atomAddressDetail.placeByCountryId.id" id="placeByCountryId" value="44" class="addressdetail form-control" />
<input type="text" name="atomAddressDetail.placeByCountryId.name" id="placeByCountryName" class="addressdetail form-control" value="India" placeholder="Country" />

But this is not working. How to resolve above?

EDIT I get some id,name value from autocomplete to my textbox placeByCountryName and its corrosponding id in placeByCountryId'. If user eraseplaceByCountryNamethen itsplaceByCountryId` should be zero.

Upvotes: 0

Views: 94

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need to attach event on input type text, not on input type hidden element:

$(document).on('keyup', '#placeByCountryName', function (e) {
     e.preventDefault();
     alert("hi");
     if (($(this).val().length === 0) || ($(this).val() === "")) {
         $('#placeByCountryId').val(0);
     }
 });

Upvotes: 2

PhuLuong
PhuLuong

Reputation: 537

It should be

$(document).on('keyup', '#placeByCountryName', function (e) {
});

instead of:

$(document).on('keyup', '#placeByCountryId', function (e) {
    });

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You need to use type="text" as keyup will not work on hidden

<input type="text" id="placeByCountryId" value="44" class="addressdetail form-control" />

$(document).ready(function () {
     $(document).on('keyup', '#placeByCountryId', function (e) {
         e.preventDefault();
         alert("hi");
         if (($(this).val().length === 0) || ($(this).val() === "")) {
             $(this).val(0);
         }
     });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" name="atomAddressDetail.placeByCountryId.id" id="placeByCountryId" value="44" class="addressdetail form-control" />
<input type="text" name="atomAddressDetail.placeByCountryId.name" id="placeByCountryName" class="addressdetail form-control" value="India" placeholder="Country" />

OR, Bind event on Country Name textbox

$(document).on('keyup', '#placeByCountryName', function(e) {
    if (($(this).val().length === 0) || ($(this).val() === "")) {
        $('#placeByCountryId').val(0);
    }
});

Upvotes: 1

Related Questions