开发者

swap yes and no images when either is clicked in html

开发者 https://www.devze.com 2023-01-22 16:08 出处:网络
I have two images yes and no, which change color when clicked, they get highlighted. When clicked on yes_unselect, it needs to change to yes_select and change the id of no to no_unselect. I am fac开发

I have two images yes and no, which change color when clicked, they get highlighted. When clicked on yes_unselect, it needs to change to yes_select and change the id of no to no_unselect. I am fac开发者_高级运维ing two problems.

1. When once clicked the yes_unselect is changing to yes_select but clicking on that again is not changing back to yes_unselect.

2. When yes_unselect changes to yes_select i want id="no" image, no_select to change to no_unselect.

<div id="yes">
<input type="image" src="images/yes_unselect.jpg" id="yes" onClick="if (this.src='images/yes_unselect.jpg') {this.src='images/yes_unselect.jpg';} else {if (this.src='images/yes_select.jpg') {this.src='images/yes_unselect.jpg';}}">
</div>

<div id="no">
<input type="image" src="images/no_select.jpg" id="no" onClick="if (this.src='images/no_select.jpg') {this.src='images/no_unselect.jpg';} else {if (this.src='images/no_select.jpg') {this.src='images/no_unselect.jpg';}}">
</div>


How about something like this in the head:

var theAnswer = undefined; //Global variable for access later.
function changeAnswer(yes) {
    theAnswer = yes;
    //Yes should be a boolean, therefore true==yes, false==no
    var eYes = document.getElementById('yes'),
        eNo = document.getElementById('no');
    eYes.src = ( yes ) ? 'images/yes_select.jpg' : 'images/yes_unselect.jpg';
    eNo.src = ( yes ) ? 'images/no_unselect.jpg' : 'images/no_select.jpg';
}

Of course, you would have to change the conflict in ids. Multiple elements mustn't have the same id, so change the <div>s ids to something like yesDiv and noDiv.

Then the image's onclick can be changeAnswer(true); for the yes button and changeAnswer(false); for the no button. At any place in the script theAnswer can be accessed and will reflect the user's current choice.


Something like this:

<script type="text/javascript">

function swap() {
    var e_yes = document.getElementById("yes");
    var e_no = document.getElementById("no");
    var yes_unselect = 'images/yes_unselect.jpg';
    var yes_select = 'images/yes_select.jpg';
    var no_unselect = 'images/no_unselect.jpg';
    var no_select = 'images/no_select.jpg';

    var result = e_yes.src == yes_unselect;


    e_yes.src = result ? yes_select : yes_unselect;
    e_no.src = result ? no_unselect : no_select;
}


</script>

<div id="div_yes">
    <input type="image" src="images/yes_unselect.jpg" id="yes" onclick="swap()">
</div>
<div id="div_no">
    <input type="image" src="images/no_select.jpg" id="no" onclick="swap()">
</div>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号