Must check last three check boxes to submit - javascript

Below is my list of check boxes that is part of my php form. I need to write a script where only the last three check boxes must be checked for the form to be successfully submitted. I have looked at other similar questions but can't seem to find what I am truly looking for and I am having trouble to write the script.
<input type="checkbox" name="checkbox" value="Send email request">Would you like to receive weekly new via email?<br>
<input type="checkbox" name="checkbox" value="Agree to T&C">I agree to the Terms and Conditions<br>
<input type="checkbox" name="checkbox" value="No Criminal Records">I have no criminal associations<br>
<input type="checkbox" name="checkbox" value="No Business with any other company">I have no personal or business relationship with any other company<br>

You do not need to use any JavaScript.
Simply add a required attribute to the input elements.
<input type="checkbox" required="required" name="checkbox" value="Send email request">Would you like to receive weekly new via email?<br>
Take a look here for more info: http://www.the-art-of-web.com/html/html5-checkbox-required/
If you want a custom message or response, then you will need to use JavaScript to handle this.

Alternatively, you could use jQuery to check if it is indeed that the last 3 checkboxes or are checked (required) before submission. Consider this example:
<form method="POST" action="index.php" id="form">
<input type="checkbox" name="checkbox[]" value="Send email request">Would you like to receive weekly new via email?<br>
<input type="checkbox" name="checkbox[]" value="Agree to T&C">I agree to the Terms and Conditions<br>
<input type="checkbox" name="checkbox[]" value="No Criminal Records">I have no criminal associations<br>
<input type="checkbox" name="checkbox[]" value="No Business with any other company">I have no personal or business relationship with any other company<br>
<input type="submit" name="submit" />
</form>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').submit(function(e){
var count = 0;
var required_indeces = [1,2,3];
$('input[type=checkbox]').each(function(index, element){
if($.inArray(index, required_indeces) !== -1 && $(this).is(':checked')) {
count++;
}
});
if(count < 3) {
e.preventDefault();
}
});
});
</script>

The checkboxes need to have different names. Using the same name means you are only storing the value of the last checked box. Try one of these two options (for PHP):
<input type="checkbox" name="checkbox[]" value="Send email request">Would you like to receive weekly new via email?<br>
<input type="checkbox" name="checkbox[]" value="Agree to T&C">I agree to the Terms and Conditions<br>
<input type="checkbox" name="checkbox[]" value="No Criminal Records">I have no criminal associations<br>
<input type="checkbox" name="checkbox[]" value="No Business with any other company">I have no personal or business relationship with any other company<br>
Then, to check that the last three are checked:
if (!isset($_POST['checkbox'][1], $_POST['checkbox'][2], $_POST['checkbox'][3])) {
echo 'One of the last 3 NOT checked!';
}
OR:
<input type="checkbox" name="checkbox1" value="Send email request">Would you like to receive weekly new via email?<br>
<input type="checkbox" name="checkbox2" value="Agree to T&C">I agree to the Terms and Conditions<br>
<input type="checkbox" name="checkbox3" value="No Criminal Records">I have no criminal associations<br>
<input type="checkbox" name="checkbox4" value="No Business with any other company">I have no personal or business relationship with any other company<br>
Then:
if (!isset($_POST['checkbox2'], $_POST['checkbox3'], $_POST['checkbox4'])) {
echo 'One of the last 3 NOT checked!';
}

Related

Modify Url from Search Form

I've search form that have part like this :
<input type="checkbox" id="checkboxlist-field-[29]" name="CategoryField[9][]" checked="checked" value="bed">
<input type="checkbox" id="checkboxlist-field-[30]" name="CategoryField[9][]" checked="checked" value="almari pakaian">
<input type="checkbox" id="checkboxlist-field-[31]" name="CategoryField[9][]" value="tv">
<input type="checkbox" id="checkboxlist-field-[32]" name="CategoryField[9][]" checked="checked" value="ac">
<input type="checkbox" id="checkboxlist-field-[33]" name="CategoryField[9][]" checked="checked" value="wifi-internet">
<input type="checkbox" id="checkboxlist-field-[34]" name="CategoryField[9][]" checked="checked" value="meja cermin rias">
<input type="checkbox" id="checkboxlist-field-[36]" name="CategoryField[9][]" checked="checked" value="sekamar berdua">
When they're checked and form is submited, it generates url into something like this :
http://localhost/index.php/category/akomodasi?CategoryField[9][]=bed&CategoryField[9][]=almari pakaian&CategoryField[9][]=ac&CategoryField[9][]=wifi-internet&CategoryField[9][]=meja cermin rias&CategoryField[9][]=bisa pasutri&CategoryField[9][]=sekamar berdua&CategoryField[10]=1
The search works fine, but I want to modify the url into something like this :
http://localhost/index.php/category/akomodasi?CategoryField[9]=bed,almari pakaian,ac,wifi-internet,meja cermin rias,bisa pasutri,sekamar berdua&CategoryField[10]=1
So values of CategoryField[9] are separated with ",".
How to modify the url? btw, I'm using Yii2 Framework.
Thank you.
Do you just want to get the category fields separated with ","? or actually need to change the url? If it's the first option you can do that with:
$categoryField = implode(', ', $_GET['CategoryField'][9]);

