Greedy
Greedy

Reputation: 115

Javascript language switch on same button

I have this part of the code:

JS:

function changeText() {
    document.getElementById('lang').innerHTML = 'default language';
}

HTML:

<p id='lang'> 
    some other language 
    <input type='text' style="font-size: 12px;" onclick='changeText()' value='click me'/>
</p>

"Click me" button works, and switches "default language" to "some other language", but disappears after initial click. I would like to be able to switch back and forth languages on that same button, but i was able only to add another button. Help ?

Upvotes: 1

Views: 1711

Answers (3)

Elheni Mokhles
Elheni Mokhles

Reputation: 4001

It disappears because your input is in the <p></p>. You need to get the input out of the p.

<p id='lang'> some other language</p>
<input type='text' style="font-size: 12px;" onclick='changeText()' value='click me'/>

Another thing : why you're using an input type text to do the work of a button ?

Upvotes: 0

fuyushimoya
fuyushimoya

Reputation: 9813

Because <input> is inside the <p>, so when you replace the innerHTML with new value, it'll also be overwrite.

some other language in <p> is still a node, so you can pick it up using p.childNodes[0], then change its node value to the new one. Which, won't affect the input now.

And if you want to toggle text, you have to include logic to switch between the languages.

function changeText()
    {
     var p  = document.getElementById('lang');
     var langList = ['some other language', 'default language'];
     // Get current index
     var idx = p.dataset.lang;
     idx = idx == null ? 0 : parseInt(idx, 10);
      
     // Switch to next language
     idx = (idx + 1) % langList.length;
     p.dataset.lang = idx;
      
     p.childNodes[0].nodeValue = langList[idx];
    }
<p id='lang'> some other language <input type='text' style="font-size: 12px;" onclick='changeText()' value='click me'/></p>

Upvotes: 0

idmean
idmean

Reputation: 14875

The problem is that you replace the whole inner HTML, the whole content of the p tag including the button.

You will want to put the content you want to replace in a sub element, for instance a span:

<p> 
   <span id='lang'>some other language</span> 
   <input type='text' style="font-size: 12px;" onclick='changeText()' value='click me'/>
</p>

You can now safely replace the content of the span because you have no other needed HTML markup in there.

You can achieve the same by using additional JavaScript but changing the markup is possibly the easiest and most clear solution.

Hint: Putting click handlers into the onclick attribute is considered bad coding style. (Why is using onClick() in HTML a bad practice?)

Upvotes: 1

Related Questions