当前位置: 动力学知识库 > 问答 > 编程问答 >

html - onclick() javascript attribute staying in check with checkboxes

问题描述:

I have a pretty simple javascript program here that changes the image of another image on click to show that it is selected, however i can not seem to be capable of keeping it in sync with my check boxes, occasionally it will come off sync and cause issues with my php form

code:

<script type="text/javascript">

function func()

{

var img1= document.getElementById("img1");

if(img1.name == "on")

{

img1.src = "images/" + "img1a.jpg";

img1.name = "off";

}

else

{

img1.src = "images/" + "img1.jpg";

img1.name = "on";

}

}

</script>

</head>

<body>

<form>

<p align="center">

<input type="checkbox" name="interest1" id="interest1" value="x">

<input type="checkbox" name="interest2" id="interest2" value="x">

<input type="checkbox" name="interest3" id="interest3" value="x"></p>

<p align="center">

<label for="interest1" id="label-interest1"><img src="images/img1.jpg" width="781" height="800" onclick="func()" id="img1" /></label>

<label for="interest2" id="label-interest2"><img src="/images/img2.jpg" width="781" height="800" /></label>

<label for="interest3" id="label-interest3"><img src="/images/img3.jpg" width="781" height="800" /></label></P><!-- code making checkbox be an image-->

</form>

网友答案:

Instead of checking if(img1.name == "on"), you can check the checkbox.checked state of the corresponding checkbox.

EDIT: For kicks and giggles, here is a jsFiddle example using jQuery.

分享给朋友:
您可能感兴趣的文章:
随机阅读: