JavaScript change image on input key press

Larry Brister
Larry Brister used Ask the Experts™
on
I have a web page with an input where users enter 8 characters.

I would like to be able .... after the FIRST character entered in an input tag

To "set" an image

The first character will always be numeric in a alphanumeric string

So...
In txtUserInput a user enters a "1"

The image would be set... and display with a src="../img/sub/1Href.jpg"

The user types In a "2"

The image would be set... and display with a src="../img/sub/2Href.jpg"

<input id="txtUserInput" runat="server" class="field" placeholder="Enter Code" style="border: solid 1px #c1c1c1; width: 70%; font-size: 50px; float: left;" />

<img src="#" alt="" />
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2017
Commented:
HTML5
Look at the input element.I set a onkeypress function returning only nymbers and maxlenght value equal to ONE ie 1or 2 or 3....or 9.
<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->

<input id="myNum" type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' maxlength="1"/>
<img id="myImg" src="#" alt="" />
  <script>
//Define and set str var
   var str="Href.jpg";
//Add keyup event at input element
document.getElementById('myNum').addEventListener('keyup',function(){
//Set the src value depending on num
   document.getElementById('myImg').setAttribute('src','../img/sub/'+this.value+str );
});
  </script>
<!-- End your code here -->
</body>
</html>

Open in new window

Distinguished Expert 2017
Commented:
Altrenative with JQUERY:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->

<input id="myNum" type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' maxlength="1"/>
<img id="myImg" src="#" alt="" />
  <script>
  $('#myNum').on('keyup',function(){  
  $('#myImg').attr('src', '../img/sub/'+$(this).val()+'Href.jpg');
});
  </script>
<!-- End your code here -->
</body>
</html>

Open in new window

Larry Bristersr. Developer

Author

Commented:
Hey Leonidas
  It works on the character but there is a limit on characters

I need to keep typing.  The change is on the first character only.
Larry Bristersr. Developer

Author

Commented:
Thanks!   Got me on the right track.

I added this to set it to first character

this.value.charAt(0)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial