How to get each checked checkbox using jQuery - javascript

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);
});

Related

How show checkbox checked data-img on list

I have this field
<input class="red-heart-checkbox " name="photo[]" type="checkbox" value="<?php echo $id; ?>" id="<?php echo $id; ?>" data-img="<?php echo $imageURL; ?>"/>
And I would like to make a list of image with url image from the data-img checked but I only have values with this code :
<script>
$(function() {
var masterCheck = $("#masterCheck");
var listCheckItems = $("#devel-generate-content-form :checkbox");
masterCheck.on("click", function() {
var isMasterChecked = $(this).is(":checked");
listCheckItems.prop("checked", isMasterChecked);
getSelectedItems();
});
listCheckItems.on("change", function() {
var totalItems = listCheckItems.length;
var checkedItems = listCheckItems.filter(":checked").length;
if (totalItems == checkedItems) {
masterCheck.prop("indeterminate", false);
masterCheck.prop("checked", true);
}
else if (checkedItems > 0 && checkedItems < totalItems) {
masterCheck.prop("indeterminate", true);
}
else {
masterCheck.prop("indeterminate", false);
masterCheck.prop("checked", false);
}
getSelectedItems();
});
function getSelectedItems() {
var getCheckedValues = [];
getCheckedValues = [];
listCheckItems.filter(":checked").each(function() {
getCheckedValues.push($(this).val());
});
$("#selected-values").html(JSON.stringify(getCheckedValues));
}
});
</script>
My result is on :
<li class="list-group-item" id="selected-values"></li>
And looks like this :
Is it possible to have url image instead of the value , or use the result with de database to have url image ?
Thanks a lot !
Two solutions in my opinion,
The one you already suggested, i.e. use a db call
try passing imageURL in value

How to verify only one checkbox is selected from checkbox list

Here i am retriving data from database and i am doing insert,update and delete of data using checkbox.My problem is when i click more than two checkbox than also i am moving to update.php page but what i actually want is that when i click on update button first it will check that only one checkbox is selected from list if not than alert message should display like select only one checkbox. please help.Thanks in advance
Here i have put my code.
<!DOCTYPE html>
<html>
<head>
<title>Insert Update Delete</title>
</head>
<body>
<form name="dataform" id="data" action="" method="get">
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db_new", $connection);
$query=mysql_query("select * from student_info");
echo "<table>";
while($row=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>"; ?> <input type="checkbox" id="box" name="num[]" class="other" value="<?php echo $row["id"];?>" /> <?php echo "</td>";
echo "<td>"; echo $row["roll_no"]; echo "</td>";
echo "<td>"; echo $row["name"]; echo "</td>";
echo "<td>"; echo $row["division"]; echo "</td>";
echo "<td>"; echo $row["std"]; echo "</td>";
echo "<td>"; echo $row["gender"]; echo "</td>";
echo "<td>"; echo $row["subject"]; echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="insert" value="insert"/>
<input type="submit" name="update" value="update"/>
<input type="submit" name="delete" value="delete"/>
</div>
</form>
<?php
if(isset($_GET["insert"]))
{
$box = $_GET['num'];
$count =count($box);
if ($count == 0){
header('Location:insert.php');
}
elseif($count == 1){
header('Location:data.php');
}
}
?>
<?php
if (isset($_GET['update'])){
$box = $_GET['box'];
$count =count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:update.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
echo $id;
header("location:update.php?id=".$id);
}
}
}
?>
<?php
if (isset($_GET['delete'])) {
$box = $_GET['num'];
$count = count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:data.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
mysql_query("delete from student_info where id = $id");
}
}
}
?>
</body>
</html>
You could use a radio button for this instead of a checkbox.
see sample here
Use Radio Instead of CheckBox
Or if you must use a checkbox do this:
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
I would use a radio button, however I don't know your situation so here's a solution using jQuery. You want to select all of the checkboxes that are checked then see if the length of that array is greater than one. Here's the javascript code you'll need and a jsbin if you want to look at it.
http://jsbin.com/qakuzajaza/edit?js,output
$("#submitbutton").click(function() {
var count = $("input[type=checkbox]:checked").length;
if (count > 1) {
alert("Only 1 can be selected");
} else {
// submit data
}
});
1. Try this, it will not allow you to check only one checkbox at a time.
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('#ckeckboxlistId').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
The approaches are more or less similar. Try this:
submitForm(); //according to an event you prefer (click some button or anchor , no button over $ .ajaks.
function submitForm(){
var tag = document.getElementById("tdForm");
var chkbx = $(tag).find("input[type='checkbox']:checked").length;
if (chkbx !== 0) {
if (chkbx > 1) {
alert("more then 1");
}else{
alert("form submited"); //$(tag).submit();
}
}else{
if (chkbx === 0) {
alert("nothing cecked");
}
}
};
Tested works for me. Hope it helps!
While I think the radio buttons or previous validation, and interception of errors on the rules for completing the form, are much more affordable.

html form inside php tag radio button validation?

