Linggo, Marso 6

Javascript: Limit Checkbox

Having a hard time in error trapping your PHP program?
First, I already post javascript codes that allow the users to input number only.
Today, I'll give you an idea on how to 'limit checkboxes in javascript'.
The following html codes will be used for input purposes. The example will limit the user to select 3 menus only.
So here's an easy step to do it:
1st Step: Insert this javascript code inside you head tag.

<script type="text/javascript">
function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup
var limit=limit
for (var i=0; i<checkgroup.length; i++){
checkgroup[i].onclick=function(){
var checkedcount=0
for (var i=0; i<checkgroup.length; i++)
checkedcount+=(checkgroup[i].checked)? 1 : 0
if (checkedcount>limit){
alert("You can select "+limit+" main dish only")
this.checked=false
}
}
}
}
</script>



2nd Step: Copy the following on notepad or macromedia dreamweaver.

<form id="maindish" name="maindish">
Select 3 main dish only:
<input type="checkbox" name="menu" /> Chicken Alexander<br />
<input type="checkbox" name="menu" /> Baby Back Ribs<br />
<input type="checkbox" name="menu" /> Vacareta<br />
<input type="checkbox" name="menu" /> Roast Beef<br />
<input type="checkbox" name="menu" /> Roast Pork<br />
</form>

Last Step: Put the following code on the last part of your page or codes.
<script type="text/javascript">
checkboxlimit(document.forms.maindish.menu, 3)
</script>
Note:maindish is the form name, menu is the checkboxes name and 3 is the limit.

0 comments:

Mag-post ng isang Komento

 
Powered by Blogger