Marcelo Martins
Marcelo Martins

Reputation: 150

Display input field value dynamically using an ID

I've been trying to display an input field value on the screen, as it is been typed by the User. Currently, I have a working prototype, but I couldn't figure out how to add an ID to the generic input field. Adding an ID would help to me target a specific input. I would appreciate any help you can provide.

Here's the HTML code:

<div class="align-center">
    <input id="MyID" type="text" class="form-control" value="" placeholder="Distributor ID">
    <span class="username"></span>
</div>

This is the Javascript:

$("input")
  .keyup(function() {
    var value = $(this).val();
    $("span").text("UserID" + value);
  })
  .keyup();

JSFiddle DEMO: https://jsfiddle.net/UXEngineer/rugf1kku/1/

Upvotes: 1

Views: 209

Answers (2)

squiroid
squiroid

Reputation: 14037

You can directly target specific input like below by getting Id from the element itself $(this)[0].id and apply switch() on for further segregation over input elements:

$("input")
  .keyup(function() {
    var value = $(this).val();
   switch($(this)[0].id){
     case 'MyID':
         $("span").text("UserID" + value);
         break;
   }
  })
  .keyup();

Upvotes: 1

K D
K D

Reputation: 5989

You can try following thing in case you are asking how to write ID selector

$("#MyID")
  .keyup(function() {
    var value = $(this).val();
    $("span").text("UserID" + value);
  })
  .keyup();

Upvotes: 3

Related Questions