开发者

JS/JQuery - Using checkbox to change background colors of random elements

开发者 https://www.devze.com 2023-04-11 11:38 出处:网络
I have a dynamically produced photo gallery using ASP. Each photo is contained by a <div> with the photoID as the ID and a checkbox to select that photo. For example:

I have a dynamically produced photo gallery using ASP. Each photo is contained by a <div> with the photoID as the ID and a checkbox to select that photo. For example:

<div id="<%=rs("photoID")%>">
<img src="blah.jpg"><br>
<input type="checkbox" id="checkbox_<%=rs("photoID")%>" onclick="selectPhoto(<%=rs("photoID")%>)">
</div>

I will then have a JS function that changes that particular DIVs background color to show it is selected, I just made this up, hope it's right:

function selectPhoto(id)
{
if (document.getElementById('checkbox_'+id).checked == true)
{
document.getElementById(id).style.backgroundColor = '#0066CC';
}
if (document.getElementById('checkbox_'+id).checked == false)
{
document.getElementById(id).style.backgroundColor = '#FFFFFF';
}
}

So, if the checkbox that was clicked, was checked, then change BG 开发者_StackOverflow社区color to something that highlights my photo. If the checkbox that was clicked, was not checked, then change back to the original color.

This seems simple enough to achieve but where I'm now getting confused, is how I could change all the highlighted photos back to white, in one go, if a user clicks an 'un-select' checkbox called 'unselect_all'.

I'm thinking of a function that will gather all checked checkboxes in that form 'gallery_form', get the ID's of the checkboxes, minus the 'checkbox_' prefix, then change all those DIV ID's back to the original color, white.

Or... I could alter the DIVs to have an ID prefix, like 'photo_<%=rs("photoID")%>', find all DIV Id's that have that prefix, then change the background colors.

Is this the best way to accomplish this? If it is, has anybody got any suggestions/snippets to get me going? Although I can see the function in my head, my basic JS skills don't allow me to write such a script, without a little help..

Many thanks


I would suggest using classes to make your life easier. So each of the colors would be a css class i.e

.blue{
   background-color: #0066CC; 
}

.white{
   background-color: #FFFFFF; 
}

function selectPhoto(id){
   var checkbox = $('#checkbox_'+id); 
   var div = $('#'+id);        

   if( checkbox.is(':checked') )
       div.addClass('blue'); 
   else 
       div.addClass('white'); 
}

Then for unselect all

function unselectAll(){
   $('.blue').removeClass('blue').addClass('white'); // find all divs with class blue and add class white. 
}


Assuming you have no other checkboxes whose ID begins with "checkbox_":

$('input[id^="checkbox_"]').removeAttr('checked');

0

精彩评论

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