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?
-
that's not even valid inline JS?NDM– NDM2013年09月13日 07:30:38 +00:00Commented Sep 13, 2013 at 7:30
-
"this.value=this.value=='Text1'?'Text2':'Text1';" there was a missing " ' "firemeaway– firemeaway2013年09月13日 07:31:45 +00:00Commented Sep 13, 2013 at 7:31
-
Works fine here: jsfiddle.net/j08691/zw2Fp. Where are you placing the code?j08691– j086912013年09月15日 02:56:12 +00:00Commented Sep 15, 2013 at 2:56
-
Yup, this was the error. I fixed.tolias63– tolias632013年09月27日 20:08:32 +00:00Commented Sep 27, 2013 at 20:08
2 Answers 2
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';
});
Comments
<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).
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>
3 Comments
inputs doesn't become global