-3

This code is supposed to return a string from an input, written the other way around but it doesn't work... Can someone help me?

function Change1() {
    document.getElementById("top").innerHTML="Inroduceti cuvantul";
    document.getElemenyById("button1").setAttribute('onclick','StringBackFlip(document.getElementById("insert").value)');
}
function StringBackFlip(str) {
    var res = "";
    var i = str.lenght;
    while (i>0) {
        res += str[i-1];
        i--;
    }
    document.getElementById("result").value=res;
    document.getElementById("top").innerHTML="Introduceti alt cuvant";
}

This is the code. I need help so tell me what I've done wrong.

2 Answers2

0

That is not how you use setAttribute. There should be no equal sign.

setAttribute=('onclick'
           ^^^

Add events with addEventListener.

And also

var i = str.lenght; <-- spelled wrong
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • I actually noticed that after posting the question. In my code it is without the equal sign. However the code doesn't work... – Whitewolf3131 Dec 28 '15 at 15:52
0

You have several syntax errors in your code, but this code does what you asked. I suggest the following really great articles, to give you a better understanding of js and it's beauty and it's quirks

  1. http://bonsaiden.github.io/JavaScript-Garden/
  2. http://devdocs.io/dom/eventtarget/addeventlistener
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

 document.getElementById("button1").addEventListener('click',function(ev){
   var forward = document.getElementById('insert').value;
   var backward = forward.split('').reverse().join('');
   document.getElementById('result').innerHTML = backward;
 });
<p id="top">Introduceti alt cuvant</p>

<input type="text" name="insert" id="insert" value="hello" />  
<button id="button1" type="button">reverse it</button>

<p id="result"></p>
code_monk
  • 9,451
  • 2
  • 42
  • 41
  • The code you gave me is good. The problem I have more than one function which is supposed to run on the same button but if I start the first one and after the second, the first function will also start on the second's one turn. What should I do to fix that? – Whitewolf3131 Dec 28 '15 at 20:10