Checkbox required on form submission - javascript

Was trying to find something how to make checkboxes required.
Like required="required" as below this is how I generate my checkboxes
I would appreciate any help on how to do so. My system requires at least one checkbox to be checked. also would like if it won't be a popup. alert('');
<?php
$result=mysql_query("SELECT * FROM tbl_tourism_type order by type_name ");
$i=1;
while($row = mysql_fetch_array($result)){
echo '<input type="checkbox" name="type"
value='.$row['type_id'].' id='.$row['type_id'].'>'.'
<label for='.$row['type_id'].'
class="fil_lab">'.$row['type_name']. '</label>';
if($i%5==0)
{
$i = 0;
echo '<br><br>';
}
$i++;}
?>

Well there are tons of jQuery validation plugins out there, but t his is pretty simple to do:
$("form").on('submit', function (e) {
if (!$(":checkbox:checked").length) {
$("form").append("<div>Check at least one box please</div>");
e.preventDefault();
}
});

$('.form').submit(function(){
var checked = true ;
$('.check_box').each(function(){
if(!$(this).is(':checked')) {
checked = false;
}
if(!checked){
$('.error_div').html("please select at least on check box");
return false;
}
});
});

Related

calling js function in php when checkbox is checked

I'm creating some checkboxes via php like this:
$query = mysql_query("SELECT user FROM login");
while ($row = mysql_fetch_assoc($query)) {
$readUser = $row['user'];
if($readUser == "mod"){}
else {
$checkboxUserId = $readUser;
echo "<p><input class='filled-in item' type='checkbox' id='$checkboxUserId' checked='checked' /><label for='$checkboxUserId'>Team: $checkboxUserId</label></p>";
}
some code after this, I do:
I'm drawing some polygones via a Javascript function based on some values I stored in a database.
$query = mysql_query("SELECT * FROM questionAnswers");
while ($row = mysql_fetch_assoc($query)) {
$readUser = $row['user'];
$someMoreVars = $row['var']; //like ten more or that
if ($user == "mod"){
if ($readUser == "mod"){}
else{
echo "drawUserPoly($someMoreVars, $iDontWantToListThemAll, $thatsJustForTheContext)";
//Some More Code here
}
Now the problem: I need to check for the checkboxes which one is checked so i don't draw them and this needs to be updated live (like: checking the checkbox again and the polygon will be drawn, uncheck the checkbox and the polygon is not drawn).
my attempt:
else {
if(isset($_POST['$readUser'])){
echo "drawUserPoly($someMoreVars, $iDontWantToListThemAll, $thatsJustForTheContext)";
}
}
my second attempt:
else {
if($_POST['$readuser'] == 'checked'){
echo "drawUserPoly($someMoreVars, $iDontWantToListThemAll, $thatsJustForTheContext)";
}
}
Remember that all PHP code is executed before the page is sent to the browser, and that PHP cannot see whatever happens on the page after that. As a result, PHP and the HTML do not interact live.
Your solution is to use Javascript which does see what's happening in the HTML, and CSS styles. A simple approach would be to register an event listener on the checkbox checked event in JavaScript. When the box is unchecked, just hide the polygon by applying a CSS class that has display:none style. When checkbox is checked, remove that class and the polygon will reappear.

Updating a MySQL Field when a checkbox is clicked using jQuery, AJAX and PHP

I need a checkbox to update a MySQL field from a 1 to 0 and vice versa when clicked. I want to use jQuery/AJAX and PHP to do this so I do not have to have the page re-loaded. I placed the code below but I cannot get it to work. I feel that I am very close.
Note: I know mysql_query is deprecated. This is an older project and I will be converting it soon but need this to work for now.
The form:
if($list_row['online'] == 0) {
echo '<input type="checkbox" name="online" id="' . $list_row['id'] . '" data-toggle="toggle" checked> ';
} else {
echo '<input type="checkbox" name="online" id="' . $list_row['id'] . '" data-toggle="toggle"> ';
}
The jQuery:
<script>
$('.online').mousedown(function() {
var id = $(this).attr('id');
if($(this).attr('checked')) {
var online = 1;
} else {
var online = 0;
}
$.ajax({
type:'GET',
url:'processes/process_item_online.php?',
data:'id= ' + id + '&online='+online
});
});
</script>
The PHP:
include '../connect.php';
// START IF LOGGED IN
session_start();
if (!isset($_SESSION['is_logged_in'])) {
header("location: login.php");
} else {
$login = true;
}
$id = $_GET['id'];
$online = $_GET['online'];
mysql_query("UPDATE `store_items` SET online=$online WHERE id='$id'");
Problem solved by using the $(document).ready(function() { code before the jquery.

Bootstrap3 toggle switch with ajax update to mysql

Hello and thank you for looking.
I have the slick new toggle effect for the checkbox (boostrap3) in place.
I would like to update my database each time the toggle is clicked.
A simple On or OFF entry will be perfect. Ofcourse it needs to be without
a page refresh.
HTML:
<span id="setQuickVar1">Enable Notifications<input id="QuickVar1" type="checkbox" class="make-switch" data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF" ></span>
<div id="resultQuickVar1"></div>
Javascript/Ajax:
var handleQuickSidebarToggler2 = function () {
// quick sidebar toggler
$('#setQuickVar1').click(function (e) {
$('body').toggleClass('make-switch');
$.post("quickRightSidebarDBUpdate.php", {"quickVar1a": $('#QuickVar1').val()},
function(data) {
$('#resultQuickVar1').html(data);
});
});
}
(I added a div to show my results)
quickRightSidebarDBUpdate.php
if ($_POST['quickVar1a']):
$quickVar1a = $_POST['quickVar1a'];
$query2 = "UPDATE test SET field1 = " . $quickVar1a . "";
endif;
I think I am close since the Db does get an entry of "on". I can set the check box to "checked" or leave it as above in the code and each time it enters "on" to the BD.
I'm not sure how the entry of "on" is even generated.
Thank you greatly for any help.
ANSWER BELOW...Well it works..but it's not pretty
I did an ugly version of what I want and it's working. Here's what I did.
HTML
<span id="setQuickVar1">Enable Notifications<input id="QuickVar1" type="checkbox" class="make-switch" data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF" <?php echo $checked;?> ></span>
<div id="resultQuickVar1"></div>
Javascript/Ajax
// Handles quick sidebar toggler2
var handleQuickSidebarToggler2 = function () {
// quick sidebar toggler
$('#setQuickVar1').click(function (e) {
$('body').toggleClass('make-switch');
//$(this).toggleClass('make-switch');
$.post("quickRightSidebarDBUpdate.php", {"quickVar1a": $('#QuickVar1').val()},
function(data) {
$('#resultQuickVar1').html(data);
});
});
}
quickRightSidebarDBUpdate.php
$sql = "SELECT * FROM `test`";
$result = mysql_query($sql)or die(mysql_error());
$r = mysql_fetch_array($result);
echo 'Finding:'.$r['quickVar1'].'<br>';
if($r['quickVar1'] == 'ON')
$quickVar1a = 'OFF';
else
$quickVar1a = 'ON';
$sql = "UPDATE test SET quickVar1 ='" . $quickVar1a . "'";
$result = mysql_query($sql)or die(mysql_error());
echo 'Updating To: '.$quickVar1a.'<br>';
Do it like this:
JS
$('#setQuickVar1').on('click', function() {
var checkStatus = this.checked ? 'ON' : 'OFF';
$.post("quickRightSidebarDBUpdate.php", {"quickVar1a": checkStatus},
function(data) {
$('#resultQuickVar1').html(data);
});
});
PHP
if (isset($_POST['quickVar1a'])):
$quickVar1a = $_POST['quickVar1a'];
$query2 = "UPDATE test SET field1 = '" . $quickVar1a . "'";
endif;
code not tested, let me know if does NOT work :)
Update 2
Here is a proper SQL query for the toggle:
$query2 = "UPDATE test SET field1 = '".$quickVar1a."' where field1 != '".$quickVar1a."'";
try this:
HTML:
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<input type="checkbox" data-toggle="toggle" data-onstyle="success" data-offstyle="danger" id="h_activate" name="host" value="1">
<p id="just"></p>
Ajax:
$('#h_activate').on('change', function(event, state) {
var checkStatus = this.checked ? 'ON' : 'OFF';
$.ajax({
url:"check.php",
method:"POST",
data:{"toogle": checkStatus},
success:function(data){
$('#just').html(data);
}
});
});
PHP: check.php
var_dump($_POST); //Allow you to see if php page getting post value or not.
$toogle= mysqli_real_escape_string($conn,$_POST['toogle']);
if(isset($toogle) && $toogle!=='')
{
$sql="update status set toogle='$toogle'";
if($conn->query($sql))
{
echo 'updated success';
}
}else{
echo 'error: not updated';
}
instead of directly updating the database first check ajax giving any response or not.

How to get each checked checkbox using jQuery

I have the following:
PHP/HTML CODE:
<?php
$c = 1;
foreach($this->contactos as $contacto){
?>
<div class="uk-form-row">
<label for="contactopadrino<?php echo $c; ?>" class="uk-form-label"><?php echo $contacto->email; ?></label>
<input class="contactopadrinos" name="contactopadrino[]" id="contactopadrino<?php echo $c; ?>" type="checkbox" value="<?php echo $contacto->email; ?>" />
</div>
<?php
$c++;
}
?>
jQuery CODE:
function validarEnviarDescuento(){
$('#errorofertacontainerdescuento').css('display','none');
$('#errorofertadescuento').html('');
var validar = 0;
var vacio = 0;
for(var e=1; e<6; e++){
var email = $("#email_contactopadrino"+e).val();
if(!validarEmail(email) && email != ''){
validar++;
}
if(email != ''){
vacio++;
}
}
if(!vacio){
$('input:radio:checked').each(function () {
var $this = $(this);
if ($(this).prop('checked')) {
return true;
}
});
$('#errorofertadescuento').append('<li>' + '<?php echo JText::_('COM_CSTUDOMUS_ERROR_SIN_SELECCIONAR'); ?>' + '</li>');
$('#errorofertacontainerdescuento').css('display','block');
return false;
}
if(validar){
$('#errorofertadescuento').append('<li>' + '<?php echo JText::_('COM_CSTUDOMUS_ERROR_EMAIL_INCORRECTO'); ?>' + '</li>');
$('#errorofertacontainerdescuento').css('display','block');
return false;
}
else{
return true;
}
}
Im trying to go through each input and if one is checked it should return true and submit but what I have done is not working.
You don't need to use each. instead use cobination :checked and length
return $('input:checkbox:checked').length;
It will return true if anyone of the checkbox button has checked
You can use :checked with selector to get all radio buttons those are checked.
$('input:radio:checked')
Description: Matches all elements that are checked or selected, jQuery docs
If you want to check if atleast one radio is checked then you can use length
if($('input:radio:checked').length)
{
}
For iterating through checked radio you can use each
$('input:radio:checked').each(function(){
alert(this.value);
});

jquery $.post not working unless debugging

I have simple form for updating the stock of products, it uses datatables to generate rows for all the items in the database. I can update the stock correctly using the form when I set a break point in the function, but if I remove the break point it stops working.
HTML form:
<form id="updateStock">
<input id="Penguincard" type="text" value="200">
<input type="submit" onclick="updateStock("Penguincard", "Penguin card");" value="Update">
</form>
Javascript:
function updateStock(id, item){
var idS = "#" + id;
var newStock = $(idS).val();
$.post("URL",{item: item, stock: newStock},
function(result){
alert(result);
});
return false;
}
PHP:
<?php
ini_set('display_errors', 1);
// Adds a new item to the database
require('common.php');
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["item"])){
echo 'item is blank';
exit();
}else
{
$item = test_input($_POST["item"]);
// check if item only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$item))
{
echo 'item reg';
exit();
}
}
if (empty($_POST["stock"])) {
echo 'stock is blank';
exit();
}else
{
$stock = test_input($_POST["stock"]);
// check if stock only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$stock))
{
echo 'stock reg';
exit();
}
}
}else{
//don't run unless post
echo 'Not post';
exit();
}
$stmt = $db->prepare('UPDATE `stock` SET `stock`=:stock WHERE `item`=:item');
// bind the parameters to the insert after sanitizing them
$stmt->bindParam(':item', $item);
$stmt->bindParam(':stock', $stock);
//execute the insert
$status = $stmt->execute();
if( $status ){
echo 'Item added successfully!';
exit();
}
//sanitizing function
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
EDIT: by not working I mean it seems to run the onClick function but doesn't submit the post.
From the answers it seems that debugging was allowing the post to be submitted before the default form action occurred, therefore making it working.
You're never actually suppressing the click functionality of the submit button; you return false; from the updateStock function, but that doesn't actually do anything (the onclick attributes code itself needs to be returning false. As a result the form is being submitted and the AJAX request is cancelled.
The simplest fix would be this:
<input type="submit" onclick="return updateStock('Penguincard', 'Penguin card');" value="Update">
However, it would probably be better to use jQuery to bind the event handler:
$(':submit').on('click', function(e) {
e.preventDefault();
updateStock('Penguincard', 'Penguin card');
});
This line is the issue:
onclick="updateStock("Penguincard", "Penguin card");"
The double quotes inside the attribute are the problem. Convert them to single quotes. This is one reason why people like to use the jQuery delegates to add click events.

Categories

Resources