how to validate the radio buttons. at least one options is selected.
the code will display a question and 3 answers as radio buttons from a database.
for example
what is Captial of India?
O New Delhi
O Chennai
O Mumbai
user has to select a correct answer. if the user not selecting any answer and click submit, I want to show a message "please answer the question".?
my code:
<?php
$today=date("Y-m-d");
mysql_query("SET CHARACTER SET utf8");
echo "<form method='post' id='submit' action='checkresult.php' dir='rtl'>";
$sql="SELECT * FROM cquestions where showdate='$today' limit 1";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['cqtext'] . "</p>";
$sql2="SELECT * FROM canswers where cqid=".$row['cqid'];
$result2=mysql_query($sql2);
while($row2=mysql_fetch_assoc($result2))
{
echo "<input type='radio' name='".$row['cqid']."' value='".$row2['cqans']."' />".$row2['aatext'];
echo"<br>";
}
}
echo"<br>";
echo"<br>";
echo"<br>";
echo "<div align='left' style='padding-left:160px;'>";
echo"<input type='submit' id='submit' name='submit' value='التالي' />";
echo "</div>";
echo "</form>" ;
?>
how to do it using javascript?
I tried like this.
echo "<form name='q1' method='post' id='submit' action='checkresult.php' onsubmit='return validateForm()';>";
echo "<input type='radio' id='a' name='".$row['cqid']."' value='".$row2['cqans']."' />".$row2['aatext'];
and this worked.
function validateForm()
{
var a = document.getElementById('a');
if ( (a.checked == false ) )
{
alert ( "Please answer the question ");
return false;
}
}
it worked.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("submit").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked == 'No')
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1)
{
ShowAlert = ShowAlert + ThisRadio + ' يرجى الإجابة على السؤال\n';
}
}
}
if (ShowAlert != '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
</script>
It didn't worked because of your JS function declaration which is wrong.
This is the right way of declaring a function. Remember to use the curly brackets.
function validateForm() {
var a = document.getElementById('a');
if (!a.checked)
{
alert ( "please answer the question ");
return false;
}
}
Also, if you want us to know why the php code isn't working we need to look at the source code.
once try this..
if(isset($_POST['submit']))
{
if($row['cqid']=="")
{
echo "Please select an answer";
}
}
I don't know whether it works or not.. but once give it a try...
echo "<form name='q1' method='post' id='submit' action='checkresult.php' onclick='return validateForm(e)';>";
<script type="text/javascript">
function validateForm(e) {
e.preventDefault();
var a = document.getElementById('a');
if ( (a.checked == false ) )
{
alert ( "please answer the question ");
return false;
}
}
</script>
Try this
if the user not selecting any answer and click submit, I want to show a message "please answer the question".? ... how to do it using javascript?
You will need to check that any one of the radio buttons is checked. A convenient way to do this is give them all a class, then retrieve all the DOM elements with that class name.
Here is an example.
<form onsubmit="return validateForm();">
<!-- note how all the radio buttons have the same name -->
<input type='radio' class="question" name='question' value='New Delhi' />
<input type='radio' class="question" name='question' value='Chennai' />
<input type='radio' class="question" name='question' value='Mumbai' />
<input type="submit" value="submit" />
</form>
<script>
function validateForm() {
var questions = document.getElementsByClassName('question'),
i = 0;
for (; i < questions.length; i++) {
if (questions[i].type === 'radio' && questions[i].checked) {
alert('You selected ' + questions[i].value
+ ', the form will submit now');
return true;
}
}
alert('please answer the question');
return false;
}
</script>
However if you have multiple forms on the page you should take care that the radio button belongs to the form that is being submitted.

My Jquery code still won't work , yet nothing is shown in firebug

I posted this code minutes 15 mins ago and I did get help for the preventDefault issue , but now I'm not getting my alerts to work , yet firebug doesn't show any error related to this code .. May i ask where I'm going wrong ,
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.preventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.preventDefault();
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
I suggest changing your design. Using <form> codes and posting isn't always the best way of sending your data to another (or the same) page for PHP processing. Instead, switch over to using AJAX code to submit your form.
For one thing, this will allow you to get away from the e.preventDefault kludges. A number of things will iron themselves out if you use the AJAX approach (instead of submitting a form). I can see that you're already using AJAX in your code, but if you're still uncomfortable with it you can check out these other answers:
Form not posting correctly
Place PHP results inside HTML Page
Update data in a DIV
Change your #edit_fields_submit input field from type="submit" to type="button" and use javascript/AJAX to:
Get all the values you would normally submit as a <form>;
Use AJAX to submit them to a PHP file for processing
In the success: function of the AJAX code block, use javascript to send the user over to whatever page you want them to see next
Example:
$('#edit_fields_submit').click(function(event) {
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
alert($('#edit_checkboxes').val()); // doesn't work
var field_data = //you know how to get these values
var project_id = //etc
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/myprocessor.php",
dataType: "json",
data: string,
success: function(data){
document.location.href='yournewpage.php';
}
});
});

Checkbox required on form submission

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;
}
});
});

Categories

Resources