set total number of checkbox in array - php

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.

Related

Using Ajax to store checkbox in database

Update: The code is working. I had an incorrectly named table in my php file.
I have the following that I've found from some snippets during my searches for help however I cannot get it to work. What I am trying to accomplish is clicking a check box and it automatically populate a row in my database that I can refer to on any other page. Right now when I click the checkbox, nothing happens.
HTML
<td><input type="checkbox" name="<?php echo $brow['WorkOrder']; ?>" value="<?php echo $brow['WorkOrder']; ?>"></td>
Ajax
<!-- Checkbox storage -->
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('functions/checkBox.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
});
</script>
functions/checkBox.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
include("../../db.php");
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO TemporaryCheckBoxID (WorkOrder) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
To check whether checkbox is checked or not use as below and try
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).is(":checked");
if(checked){
var value = $(this).val();
$.post('functions/checkBox.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
});

Javascript add checkbox values on click

I am using this JavaScript code:
<script>
function add(total, this_chk_bx)
{
var thetotal = form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//add if its checked
form2.thetotal.value = Number(thetotal)+Number(total);
}
else
{
//subtract if its unchecked
form2.thetotal.value = thetotal-total;
}
}
</script>
And then I have PHP/HTML code that selects from a table in a database and adds checkboxes with the values as a float field in the database.
What I'm trying to do is to make it so that when the checkboxes are ticked, it adds the values up and displays them in a text field, and then when they are unchecked, it removes that value from the field.
For some reason, when subtracting, it's displaying odd numbers and incorrectly.
I have created a fiddle here so you can also see the HMTL: http://jsfiddle.net/j08691/kHxmG/4/
Any ideas on what I can do to get it working properly?
***jsFiddle Demo***
I suggest you read this posts:
Elegant workaround for JavaScript floating point number problem
Is JavaScript's Floating-Point Math Broken?
Write a function to correct the number for you:
function correctNumber(number) {
return (parseFloat(number.toPrecision(12)));
}
And pass your final number to this function:
function add(total, this_chk_bx) {
var thetotal = (form2.thetotal.value * 1);
var total = total * 1;
if (this_chk_bx.checked == true) {
//add if its checked
form2.thetotal.value = correctNumber(thetotal + total);
} else {
//subtract if its unchecked
form2.thetotal.value = correctNumber(thetotal - total);
}
}
Don't forget to check the jsFiddle Demo.
function add(total, this_chk_bx)
{
var thetotal = form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//add if its checked
form2.thetotal.value = ((thetotal*100)+(total*100))/100;
}
else
{
//subtract if its unchecked
form2.thetotal.value = ((thetotal*100)-(total*100))/100;
}
}

Force selection with JQuery autocomplete

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

jQuery get() php button submit

I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});

Dynmaic checkboxs validation

I want to validate Checkbox in javascript, checkboxes is generating dynamically by PHP and name of checkboxes are like "checkbox1" , "checkbox2" ,"checkbox3" i.e. incrementing i++ and these numbers are coming from database, it might be first time only 2 rows fetched and next time 112 rows.
How i can make sure in javascript that atleast one checkbox must be selected.
// When you use jQuery... somehow like this
$('form').submit(function() {
if ($("input:checked").length == 0) {
alert('Please check at least one checkbox!');
return false;
}
});
If you do not want to use any js framework, then just give the same name attribute to the checkboxes
Assuming your checkboxes are named test
var chkBoxes = document.getElementsByName("test");
var chked=0;
for(var i=0;i<chkBoxes.length;i++)
{
if(chkBoxes[i].checked)
chked++;
}
if(chked===0)
alert("Please select a value");
Added as per the sample code specified in the comment
function isChecked()
{
var i=1;
var chkd=0;
var elem = "";
var chkForMoreChkBoxes=true;
do{
elem=document.getElementById("check_"+i);
try{
if(elem.checked)
{
chkd++;
}
i++;
}
catch(err)
{
chkForMoreChkBoxes=false;
}
}while(chkForMoreChkBoxes)
if(chkd===0)
{
alert("Please select a value");
return false;
}
}

Categories