more javascript run-ins
I have a li开发者_JAVA百科st of checkboxes. Each have a class, either East or West. I have 2 links currently, Select All, Select None. I'm making 2 new links, Select East, Select West. I'm using the following javascript to select the checkboxes by class:
<script language="JavaScript">
function checkAll(theForm, cName, status) {
for (i=0,n=theForm.elements.length;i<n;i++)
if (theForm.elements[i].className.indexOf(cName) !=-1) {
theForm.elements[i].checked = status;
}
}
</script>
Here is a copy of the onClick:
<a href="" onclick="$('sites').select('input[type=checkbox]').each(function(e){if(!e.checked)e.click();}); return false;">Select All</a> |
<a href="" onclick="$('sites').select('input[type=checkbox]').each(function(e){if(e.checked)e.click();}); return false;">Select None</a> |
<a href="" onclick="checkAll(document.getElementById('selectForm'), 'East', this.checked);">East</a> |
<a href="" onclick="checkAll(document.getElementById('selectForm'), 'West', this.checked);">West</a>
The Javascript is not working and reloads my page after clicking my new links. Help please :(
Your missing the return false
from your East & West links, thus the reload. Also I don't think you should be passing the checked status of the checkbox into the function. I think your if
should be something like
if (theForm.elements[i].className.indexOf(cName) !=-1) {
// select the ones that are in the class
theForm.elements[i].checked = true;
}
else {
// deselect the ones that are not in the class
theForm.elements[i].checked = false;
}
** UPDATE: **
In that case you would want to pass in the state of the checkboxes in. You will essentially need to change the behaviour so that each link becomes a toggle. So you don't do anything to the other classes, and you invert the status of the class the user clicked on.
if (theForm.elements[i].className.indexOf(cName) !=-1) {
// toggle the checked status of the current class of checkboxes
theForm.elements[i].checked = !state;
}
You can also replace
onclick="checkAll..."
to
onclick="return checkAll..."
And your checkAll
function must return false
Is just another way to do it.
精彩评论