Assigning numerical values to a Survey in html

I have a questionnaire with radio buttons and checkboxes which I want to grade. Almost all of them have this format:
<input type="radio" name="1" value="Да"
onclick="document.getElementById('pls').setAttribute('required', true)" required>Да
<input type="radio" name="1" value="Не"
onclick="document.getElementById('pls').removeAttribute('required')">Не </br>
I need both the name and value attributes to carry their current purpose, so I cannot use them.
Is there a way to still assign some point values to the different answers and get they summed client side. Then ill add them as a different column in a database. The problem is just having an attribute carry the value of the answer.
EDIT:
This is the full format of 2 questions:
<b>1.QUESTION?</b></br>
<input type="radio" name="1" value="Да" data-points="1" onclick="document.getElementById('pls').setAttribute('required', true)" required>Да
<input type="radio" name="1" value="Не" data-points="0" onclick="document.getElementById('pls').removeAttribute('required')">Не </br>
<input type="radio" name="1" value="Пропуснах да се огледам" onclick="document.getElementById('pls').removeAttribute('required')">Пропуснах да се огледам </br>
<i>COMENT?</i> </br>
<textarea name="edno" id="pls"></textarea></br>
</br>
<b>2.QUESTION?</b></br>
<input type="radio" name="2" value="Да" data-points="1" onclick="document.getElementById('2a').removeAttribute('required')" required>Да
<input type="radio" name="2" value="Не" data-points="0" onclick="document.getElementById('2a').setAttribute('required', true)">Не </br>
<i>COMMENT</i> </br>
<textarea id="2a" name="dve"></textarea></br></br>
Now I need when I have option one ДА checked to add 1 point and when НЕ is checked to add 0 points to the score. I hope this clears it.
Use data-attributes:
<input type="radio" name="1" value="Да" data-points="10" onclick="changePoints(this); document.getElementById('pls').setAttribute('required', true)" required>Да
<input type="radio" name="1" value="Не" data-points="5" onclick="changePoints(this); document.getElementById('pls').removeAttribute('required')">Не
So you can get them with javascript:
function changePoints(el)
{
var points = el.dataset.points;
alert(points);
}
Demo
Remember: For any kind of data you need to set in an element, use data- attributes. Is not nice to use any other default attribute for that.

Validating if atleast one checkbox is checked or one input field is filled

I need better validation logic, where some Checkboxes and some input fields are grouped together.
The user either have to check at least one checkbox or have to fill at least one input box.
If a checkbox is checked or an input field is filled then the complete group is validated.
What will be the best possible way to validate such a situation?
e.g
<input class="checkbox" type="checkbox" name="check-deal" value="1" grouped="deal" >
<input class="checkbox" type="checkbox" name="check-deal" value="2" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="3" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="4" grouped="deal">
<input class="input-group" type="text" name="deal-name1" value="" grouped="deal">
<input class="input-group" type="text" name="deal-name2" value="" grouped="deal">
I have defined an extra attribute grouped for all input and checkboxes that should be grouped togather
but getting no idea how to validate the group as best practice.
DEMO
Point No.1 : There isn't any attribute called grouped for html as of my knowledge but I would suggest you to use data-* prefixed attribute names like data-grouped or data-anyname which is valid
Point No.2 : I rather categorized your checkboxes and textboxes into separate divs and below is how it is:
<div class="chkbox">
<input class="checkbox" type="checkbox" name="check-deal" value="1" />
<input class="checkbox" type="checkbox" name="check-deal" value="2" />
<input class="checkbox" type="checkbox" name="check-deal" value="3" />
<input class="checkbox" type="checkbox" name="check-deal" value="4" />
</div>
<div class="txtbxs">
<input class="input-group" type="text" name="deal-name1" value="" />
<input class="input-group" type="text" name="deal-name2" value="" />
</div>
<button class="btnValidate">Validate</button>
Point No.3 : Below is how you can validate using jquery
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length; //get checkbox checked length
var filledText=$(".txtbxs .input-group").val()!="";
//get bool value whether any of the text box is filled or not
if(chkLength || filledText) //check with or condition
alert('valid')
else
alert('invalid');
});
UPDATE
DEMO
As #AkshatG pointed in his answer the discrepancy was there in my answer so I've edited it and here is the updated solution.
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length;
var filledText=false; //First set it to false
$.each($(".txtbxs .input-group"),function(index,value){
if($(value).val()!="")
{
filledText=true//if it finds any value then set it to true
return;//break from $.each
}
})
if(chkLength || filledText)
alert('valid')
else
alert('invalid');
});
You first need to take count of each validations. And then check if any of the two has count greater than 0 or not. Guruprasad's answer won't work if you enter text on second textbox because it won't filter all the textboxes. You have to use filter function for this :
$("input[type='text'],textarea").filter(function() {
return $(this).val() != "";
}).length;
Here's a jsfiddle :
http://jsfiddle.net/myfLgpdv/
Hope this helps.

