PDA

View Full Version : How to dynamically change text with an input's value (no refreshing or form submit)



sajtc
02-06-2015, 01:48 AM
I have an input, and when a user types something in it, I'd like for a piece of text that already exists on the page to be updated with that input value. I'd like to have it change without page refreshing or form submission. For example, the text on the page is "I'm going to the store." When the user types "library", "store" is automatically changed to "library." I can't have the sentence in an HTML element; it is its own text node. I came across a JS Fiddle that almost does what I need, but it uses a span to insert the text - http://jsfiddle.net/cTq7K/ As mentioned, I'm not able to have the text in an HTML element, but I'm not sure how to get the string itself and manipulate it.
JavaScript and JQuery solutions would be great. Thanks.



I'm going to the store.
<input type="text">

molendijk
02-06-2015, 03:20 PM
Try this:

<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<title>&nbsp;</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

</head>

<body>
<input id="input_32_1" onmouseover="this.value='';document.getElementById('test').innerHTML=''">I'm going to the
<span id="test"></span>

<script>
$("#input_32_1").keyup(function() {
document.getElementById('test').innerHTML=''; $("#test").text($("#input_32_1").val());
});
</script>

</body>
</html>

sajtc
02-06-2015, 06:07 PM
Thank you for your reply, molendijk. Interesting solution. Is there a way to not use the span at all? I have several instances of text that need to be manipulated in this way, and it would be preferable to not have the extra markup.

molendijk
02-06-2015, 06:57 PM
Is there a way to not use the span at all? I have several instances of text that need to be manipulated in this way, and it would be preferable to not have the extra markup.
I doubt it: we need an ID, so we need a HTML-element (here: the span).