Reputation: 43
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?
Upvotes: 1
Views: 260
Reputation: 141829
<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>
Upvotes: 1
Reputation: 3445
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';
});
Upvotes: 1