Home > Net >  Append text to class when id changes
Append text to class when id changes

Time:12-22

I try to append text when some id changes.

<div >
    <input name="stime" type="text"  id="stime" placeholder="00:00" required maxlength="5" />
    <span ></span>
</div>

When id stime changes, I want to append a text to the form-control-feedback class.

This is my script, but nothing changes.

$("#stime").change(function (e) {
    var time = $("#stime").val();

    $("#stime").find(".form-control-feedback").append("* Check Format Time (HH:mm)");
});

CodePudding user response:

You want to use .siblings() instead of .find() because the .form-control-feedback element isn't a child of #stime, but instead a sibling.

You're also probably looking for .text(), not .append()

$("#stime").change(function (e) {
  var time = $("#stime").val();
  $("#stime").siblings(".form-control-feedback").text("* Check Format Time (HH:mm)");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <input name="stime" type="text"  id="stime" placeholder="00:00" required maxlength="5">
  <span class='form-control-feedback'></span>
</div>

CodePudding user response:

you can do the following

$("#stime").change(function () {
    $(this).siblings(".form-control-feedback").append("* Check Format Time (HH:mm)");
});

but since the input is unique by id I'd rather assign the id to the span as well. Then

$("#stime").change(function () {
    $("#form-control-feedback").append("* Check Format Time (HH:mm)");
});

or

$("#stime").change(function () {
    $("#form-control-feedback").text("* Check Format Time (HH:mm)");
});

if you don't want to append but rather replace

  • Related