I have a question about javascript that I using in TCPDF to generate PDF.
I use mix of php native and codeigniter with MySQL database to develop my App.
My Soryboard :
I have a field in my table like this that represntated like this :
$dataKind = $d['kindOf_request'];
// This code will be return a string like this : **Login, Printer, Monitor, Computer, Network, Other**
So, I use Javascript to split this string to convert into an array.
You know, TCPDF can write html. How to manipulated a checkbox that will be checked if matching with Element of this array. This is the code :
$dataKind = $d['kindOf_request'];
$html = <<<EOD
<body>
<form action="">
<input type="checkbox" name="request[]" id="Login" value="Login" > Login
<input type="checkbox" name="request[]" id="Printer" value="Printer" > Printer
<input type="checkbox" name="request[]" id="Monitor" value="Monitor" > Monitor
<input type="checkbox" name="request[]" id="Computer" value="Computer" > Computer
<input type="checkbox" name="request[]" id="Network" value="Network" > Network
<input type="checkbox" name="request[]" id="Lain-lain" value="Lain-lain"> Other
</form>
</body>
EOD;
$pdf->writeHTMLCell(0, 10, '', '', $html, $border = 0, $ln = 1, $fill = false, $reseth = true, $align = 'L', $autopadding = false);
$js = <<<EOD
var str = "$dataJenis";
var res = str.split(" ");
for (var i=0, item; item=res[i]; i++) {
item = item.replace(/,/g, "");
/*if item == id checkbox, then :
checkbox will be checked
*/
if (item == document.getElement ...) {
// Confused
# code...
}
//app.alert(item);
}
EOD;
$pdf->IncludeJS($js);
So million thanks for the help ...
Related
function check_uncheck(truefalse) {
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form.chkboxarray[i].checked = true;
} else {
form.chkboxarray[i].checked = false;
}
}
}
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
The snippet shows how it works without connection to a database
I am trying to save the data that is sent from the checklist to a database but i'm stuck. I was thinking of using a foreach but I don't know what to put in it.
I though of putting it as:
foreach($_POST['id'] as $add){
insert into database...
}
How do I do this?
If I do this as Fred-ii and xjstratedgebx suggested where I just change name="chkboxarray" to name="chkboxarray[]" then the javascript code would stop working.
<?php
include '../conec.php';
mysql_select_db("test",$conec)or die('Database does not exist.') or die(mysql_error());
$sql = mysql_query("SELECT * FROM user WHERE state='Not Signed Up'");
?>
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<?php
while($row = mysql_fetch_array($sql)){
$id = $row['id'];
$name = $row['name'];
$lName= $row['lName'];
$concate = $name.' '.$lName;
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
}
?>
<!--<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />-->
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
<script type="application/javascript">
function check_uncheck(truefalse){
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for(var i=0;i < boxes;i++){
if (truefalse) {
form.chkboxarray[i].checked=true;
} else {
form.chkboxarray[i].checked=false;
}
}
}
</script>
If you change the name of your checkbox from "chkboxarray" to "chkboxarray[]", then any boxes that are checked when the form is submitted will pass their values as an array to the server under the key of "chkboxarray".
Basically, change this line:
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
To:
echo '<input type="checkbox" name="chkboxarray[]" value="'.$id.'" />'.$concate.'<br />';
As a result, if you var_dump the $_POST super global, you should see something like:
array(1) {
[chkboxarray]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
In the example above, the checkboxes for id's 3 and 4 were checked, so they were sent to the server.
Once you have that array, inserting it into your database depends heavily on what you're trying to accomplish and your database's schema.
Hope that helps.
Also, in fairness, this is exactly what #Fred meant in his comment.
Edit 1
To make the javascript work with the change of the input name, you'll need to update all the places in your javascript where you were referencing the name of the input to the new name (chkboxarray[]).
The resulting code should look like this:
<script type="application/javascript">
function check_uncheck(truefalse) {
var boxes = document.forms[0]["chkboxarray[]"].length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form["chkboxarray[]"][i].checked = true;
} else {
form["chkboxarray[]"][i].checked = false;
}
}
}
</script>
I've created a fiddle to show this works for checking/unchecking all the boxes: https://jsfiddle.net/solvomedia/3Ln468u3/
I have an HTML form to retrieve some options from checkboxes:
<form action="" method="post" id="menuform" name="menuform">
<fieldset>
<legend>Select a Menu</legend>
<label>
<input type="radio" name="selectedmenu" checked value="menu01" ape-qty='8' ent-qty='1' pes-qty='1' sor-qty='1' car-qty='1' pos-qty='1' data-price='95' />
<span>First Item</span>
</label>
...(more)...
</fieldset>
<fieldset>
<legend id='aperitivosPrompt'>Elegir Aperitivos</legend>
<label>
<input type='checkbox' name='aperitivos' value="1" />
<span>Item 1</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="2" />
<span>Item 2</span>
</label>
<label>
<input type='checkbox' name='aperitivos' value="3" />
<span>Item 3</span>
</label>
...(more)...
</fieldset>
<fieldset>
<input type="submit" value="Enviar" />
</fieldset>
</form>
Then I send this variables to a JavaScript file and I save all checkboxes options in multiple arrays
var menuform = document.getElementById('menuform'),
radios = document.getElementsByName('selectedmenu'),
aperitivos = document.getElementsByName('aperitivos'),
aperitivosPrompt = document.getElementById('aperitivosPrompt'),
totalPrice = document.getElementById('totalPrice'),
result = document.getElementById('result'),
aperitivosAllowed = 0,
currentSelectionAperitivos = [],
currency = '€';
function handleAperitivos(e) {
var count = getSelectedCountApe();
if (count > aperitivosAllowed) {
resetSelectApe();
} else {
currentSelectionAperitivos = getSelectedValuesApe();
}
}
...(more)...
function getSelectedCountApe() {
var count = 0;
for (var i = 0; i < aperitivos.length; i++) {
if (aperitivos[i].checked) count++;
}
return count;
}
...(more)...
So, how can I send these arrays named currentSelectionAperitivos = [] in an email? I want that after user selects all his options, I receive an email in my inbox with his selected options.
I think that I must connect this form and JS file with a PHP function and send emails from there. Anyway, how can I do this?
-EDITED-
I tried a solution with JSON:
for (var i = 0; i < aperitivos.length; i++) {
var item = {
"valor": i,
"etiqueta": aperitivos[i].value
};
currentSelectionAperitivos.push(item);
}
currentJSON = JSON.stringify({currentSelectionAperitivos:currentSelectionAperitivos});
console.log(currentJSON);
So now I get in browser console all "values" from fields <input> of the HTML form. But not only CHECKED values and anyway, what I need now is to get this JSON.stringify and send it by mail with PHP.
Write a PHP script to send the email, change the form action to post on this script.
Attention: this is untested.
Change your form to:
<form action="mail.php"...>
</form>
Create mail.php like
<?php
ob_start();
var_dump($_POST);
$result = ob_get_clean();
mail ( 'your#email.com' , 'subject' , $result);
?>
Otherwise you could use JSON.stringify and an API to send the E-Mail with JS.
I found a good solution for my needs. I get all 'checked' values and I create an email with theme.
So, HTML form:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript' src='http://sisyphus-js.herokuapp.com/assets/application-09059f9f54cc3c3bff98487cf866644b.js'></script>
</head>
<body>
<form action="configurador.php" method="post" id="menuform" name="menuform">
<fieldset>
<legend id='itemPrompt'>Choose Item</legend>
<label>
<input type='checkbox' name='item' value="Value#01" />
<span>Value#01</span>
</label>
(...more...)
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
</body>
So there I have all my 'checkboxes' with values and names. I made some JavaScript functions but most important one is this one where I retrieve all values and send theme in an email:
function sendMail() {
var mailbody = "My Configurator: \n\n"
+ $('input[name="item"]')
.map(function(id, box){ return (box.checked ? "[x]" : "[_]") + " " + box.value;})
.get()
.join("\n");
var link = "mailto:mail#mail.com"
+ "?cc="
+ "&subject=" + escape("Configurator - Subject")
+ "&body=" + escape(mailbody);
window.location.href = link;
}
$(function(){
$( "#menuform" ).sisyphus();
});
And it's OK with just this. But I'm getting all checkboxes, even not checked ones, in that email. And could be perfect if I don't have to open a client mail, just send that mail from my server automatically.
Any solution for this variation?
I am creating a comments board and via Javascript i am attempting to implement a piece of script which will prevent the user from submitting a paragraph if it has a undesirable word(s) in it. I have looked online and struggled to find any examples. This is what i have so far but not sure if i should be using index.of
index.php
<div class="askComment">
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post; ?>">
<input type="hidden" name="type" value="A">
<p>Hello <strong><?php echo $fname; ?></strong> what do you have to say</p>
<input type="hidden" name="fname" id="comment-name" value="<?php echo $fname; ?>" >
<input type="hidden" name="userid" id="comment-mail" value="<?php echo $UserId; ?>" >
<p>Your comment *</p>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." ></textarea>
<div id="error"></div>
<input type="submit" id="submit-comment" name="submit" value="Submit Comment">
</form>
</div>
mod_comment.php
$(document).ready(function () {
document.getElementById("submit-comment").disabled = true;
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").change(function () {
var comment = $("#comment").val();
if (comment.indexOf('????') === -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
} else {
document.getElementById("loginsubmit").disabled = false;
}
});
});
One possible solution (similar to your, same logic, just few changes/additions).
http://jsfiddle.net/pK7DK/
$("#submit-comment").attr('disabled', true);
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").on("keyup", function () {
var comment = $("#comment").val();
word = comment.split(' ');
for (i = 0; i < word.length; i++) {
worda = word[i].trim();
worda = worda.replace(/\.|,|!|:| |;|\?|\r?\n/g, ''); // bad word + one of chars = bad word
console.log(worda);
if ($.inArray(worda, swear) != -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
$("#submit-comment").attr('disabled', true);
break;
} else {
$("#error").html('');
$("#submit-comment").attr('disabled', false);
}
}
});
I would rather use 'keyup' event, so user will get error message(s) as he type. However - as mentioned, this can be easily overriden, server-side checking is a must.
Take a look at this: http://www.w3schools.com/jsref/jsref_search.asp (searches an array inside of an array);
It may not be the most optimal option, but it will be a start for your code.
EDIT: A better option (not the best, maybe) could be separating the comment string by words into an array and doing an intersection between the two arrays, here's a question explaining how to do intersections between arrays in js Simplest code for array intersection in javascript
I'm making a card generator for fun and learning how to collect data from inputs and write to database.
When trying to send this simple piece of JSON data I get POST Forbidden (403) errors from my PHP script.
Here is the jsonlint.com validated object I am working with which is generated from input elements and javascript-
{
"name": "Transfer Power",
"layout": "cic",
"artwork": "http://static.tvtropes.org/pmwiki/pub/images/Voyager_shield.jpg",
"rarity": "common",
"cost": "3",
"text": "Until the start of your next turn, target friendly Ship gains Shield +X and Damage -X where X is the Ship's current Damage."
}
From what I understand I should be able to send the complete artwork url without any formatting but the POST only works when I remove the scheme of the url. I hope it's something simple. Here is the code-
var name = $('#name').val();
var layout = type;
var artwork = $('#artwork').val();
var rarity = $('#rarity').val();
var cost = $('#cost').val();
var type = $('#type').val();
var text = $('#text').val();
var card = {};
card.name = name;
card.layout = layout;
card.artwork = artwork;
card.rarity = rarity;
card.cost = cost;
card.text = text;
$.post('writecard.php', card, function(data){
console.log(data);
});
And the super simple PHP echo to re-verify my data-
<?php
$raw = $_POST;
foreach($raw as $key => $val){
echo $key . ': ' . $val . ' -- ';
}
?>
Again: It successfully sends the POST and returns the data when I remove the scheme of the URL.
One other point of concern: How do I ensure I'm sending integers and not characters? Should the "cost": "3", not be shown, instead, as "cost": 3, ?
Thanks for reading. :]
When using writecard.php as per your example, the following index.html:
<html>
<script src="jquery-1.10.2.min.js" ></script>
<body>
<input id="name" value="Transfer Power" />
<br/>
<input id="layout" value="cic" />
<br/>
<input id="artwork" value="http://static.tvtropes.org/pmwiki/pub/images/Voyager_shield.jpg" />
<br/>
<input id="rarity" value="common" />
<br/>
<input id="cost" value="3" />
<br/>
<input id="type" value="unknown" />
<br/>
<input id="text" value="Until the start of your next turn, target friendly Ship gains Shield +X and Damage -X where X is the Ship's current Damage." />
</body>
<script>
var name = $('#name').val();
var layout = type;
var artwork = $('#artwork').val();
var rarity = $('#rarity').val();
var cost = $('#cost').val();
var type = $('#type').val();
var text = $('#text').val();
var card = {};
card.name = name;
card.layout = layout;
card.artwork = artwork;
card.rarity = rarity;
card.cost = cost;
card.text = text;
$.post('writecard.php', card, function(data){
console.log(data);
});
</script>
</html>
Outputs:
name: Transfer Power -- artwork: http://static.tvtropes.org/pmwiki/pub/images/Voyager_shield.jpg -- rarity: common -- cost: 3 -- text: Until the start of your next turn, target friendly Ship gains Shield +X and Damage -X where X is the Ship's current Damage. --
And to take the javascript out of the equation - what about if it's a simple form?
<html>
<body>
<form action="writecard.php">
<input id="name" name="name" value="Transfer Power" />
<br/>
<input id="layout" name="layout" value="cic" />
<br/>
<input id="artwork" name="artwork" value="http://static.tvtropes.org/pmwiki/pub/images/Voyager_shield.jpg" />
<br/>
<input id="rarity" name="rarity" value="common" />
<br/>
<input id="cost" name="cost" value="3" />
<br/>
<input id="type" name="type" value="unknown" />
<br/>
<input id="text" value="Until the start of your next turn, target friendly Ship gains Shield +X and Damage -X where X is the Ship's current Damage." />
<br/>
<input type="submit" />
</form>
</body>
</html>
Here's my code:
<script type="text/javascript" xml:space="preserve">
function ATHD(f) {
var aa = "I would like help with the following topic(s): "
var bb = "Password Reset "
var cc = "Password Setup "
var dd = "Firmware Upgrade (if applicable) "
var ee = "Local Access Setup "
var ff = "Remote Access Setup "
var gg = "Mobile Access Setup "
var hh = "Recording Schedule Setup "
var ii = "How to playback video "
var jj = "How to convert video "
var kk = "Email Notification Setup "
var ll = "PTZ Setup (if applicable) "
if( f.pr.checked == true) {
f.sup.value = aa + bb;
}
if( f.ps.checked == true) {
f.sup.value = aa + cc;
}
}
</script>
<form><input onclick="ATHD(this.form)" id="1" type="checkbox" name="pr" /> Password Reset<br />
<input onclick="ATHD(this.form)" id="2" type="checkbox" name="ps" /> Password Setup<br />
<input onclick="ATHD(this.form)" id="3" type="checkbox" name="fu" /> Firmware Upgrade (if applicable)<br />
<input onclick="ATHD(this.form)" id="4" type="checkbox" name="la" /> Local Access Setup<br />
<input onclick="ATHD(this.form)" id="5" type="checkbox" name="ra" /> Remote Access Setup<br />
<input onclick="ATHD(this.form)" id="6" type="checkbox" name="ma" /> Mobile Access Setup<br />
<input onclick="ATHD(this.form)" id="7" type="checkbox" name="rss" /> Recording Schedule Setup<br />
<input onclick="ATHD(this.form)" id="8" type="checkbox" name="pb" /> How to playback video<br />
<input onclick="ATHD(this.form)" id="9" type="checkbox" name="cv" /> How to convert video<br />
<input onclick="ATHD(this.form)" id="10" type="checkbox" name="en" /> Email Notification Setup<br />
<input onclick="ATHD(this.form)" id="11" type="checkbox" name="ptz" /> PTZ Setup (if applicable)<br />
<br />
<span style="FONT-WEIGHT: bold">Question</span><span style="COLOR: #ff0000">*</span> (please be specific)<br />
<br />
<textarea style="HEIGHT: 164px; WIDTH: 577px" rows="10" cols="40">
</textarea></p>
<p><button>Continue...</button>
<textarea style="HEIGHT: 164px; DISPLAY: hidden; WIDTH: 577px" rows="10" cols="40" name="sup">
</textarea>
</p>
</form>
Basically, what I am looking to do is to whenever a box is checked, I want the value of the checkbox to be added into a hidden field. I understand that I still need to add the "value=[the value of the checkbox]" in the html code; what I want to allow for is multiple checkboxes to be selected so that multiple items will get added to the textbox.
I understand that one way of doing this would be to be to create if-then statements for every possible variation; this would not be very time effective as there would be thousands of permutations.
I am also trying to figure out if using an array would work to simplify this; I am not really sure how to conceptualize this in the simplest way as I have only been doing javascripting for three weeks. If someone can tell me how to think about this, I would greatly appreciate it. Looking more to learn how to do this so I can contribute to these forums and simplify the process of scripting functions as I do not have a background in coding.
If you can use jQuery, you won't need much code:
You could update the results whenever somebody clicks on a checkbox ($('input').on('click', function() {).
I personally would use <label> elements, but that's just me. You could grab the values by
$('input:checked').each(function() {
values.push($(this).parent().text());
});
Here is a working example: http://jsfiddle.net/HarryPehkonen/zNfju/1/
I have made small changes your dom like removing onclick events and It may solve your problem
var arr = [];
remove_item = function(arr,value){
for(b in arr ){
if(arr[b] == value){
arr.splice(b,1);
break;
}
}
return arr;
}
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].getAttribute('type') == 'checkbox')
{ inputs[i].addEventListener("change",function() {
if(this.checked)
arr.push(parseInt(this.id));
else
{
remove_item(arr,parseInt(this.id));
}
console.log(arr); document.getElementById("chcbx").value = arr.join(",");
},false);
}
}
and have a look at jsFiddle remove_item
Here's another way of doing it.
// find number of checkboxes (you haven't specified if you
// have a set number or not. If you have a set number, just
// set checkboxCount to whatever number you have.
var checkboxCount = 0;
var inputTags = document.getElementsByTagName('input');
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].getAttribute("name") + ';';
}
document.getElementById("hdnValues").value = totalValue;
alert(totalValue);
}
This basically counts all the checkboxes, loops through all, checks if they're checked, gets the value of the name attribute, then appends it to a string which is delimited by ;
jsfiddle: http://jsfiddle.net/mcDvw/
Alternatively, you could set all the values you want into the value attribute of the checkbox and read that instead of having the value in JS variable. e.g.
HTML:
<input onclick="ATHD()" id="1" type="checkbox" name="pr" value="Password Reset" /> Password Reset<br />
<input onclick="ATHD()" id="2" type="checkbox" name="ps" value="Password Setup" /> Password Setup<br />
JS:
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].value + ';';
}
document.getElementById("hdnValues").value = totalValue;
document.getElementById("showValues").value = totalValue;
}
jsfiddle: http://jsfiddle.net/mcDvw/1/