1

How can I channge this inline javascript to Unobtrusive JavaScript?

<input type="button" value="Text1" onclick="this.value=this.value=='Text1'?'Text2':'Text1';">

Thank you!


Thank you for your answears, but it doesn't work. My codes are:

php

<input id=\"button1\" type=\"button\" value=\"Text1\">

js file

document.getElementById('button1').onclick = function(){
    this.value = this.value === 'Text1' ? 'Text2' : 'Text1';
}

or

document.getElementById('button1').addEventListener('click', function () {
    this.value = (this.value === 'Text1') ? 'Text2': 'Text1';
}, false);

I tried everything you told me, but it didn't work! Neither with jquery.

Have I forgotten something?

4
  • that's not even valid inline JS? Commented Sep 13, 2013 at 7:30
  • "this.value=this.value=='Text1'?'Text2':'Text1';" there was a missing " ' " Commented Sep 13, 2013 at 7:31
  • Works fine here: jsfiddle.net/j08691/zw2Fp. Where are you placing the code? Commented Sep 15, 2013 at 2:56
  • Yup, this was the error. I fixed. Commented Sep 27, 2013 at 20:08

2 Answers 2

1

Add an id to the input and do this:

document.getElementById('somebutton').addEventListener('click', function () {
    this.value = (this.value === 'Text1') ? 'Text2': 'Text1';
}, false);

or with jQuery

$('#somebutton').on('click', function () {
    this.value = (this.value === 'Text1') ? 'Text2': 'Text1';
});
Sign up to request clarification or add additional context in comments.

Comments

1
<input type="button" value="Text1" />
<script>
  (function(){
    var inputs = document.getElementsByTagName('input');
    return inputs[inputs.length - 1];
  })() // returns the input element
  .onclick = function(){
    this.value = this.value === 'Text1' ? 'Text2' : 'Text1';
  }
</script>

This script has to be placed immediately after the element (or at least somewhere before the next input element on the page).

Demo

If you are okay with adding an id to your element that script becomes a bit simpler and you can put it anywhere after the input exists (such as right before your closing </body> tag:

<input id="somename" type="button" value="Text1" />

Script:

<script>
  document.getElementById('somename').onclick = function(){
    this.value = this.value === 'Text1' ? 'Text2' : 'Text1';
  }
</script>

Demo

3 Comments

i want to know the purpose of (function(){ in your reply cause i never use that. can't it be (inputs[inputs.length -1]).onclick ... ?
Yeah, that would work jist as well. As long as it's all inside the function so that the vraiable inputs doesn't become global
i see. by that way we can prevent the variable scope very local. ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.