PHP : insert multiple check boxes values into one MySQL column

I want to write a simple PHP function to insert values of 10 and 20 check boxes. Now, the issue is: should I insert all values in a single column of MySQL table or should I go with the separate table?
My main goal is to insert the values of multiple checkboxes into MySQL and then update them. If I checked 7 checkboxes, and after some time I want to update from 7 to 5, how it will remove values from table column?
Please help me with some kind simple PHP example and what type of MySQL fields should I add, becuase I want to insert checkbox value which should in digital and the label of check boxes in other field.
Here is the HTML I have
<form method="post" action="">
Games You Like: <br/>
<input type="checkbox" name="games[]" value="1"><label>Football</label><br>
<input type="checkbox" name="games[]" value="2"><label>Basket Ball</label><br>
<input type="checkbox" name="games[]" value="3"><label>Pool</label><br>
<input type="checkbox" name="games[]" value="4"><label>Rugby</label><br>
<input type="checkbox" name="games[]" value="5"><label>Tennis</label><br>
<input type="checkbox" name="games[]" value="6"><label>Cricket</label><br>
<input type="checkbox" name="games[]" value="7"><label>Table Tennis</label><br>
<input type="checkbox" name="games[]" value="8"><label>Hockey</label><br>
<input type="submit" name="submit" value="submit">
</form>
Try this whole example,
Table Structure
CREATE TABLE IF NOT EXISTS `games` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`game_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
<?php
include_once("yourconfig.php"); //include your db config file
extract($_POST);
$check_exist_qry="select * from games";
$run_qry=mysql_query($check_exist_qry);
$total_found=mysql_num_rows($run_qry);
if($total_found >0)
{
$my_value=mysql_fetch_assoc($run_qry);
$my_stored_game=explode(',',$my_value['game_name']);
}
if(isset($submit))
{
$all_game_value = implode(",",$_POST['games']);
if($total_found >0)
{
//update
$upd_qry="UPDATE games SET game_name='".$all_game_value."'";
mysql_query($upd_qry);
}
else
{
//insert
$ins_qry="INSERT INTO games(game_name) VALUES('".$all_game_value."')";
mysql_query($ins_qry);
}
}
?>
<form method="post" action="">
Games You Like: <br/>
<input type="checkbox" name="games[]" value="1" <?php if(in_array(1,$my_stored_game)){echo "checked";}?>><label>Football</label><br>
<input type="checkbox" name="games[]" value="2" <?php if(in_array(2,$my_stored_game)){echo "checked";}?>><label>Basket Ball</label><br>
<input type="checkbox" name="games[]" value="3" <?php if(in_array(3,$my_stored_game)){echo "checked";}?>><label>Pool</label><br>
<input type="checkbox" name="games[]" value="4" <?php if(in_array(4,$my_stored_game)){echo "checked";}?>><label>Rugby</label><br>
<input type="checkbox" name="games[]" value="5" <?php if(in_array(5,$my_stored_game)){echo "checked";}?>><label>Tennis</label><br>
<input type="checkbox" name="games[]" value="6" <?php if(in_array(6,$my_stored_game)){echo "checked";}?>><label>Cricket</label><br>
<input type="checkbox" name="games[]" value="7" <?php if(in_array(7,$my_stored_game)){echo "checked";}?>><label>Table Tennis</label><br>
<input type="checkbox" name="games[]" value="8" <?php if(in_array(8,$my_stored_game)){echo "checked";}?>><label>Hockey</label><br>
<input type="submit" name="submit" value="submit">
</form>
this is just basic example and query i have added in this example, you can learn from this basic example and i think this is very useful for you... if useful than give correct answer for this solution
use implode function to convert returned array into a string an then insert it into database as normal
if(isset($_POST['submit'])){
$result = implode(",",$_POST['games']);
}
hopefully this will help you.
Regards
Imran Qasim
I put the game name into the brackets and changed their values to true:
<form method="post" action="">
Games You Like: <br/>
<input type="checkbox" name="games[Football]" value="true"><label>Football</label><br>
<input type="checkbox" name="games[Basket]" value="true"><label>Basket Ball</label><br>
<input type="checkbox" name="games[Pool]" value="true"><label>Pool</label><br>
<input type="checkbox" name="games[Rugby]" value="true"><label>Rugby</label><br>
<input type="checkbox" name="games[Tennis]" value="true"><label>Tennis</label><br>
<input type="checkbox" name="games[Cricket]" value="true"><label>Cricket</label><br>
<input type="checkbox" name="games[Table]" value="true"><label>Table Tennis</label><br>
<input type="checkbox" name="games[Hockey]" value="true"><label>Hockey</label><br>
<input type="submit" name="submit" value="submit">
</form>
After submission this will result in an array like this:
$_POST["games"] = Array ( [Tennis] => true [Cricket] => true [Table] => true )
// all other values false
You can easily store and later manipulate this array if you store it as an JSON string in your database. For that you need a single varchar or text column.
json_encode($_POST["games"])
// {"Tennis":"true","Cricket":"true","Table":"true"}
Please you try this
<?php
if(isset($_POST['submit']))
{
//in here you get games array
$mygames = $_POST['games'];
}
?>
<form method="post" action="">
Games You Like: <br/>
<input type="checkbox" name="games[]" value="1"><label>Football</label><br>
<input type="checkbox" name="games[]" value="2"><label>Basket Ball</label><br>
<input type="checkbox" name="games[]" value="3"><label>Pool</label><br>
<input type="checkbox" name="games[]" value="4"><label>Rugby</label><br>
<input type="checkbox" name="games[]" value="5"><label>Tennis</label><br>
<input type="checkbox" name="games[]" value="6"><label>Cricket</label><br>
<input type="checkbox" name="games[]" value="7"><label>Table Tennis</label><br>
<input type="checkbox" name="games[]" value="8"><label>Hockey</label><br>
<input type="submit" name="submit" value="submit">
</form>
Firstly very straight to point, I prefer doing names like this from different checkboxes
BasketBall;Cricket;Tennis
You can do that by
implode(";",$array);
and then write that in mySQL table...
To get those values Just use
$array = explode(";",$urVariable);
For different values use
numberOne = $array[1]; // returns Cricket
to change any value use Just get the values and rewrite in ";" form..
I like this as it is simple to implement and do job perfectly!

How to select Multi Check Boxes in HTML using Meteor?

I need to know about selecting multi check boxes in html using meteor.I did a sample.In this sample selecting more than one check box.how to get the selected data and how to store the data in array.Can you please see the below code and suggest me what to do?
The storage of the details in array as suppose arrayname = Bike,car,Computer(these are selected items)
HTML Code:
<form id="cb-form" action="action">
<input type="checkbox" name="owns" value="Bike">Bike<br/>
<input type="checkbox" name="owns" value="Car">car<br/>
<input type="checkbox" name="owns" value="Refridgerator">Refridgerator<br/>
<input type="checkbox" name="owns" value="Mobile">Mobile<br/>
<input type="checkbox" name="owns" value="Tablet">Tablet<br/>
<input type="checkbox" name="owns" value="Computer">Computer<br/>
<input type="submit" value="send" />
</form>
JS Code:
Template.login.events
({
'submit #cb-form' : function (e,t)
{
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed LOGIN Button");
e.preventDefault();
//retrieve the input field values
//here write get multiple check boxes data logic same as above scenario
}
});
HTML:
<template name="login">
<form id="cb-form" action="action">
<input type="checkbox" name="owns" value="Bike">Bike<br/>
<input type="checkbox" name="owns" value="Car">car<br/>
<input type="checkbox" name="owns" value="Refridgerator">Refridgerator<br/>
<input type="checkbox" name="owns" value="Mobile">Mobile<br/>
<input type="checkbox" name="owns" value="Tablet">Tablet<br/>
<input type="checkbox" name="owns" value="Computer">Computer<br/>
<input type="submit" value="send" />
</form>
</template>
JS:
Template.login.events({
'submit #cb-form' : function (event, template) {
event.preventDefault();
var selected = template.findAll( "input[type=checkbox]:checked");
var array = _.map(selected, function(item) {
return item.defaultValue;
});
console.log(array);
}
});
This outputs ["Car", "Refridgerator"] if Car and Refridge are selected. Its just easy use of underscore. Check underscore documentation for further reading.

Categories

Resources