I have a form that allows the user to select up to X amount of options from a multi-select field. If the user selects an item greater than the X items it prompts and de-selects the last selected item.
There is an issue when the warning message has been thrown by a previous multi-select.
The form have 4 mult-selects, so if its thrown on the third mult-select or the max number has already been reached by a previous mult-select it will throw the error for the next multi-select regardless of whether the user chooses the correct number.
Here is a code snippet. The rest of the selects on the page are built the same way but use different names:
<select multiple name="seasons[]" size="6" id="seasons" onChange="countSelected(this,5)">
<option value=0>Hold CTRL to select more than one</option>
<?
$ftw = mysql_query("SELECT s.seasonId, s.type FROM seasons s ORDER BY开发者_运维技巧 s.seasonId ASC");
while ($line = mysql_fetch_array($ftw)) {
$queried = mysql_query("SELECT seasonId FROM selectedSeason where seasonId = '$line[0]' AND id = '$objItem->itemId'");
if(mysql_fetch_row($queried))
echo "<option selected value=\"$line[0]\">". $line[1] ."</option>";
else
echo "<option value=\"$line[0]\">". $line[1] ."</option>";
}
?>
</select>
Here is the javascript to warn:
var selectedOptions = [];
function countSelected(select,maxNumber){
for(var i=0; i<select.options.length; i++){
if(select.options[i].selected && !new RegExp(i,'g').test(selectedOptions.toString())){
selectedOptions.push(i);
}
if(!select.options[i].selected && new RegExp(i,'g').test(selectedOptions.toString())){
selectedOptions = selectedOptions.sort(function(a,b){return a-b});
for(var j=0; j<selectedOptions.length; j++){
if(selectedOptions[j] == i){
selectedOptions.splice(j,1);
}
}
}
if(selectedOptions.length > maxNumber){
var throwAlert = true;
select.options[i].selected = false;
selectedOptions.pop();
}
}
if(throwAlert == true){
alert('You may only choose '+maxNumber+' options!!');
document.body.focus();
}
}
seasons needs to be seasons[] so it can post multiple values to PHP. I have no issue posting or retrieving data just with the javascript. The error occurs in IE, FF, and Safari but not Chrome...alas.
Any ideas would be invaluable.
i guess u need to make the selectedOptions into a multidimensional array something on the lines
selectedOptions[0][0] /// indicating to first select box option 1
selectedOptions[0][1] /// indicating to first select box option 2
something on those lines should work.
Edit: if you want to do it the quick and dirty way have selectedOptions1[] selectedOptions2[] etc and use an if else statement to work with the correct array at the start of the js function.
精彩评论