简体   繁体   中英

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 erase placeByCountryId'. If user erase placeByCountryName then its placeByCountryId` should be zero.

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

It should be

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

instead of:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM