Javascript to change button text
i need a javascript function to be called on certain button click, upon that click the button name will change. ie,
<input type=butt开发者_Python百科on id = button1 value=boy onclick=function(boy,girl)>
i need the javascript function to take 2 parameters and check if the value of the button is the first paramter, then the value will become the 2nd and vice versa.
so if i press the button and it says BOY, it will become Girl and if i press the button and it says Girl it will become boy! using javascript please thx.
var foo = function(a,b,c){
if(a.value==b){
a.value=c;
}
else{
a.value=b;
}
};
and for the button
<input type="button" id="button1" value="boy" onclick="foo(this,"boy","girl")">
see here: http://jsfiddle.net/w9ed8/
or:
<input type=button id = button1 value=boy onclick="changeMe(this)">
<script>
function changeMe(obj){
if(obj.value == "boy"){
obj.value = "girl"
}else{
obj.value = "boy"
}
}
</script>
Or
<input type=button id = button1 value=boy onclick="changeMe(this, 'boy' , 'girl')">
<script>
function changeMe(obj , param1 , param2){
if(obj.value == param1 ){
obj.value = param2
}else{
obj.value = param1
}
}
</script>
There are many ways to do this, but by getById
function showed below you will have a portable function to access to DOM elements by id
:
<html>
<script type="text/javascript">
function getById(a) {
if (document.getElementById && document.getElementById(a)) {
return document.getElementById(a)
} else {
if (document.all && document.all(a)) {
return document.all(a)
} else {
if (document.layers && document.layers[a]) {
return document.layers[a]
} else {
return false
}
}
}
}
function myfunc()
{
getById("button1").value =(getById("button1").value=="boy")?"girl":"boy";
}
</script>
<head>
</head>
<input type="button" value="boy" id="button1" onclick="myfunc();" />
</html>
<input type=button id=button1 value=boy onclick='test(this,boy,girl)'>
<script>
function test(Sender,boy,girl){
Sender.value = Sender.value == boy ? girl : boy;
}
</script>
function change()
{
if((document.getElementById("button1").value)=="Boy")
{
document.getElementById("button1").value="Girl"
}
else
{
document.getElementById("button1").value="Boy"
}
}
精彩评论