How to select Multi Check Boxes in HTML using Meteor? - javascript

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.

Related

Convert checklist auto submit code to checklist with submit button

Here is the checklist radio button code I am using right now, I would like to convert it into a checklist with submit button. Currently, selecting one option will filter the result instantly, but i want to select multiple options and click submit button to get result. I want to use it without effecting the existing functions, as an addon feature.
In short it should allow to select more than one option at a time and submit.
Someone give me an example on how to do this ?
I am trying to learn JQuery and javascript, and need someone's help.
I tried but couldn't get a working result.
I want to use this method
<form>
<ul>
Brand
<li><input name="Samsung" type="checkbox" value="Samsung" /> Samsung</li>
<li><input name="OnePlus" type="checkbox" value="OnePlus" /> OnePlus</li>
<li><input name="Apple" type="checkbox" value="Apple" /> Apple</li>
</ul>
<ul>
RAM
<li><input name="1GB" type="checkbox" value="1GB" /> 1GB</li>
<li><input name="2GB" type="checkbox" value="2GB" /> 2GB</li>
</ul>
<div><button id="apply">Apply</button> <button id="apply">Clear</button></div>
</form>
So that the filter will not apply automatically, this funtion is for mobile pages.
and in PC, the regular auto filter will work.
Example image attached
<h3>Sort</h3>
<div class="list-group-item checkbox">
<label for="radio1">
<input type="radio" id="radio" class="common_selector brand" name="radio" value="Samsung"> Samsung
</label>
<label>
<input type="radio" class="common_selector brand" name="radio" value="Apple" > Apple
</label>
<label>
<input type="radio" class="common_selector brand" name="radio" value="Nokia" > Nokia
</label>
<label>
</div>
The following JQuery function is capturing data from this checklist
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var sort = get_filter('sort');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, sort:sort},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
$('#price_range').slider({
range:true,
min:1000,
max:95000,
values:[1000, 95000],
step:500,
stop:function(event, ui)
{
$('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
$('#hidden_minimum_price').val(ui.values[0]);
$('#hidden_maximum_price').val(ui.values[1]);
filter_data();
}
});
});
</script>
I tried the following code, but it didn't work.
<form>
<input type="checkbox" value="Samsung"> Samsung
<input type="checkbox" value="Apple"> Apple
<input type="button" id="apply" class="common_selector brand" value="Submit">
</form>
$('#apply').click(function(){
filter_data();
});
In the html, convert the radiobuttons to checkboxes. Then create the Apply button. In the script, connect the click event of the Apply button to the filter_data function.
<form>
<input type="checkbox" class="brand" id="samsung" value="Samsung"> Samsung
<input type="checkbox" class="brand" id="apple" value="Apple"> Apple
<button id="apply" class="common_selector brand">Apply</button>
</form>
The script would then be
$('#apply').click(function(){
filter_data();
});
In place of "$('#apply')" you will include a selector for the button, which can be based on the identifier (as above).

How can serialize html form to json object with multipe value

I send my html values to server in below steps:
User submit form
In jquery i get user data
Convert it to object
Create jquery ajax data and object to it
Call ajax form
Notice: I don't want to use jquery serialize because I need get some component like lookup that I created.
My problem is complicated forms that contains multiple values.
For example when I need a form that get uncertain numbers of user emails and so after it, add it object as an array.
<form>
<input name="firstName">
<input name="lastName">
<input type="hidden" name="userId">
<input type="checkbox" name="chkUserRole">
<input type="checkbox" name="chkUserRole">
<input type="checkbox" name="chkUserRole">
<input type="checkbox" name="chkUserRole">
<input name="userPhone">
<input name="userPhone">
<input name="userPhone">
<input name="userPhone">
</form>
Result should be:
{
firstName:"",
lastName:"",
userId:"",
chkUserRole:[],//items that are checked.
userPhone:[],//it can be unlimited phone numbers that user can add field to form.
}
try this:
const form = $("#form");
form.on('submit', function(e) {
e.preventDefault();
const requestData = {
firstName: $("input[name='firstName']").val(),
lastName: $("input[name='lastName']").val(),
chkUserRole: [],
userPhone: []
};
$.each($("input[name='chkUserRole']:checked"), function(){
requestData.chkUserRole.push($(this).val());
});
$.each($("input[name='userPhone']"), function(){
if($(this).val().length) {
requestData.userPhone.push($(this).val());
}
});
console.log(requestData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form id="form">
<input name="firstName">
<input name="lastName">
<input type="hidden" name="userId">
<input type="checkbox" name="chkUserRole" value=1>
<input type="checkbox" name="chkUserRole" value=2>
<input type="checkbox" name="chkUserRole" value=3>
<input type="checkbox" name="chkUserRole" value=4>
<input name="userPhone">
<input name="userPhone">
<input name="userPhone">
<input name="userPhone">
<input type="submit">
</form>
Use the formData object:
var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
request.send(new FormData(formElement));
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Create and Delete input type text if the selected input type checkbox

I have a problem, I need to create or delete as appropriate, a Input type text if a Input type checkbox is selected.
At the moment I can only create the input text, but I manage to find the solution to clear if the checkbox is unchecked.
My HTML code:
<form role="form" action="" method="POST">
<input type="checkbox" class="myCheckBox" name="category[]" value="1">
<input type="checkbox" class="myCheckBox" name="category[]" value="2">
<input type="checkbox" class="myCheckBox" name="category[]" value="3">
<input type="checkbox" class="myCheckBox" name="category[]" value="4">
<input type="checkbox" class="myCheckBox" name="category[]" value="5">
<div class="inputCreate"></div>
<input type="submit" name="" value="Send yours categories">
</form>
And the jQuery code is as follows
var wrapper = $(".inputCreate");
$('.myCheckBox').click(function() {
if ($(this).is(':checked')) {
$(wrapper).append('<input type="text" name="mytext[]" placeholder="">');
}
});
As I can do that by unchecking the checkbox, also delete the input text field ?.
Solution to this problem:
var wrapper = $(".inputCreate");
$(".myCheckBox").change( function(){
if($(this).is(':checked')){
$(wrapper).append('<input type="text" name="mytext[]" placeholder="">');
}
else{
$('.inputCreate :last-child').remove();
}
});
Greeting From Chile.
This should be exactly what you want:
Working Fiddle
var wrapper = $(".inputCreate");
$(".myCheckBox").change( function(){
if($(this).is(':checked')){
$(wrapper).append('<input type="text" name="mytext[]" placeholder="'+$(this).val()+'">');
}
else{
$('.inputCreate :last-child').remove();
}
});
Try this. I assume you want to remove the text box if checkbox unchecked.
$('.myCheckBox').click(function() {
if ($(this).is(':checked')) {
$(wrapper).append('<input type="text" name="mytext[]" placeholder="">');
}else{
$(wrapper).find('input').remove();
}
});

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!

Must check last three check boxes to submit

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!';
}

Categories

Resources