I have this code where a user types a phrase or word and it reverses the string, but my problem is that I would like for it to display the results in the very same text box the user typed the word. Here's my code:
function revme() { var textb = document.getElementById("textb"); var str = textb.value; var str1 = ""; l = str.length; for (i = l; i >= 0; --i) { str1 = str1 + str.substring(i, i + 1); } document.getElementById("results").innerHTML = str1; }
Please enter your text <br> <input type="text" id="textb"> <p id="results"></p> <input type="button" value="Reverse" onclick="revme()">
I tried to do it like this:
document.getElementById("textb").innerHTML = str1;
But that doesn't work. Any Ideas?
The problem with your code is that you're setting the innerHTML
of textbox. Instead, you should set the value
of the textbox.
var textb = document.getElementById("textb"); function revme() { var str = textb.value; var str1 = ""; l = str.length; for (i = l; i >= 0; --i) { str1 = str1 + str.substring(i, i + 1); } textb.value = str1; // ^^^^^^^^^^^^^^^^ }
Please enter your text <br> <input type="text" id="textb"> <p id="results"></p> <input type="button" value="Reverse" onclick="revme()">
Another way to reverse string will be using string
and array
functions as follow. I'll also recommend you to use addEventListener
instead of inline event handlers.
var textb = document.getElementById("textb"); document.getElementById('reverse').addEventListener('click', function() { var str = textb.value || ''; textb.value = str.split('').reverse().join(''); }, false);
Please enter your text <br> <input type="text" id="textb"> <p id="results"></p> <input type="button" id="reverse" value="Reverse" />
Let it done done by this .. i am getting the exact reverse pattern of any value i enter.
<html>
<body>
Please enter your text<br>
<input type="text" id="textb">
<p id="results"></p>
<input type="button" value="Reverse" onclick="revme()">
</body>
<script>
function revme() {
var textb = document.getElementById("textb");
var str = textb.value;
var str1 = "";
l = str.length;
for (i = l ; i >=0 ; --i ){
str1 = str1 + str.substring(i,i+1);
}
document.getElementById("textb").value= str1;
}
</script>
</html>
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.