How can I limit the count of multiselect? Like I want the user to select atmost 3 elements from multiselect. If more than 3 are selected then I ll throw him an error...
Here is a complete example, showing the HTML of a simple form and the PHP that only allows up to three options being selected - and an added bonus of client-side JavaScript to explain how the user can be informed of their error before the form is submitted.
You can use JavaScript to stop the user checking more than three options, but note that client-side validation can easily be avoided, so you will still need to use PHP to verify on the server.
HTML
<!doctype html>
<head>
<meta charset="utf-8">
<title>Multiselect example</title>
</head>
<p>Please make a selection below (maximum three options!)</p>
<form method="post">
<select name="selection[]" multiple="multiple">
<!-- Put <option> elements here -->
</select>
<input type="submit">
</form>
<script src="Script.js"></script>
JavaScript (in Script.js):
var formChange = function(e) {
var i,
num = 0,
// Obtain a list of all selected options:
nodeList = this["selection[]"];
// Loop over all options, count how many are selected.
for(i = 0; i < nodeList.length; i++) {
if(nodeList[i].selected) {
num ++;
}
}
if(num > 3) {
alert("Please do not select more than three options");
e.preventDefault();
}
};
// Attach the same function to the change and submit event.
// This will alert the user of more than three selections
// as the fourth is selected, or as the form is submitted.
// ... it will also not allow the form to submit with
// more than three checked boxes.
document.forms[0].addEventListener("change", formChange);
document.forms[0].addEventListener("submit", formChange);
PHP:
if(isset($_POST["selection"])) {
if(count($_POST["selection"]) > 3) {
die("Error: More than three check boxes were checked.");
}
// $_POST["selection"] is an array of the checked values.
}
A multiselect element in PHP returns an array, so it's simply a matter of comparing the count() of the returned array against the maximum value you want to allow and generating some kind of error if the count exceeds the limit (throw an exception, trigger an error, etc).
If you want to do it server-side, look at the count() function. E.g.,
HTML:
<form ...>
<select name="options[]" multiple="multiple">
<!-- options here ... -->
</select>
...
</form>
PHP:
<?php
if (isset($_POST['options']) && count($_POST['options']) <= 3) {
// OK
} else {
// Not OK
}
?>
Take a look at this js function, suppose your multiselect object is "muSelect"
function checkSelected() {
var i;
var count = 0;
for (i=0; i<muSelect.options.length; i++) {
if (muSelect.options[i].selected) {
count++;
}
if (count > 3) {
alert("cant select more than three options";
// any other additionnal processing
}
}
}
and then you can add this function as onClick event
I know that this is an old question but if someone is trying to do the same thing now and looking for answers is best to write a current answer for this one. The best way at the moment is with AJAX (as long as I know):
HTML: form.html
<form id="myForm" action="validate.php?q=1">
<select name="options[]" multiple="multiple">
<!-- options here ... -->
</select>
...
</form>
PHP: validate.php
<?php
switch($_REQUEST['q']){
case 0:
if(isset($_REQUEST['options']) && count($_REQUEST['options']) <=3){
echo true;
}else{
echo false;
}
break;
case 1:
if(isset($_POST['options']) && !empty($_POST['options'])){
if(count($_POST['options']) <= 3){
//OK
}else{
//NOT OK
}
}
break;
}
?>
JavaScript(jQuery): script.js
var form = $("#myForm");
var options = $("#select_menu option")
var selected = [];
$(options).each(function(key,option){
if(option.selected){
selected[key] = option;
}
});
$.ajax({
url: "validate.php",
method: "GET",
data: {
options: selected,
q: 0
},
success: function(Response){
if(Response === true){
//OK
}else{
//NOT OK
}
}
});
Please correct me if I have error somewhere.
Related
I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>
here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here
I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).
My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.
My Javascript:
<script type="text/javascript">
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
My form:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
Search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.
You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form
$college = mysql_real_escape_string($_GET['college']);
if ($college != "" || $college != null || $college != -1)
{
//DO STUFF
}
NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection!
more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
So accordingly in search.php change the
$ac_term = "%".$_GET['term']."%";
to
$ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)
so maybe something like this would help: Submit Event Listener for a form
function evtSubmit(e) {
// code
e.preventDefault();
// CHECK IT HERE!
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');
In my project i handled it by checking on focus-out , if the text entered in the autocomplete field actually matches my dropdown options.If not i will simply remove it.
change: function(event, ui) {
if (!ui.item) {
this.value = '';
}
}
See my full example here-Jquery auto comp example
it has an embeded fiddle,you can check the fiddle directly also
http://jsfiddle.net/9Agqm/3/light/
Add this code to your JavaScript before you instantiate your autocomplete object:
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
This will make it so whenever the menu appears, you have a list of current items the user can choose from stored in $.ui.autocomplete.currentItems. You can then use that to check against when you are submitting your form. Of course the way you implement this part is up to you depending on how dynamic your form is, but here is an example that requires hard-coding a list of input fields and making sure they all have ids.
//create an object that contains every input's id with a starting value of false
var inputs = {college: false};
//for each input, you will have a function that updates your 'inputs' object
//as long as all inputs have id's and they all are using autocomplete,
//the first line could be written as: $('input').change(function(){ and the
//function would only need to be written once. It is easier to maintain
//if you use seperate id's though like so:
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
//when you submit, check that your inputs are all marked as true
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
return false; //one or more input does not have correct value
}
}
//all inputs have a value generated from search.php
$('#myform').submit();
});
UPDATE
The only difference between our two examples (one that works and one that doesn't) is that you are binding other events to your input element, onclick and onblur. So by changing our listener from change to blur as well mostly fixes the problem. But it creates a new problem when the enter/return key is pressed to submit the form. So if we add a listener for that specific event then everything works out ok. Here is what the code looks like now:
var validateInfo = function(elem){
var id = elem.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(elem).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
}
$('#college').on('blur', function(){
validateInfo(this);
}).on('keydown', function(e){
if(e.which == 13){ //Enter key pressed
validateInfo(this);
}
});
Add a hidden input element to your form:
<input type="hidden" name="selectedvalue" id="selectedvalue" />
Add a select event handler to your autocomplete, that copies the selected value to the hidden input:
$("#college").autocomplete({
source: "search.php",
minLength: 5,
select: function (event, ui) {
$('#selectedvalue').val(ui.item.value);
}
});
Then just ignore the auto-complete form input in posted data.
As this is javascript, your only concern should be if an item is selected from the autocomplete list. This can simply be done by setting a variable to true on select and false on change. That is enough to prevent regular users from continuing without selecting a school. To prevent abuse you need to check the value server side after posting. All normal user will pass that check.
If I understand the question correctly, this is something I have encountered before. Here is some code pretty much lifted straight out of another project. I have used a local datasource here but the project this is lifted from uses remote data so there won't be a difference:
var valueSelected = '';
$('#college').autocomplete({
source: ['collegeA', 'collegeB', 'collegeC']
}).on('autocompletechange autocompleteselect', function (event, ui) {
if (!ui.item) {
valueSelected = '';
} else {
$('#submit').prop('disabled', false);
valueSelected = ui.item.label;
}
}).on('propertychange input keyup cut paste', function () {
if ($(this).val() != valueSelected) {
valueSelected = '';
}
$('#submit').prop('disabled', !valueSelected);
});
This will programatically enable and disable the submit button depending on whether a value has been selected by the user.
Fiddle here
I would like to make it that when a button is clicked a certain values in a drop down menu appears later on in the same document.
For example if there was a button called Honda and it is clicked it would change the content in a drop down menu to the model details of the car.
How is it possible to do this?
CONTEXT: Webpage on a PHP enabled server
Thanks in advance!
I suggest the simplest solution is a JavaScript. Seems overload to use a framework for such a simple task:
<html>
<head><title>JS example</title></head>
<body>
<script type="text/javascript"><!--
//
var opt_one = new Array('blue', 'green', 'red');
var opt_two = new Array('plaid', 'paisley', 'stripes');
//
function updateTarget() {
var f = document.myform;
var which_r = null;
if (f) {
// first option selected? ("One")
if (f.trigger.value == '1') {
which_r = opt_one;
// ...or, second option selected? ("Two")
} else if (f.trigger.value == '2') {
which_r = opt_two;
// no known option, hide the secondary popup
} else {
f.target.style.display = 'none';
}
// did we find secondary options for the selection?
if (which_r) {
// reset/clear the target pop-up
f.target.innerHTML = '';
// add each option
for (var opt in which_r) {
f.target.innerHTML += '<option>' + which_r[opt] + '</option>';
}
// display the secondary pop-up
f.target.style.display = 'inline';
}
}
} // updateTarget()
//-->
</script>
<form name="myform" action="#">
<select name="trigger" onchange="updateTarget();">
<option>Select one...</option>
<option>-</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select name="target" style="display:none;">
</select>
</form>
</body>
</html>
You could do this using jquery, with one PHP backend script to populate the values of the select box based on the button you click.
Some simple HTML to start with:
<form action="script.php">
<button id="Honda" onClick="loadModelsForMake('Honda');">Honda</button>
<button id="Toyota" onClick="loadModelsForMake('Toyota');">Toyota</button>
<select name="models" id="models">
<option value="">Please Select A Make</option>
</select>
</form>
Then you'd need a PHP script set up to give you the appropriate list of values given the make selected. Best to do this on the back-end so you don't hardcode things in your javascript code. Make a file called models.php. It will look for the "make" variable defined in the query string and return a JSON array of models for that make. If you want you can hook this up to a database of models for makes so you're not hard coding things:
<?php
$models = array();
if ($_GET['make'] == 'Toyota') {
models[] = array(id: 0, name: 'Matrix'});
models[] = array(id: 1, name: 'Yaris'});
} else if ($_GET['make'] == 'Honda') {
models[] = array(id: 0, name: 'Civic'});
models[] = array(id: 1, name: 'Pilot'});
}
echo json_encode($models);
?>
Lastly you need the JQuery to hook it all together. Add this script block to your page:
<script type="text/javascript" charset="utf-8">
function loadModelsForMake(carMake) {
$.getJSON("/models.php", {make: carMake, ajax: 'true'}, function(json){
var options = '';
for (var i = 0; i < json.length; i++) {
options += '<option value="' + json[i].id+ '">' + json[i].name + '</option>';
}
$("models").html(options);
})
}
</script>
Of course make sure you include the base jQuery script in your page ;)
You would need to use AJAX and jQuery has functions built in that can make this simpler.
As for the button itself, you would use onclick to start the request.
<input type="button" onclick="carRequest('honda');" />
i have check box array like this
for($j=1;$j<=10;$j++)
<input type="checkbox" name="chkLimit[]" id="chkLimit_<?php echo $j;?>" value="<?php echo $j;?>" />
i got 10 check box
and i write the jquery code like this...
$(document).ready(
function (){
setLimitSelection();
}
);
function setLimitSelection(){
$('input[name="chkLimit[]"]').limitSelection(
{
// number of items to limit to
limit: 4,
// on error, do this
onfailure: function (n){
$("#idCheckboxMsg").html(
"You can not select more than " + n + " items."
);
return false;
},
// on success, do this
onsuccess: function (n){
$("#idCheckboxMsg").html("");
return false;
}
}
);
$('select[name="selLimit[]"]').limitSelection(10);
}
$("input.chkLimit").click(function() {
var numSelected = $("input.chkLimit[]:checked").length;
var numLeft = 10 - parseInt(numSelected);
$("#statusBox").html("You have "+numSelected+" CD's selected.<br>You have "+numLeft+" selections left.");
});
what i want is: user can't select more than 4 check boxs
thanks
I haven't tested this, but it should get the job done for you:
$(function(){
$("#myCheckboxes input[type='checkbox']").change(
var checked = $("#myCheckboxes input[type='checkbox'][checked]").length;
if(checked == 4){
$("#myCheckboxes input[#type='checkbox']").not(":checked").attr('disabled',true);
}else{
$("#myCheckboxes input[#type='checkbox']").not(":checked").attr('disabled',false);
}
)
});
Every time the checked state of a checkbox changes, it looks at how many checkboxes are checked. If there are 4, it disables the unchecked boxes, otherwise it enables them. This assumes that they all live in a container called #myCheckboxes
Looks like #inkedmn had some syntax errors but the comment box just isn't adequate to elaborate. So, here's what I think he's trying to do:
$(function(){
$("#myCheckboxes input[type='checkbox']").change(function() {
var checked = $("#myCheckboxes input[type='checkbox']:checked").length;
if(checked == 4){
$("#myCheckboxes input[type='checkbox']")
.attr('disabled',true)
.filter(':not(:checked)')
.attr('disabled',false);
} else {
$("#myCheckboxes input[type='checkbox']").attr('disabled',false);
}
)
});
That should get it done for you.