I Can't get all selected checkboxes to print ! (Array) - javascript

I am struggling to get my QR codes to line up to print, I have a list of QR codes and wanted to check and Print SELECTED, I am almost there. but I got Stuck on Iterating throgh.. When I click Print it only prints Array[0] by default. I wanted to print ALL slected items on a popup Print window.
Here is my Code:
Hi All,
I am struggling to get my QR codes to line up to print, I have a list of QR codes and wanted to check and Print SELECTED, I am almost there. but I got Stuck on Iterating through.. When I click Print it only prints Array[0] by default. I wanted to print ALL slected items on a popup Print window.
Here is my Code:
<script type="text/javascript">
function PrintQR() {
var codes = document.getElementsByClassName("QR")[0].innerHTML
for (var i = 0; i < codes.length; i++) {
var popupWin = window.open('', 'blank');
popupWin.document.open();
popupWin.document.write('' + '<html>' + '<body onload="window.print()">' + '<div class="Q">' + codes + '</div>' + '</body>' + '</html>');
popupWin.document.close();
setTimeout(function() {
popupWin.close();
}, 10);
}
};
</script>
//MY Submit Button Here :
<div>
<center><button type="button" class="btn btn-primary btn-sm" onclick="PrintQR()"> Print This </button></center>
</div>
Here is my FORM:
<form method="POST">
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['qrcode'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['qrcode']);
echo "You have selected following " . $checked_count . " option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
foreach ($_POST['qrcode'] as $selected) {
$output = '
<br><br><br>
<div class="QR">
<center><img src="userQr/' . $selected . '" /> </center>
</div>
';
echo $output;
}
}
}
?>
</form>
It's only printing First Array, sometimes when I would try and it would give me an "HTML Collection" Javascript error !
Any Help will be appreciated .
Thank you all for the CLEVER Work here at Stackoverflow .
Ed-

You are explicitly selecting only the first element here:
var codes = document.getElementsByClassName("QR")[0].innerHTML
You should select all the elements and the loop on them. Here is an example:
function PrintQR() {
var codes = document.querySelectorAll('.QR');
codes = [...codes].map(code => code.innerHTML);
console.log(codes.join('\n'));
// Uncomment the following on your real page
/*
var popupWin = window.open('', 'blank');
popupWin.document.open();
popupWin.document.write('' + '<html>' + '<body onload="window.print()">' + '<div class="Q">' + code + '</div>' + '</body>' + '</html>');
popupWin.document.close();
setTimeout(function() {
popupWin.close();
}, 10);
*/
};
<div>
<center><button type="button" class="btn btn-primary btn-sm" onclick="PrintQR()"> Print This </button></center>
</div>
<form method="POST">
You have selected following 3 option(s): <br />
<br><br><br>
<div class="QR">
<center><img src="userQr/1" /> </center>
</div>
<br><br><br>
<div class="QR">
<center><img src="userQr/2" /> </center>
</div>
<br><br><br>
<div class="QR">
<center><img src="userQr/3" /> </center>
</div>
</form>
Update
Since you want to print all the images in one run, you do not need to loop over them. The above snippet has been updated to show an example without the loop.
You will probably need some CSS styles in order for the images to each print on a different page.

Thank you Sir, but now it is printing ONLy the last One, and by Printing I meant Print to printer, A popup will show and the only QR code that's displayed is the Last one in the Array...
I really want them to show all in the popup Print preview window before printing and Yes I have selected Pages All.
Many Thanks.!
Ed-

Related

How to create dynamic textarea which includes php $_POST code

I got a little problem with php/js. I want to create a website for a school project which is a communotary food receipe oriented website. And here I'm struggling with my page 'submit receipe'.
To be exact the problem is that I create, with a button, some dynamic textarea in order to represents the steps of a receipe, to do so I use a js eventHandler. And here I have a problem because I want to insert in this js code the post value that the user has typed. But I honestly don't know how to do this, I get the fact that js is executed before php so do I have a solution to bypass this problem ?
Here my code :
// The js script
function createNewElement() {
var txtNewInputBox = document.createElement('div');
var php = "<?php if(isset($_POST['boxExplain_" + numStep + "']))echo $_POST['boxExplain_"+ numStep + "']?>";
txtNewInputBox.innerHTML = "<label for='box-explain'>Step " + numStep + "</label>"+
"<br>"+
"<textarea type='text' class='box-explain' name='boxExplain_" + numStep + "'" +
"value='' placeholder='BlaBla.'>" +
php + "</textarea>" +
'<i class="fas fa-minus-circle '+ numStep +'"></i>';
numetape++;
document.getElementById("step-box").appendChild(txtNewInputBox);
}
And here the HTML :
<div class="explain-box">
<h3>Explanations </h3>
<label for="box-explain">Step 1</label>
// The first one is not dynamic
<textarea type='text' class='box-explain' name='boxExplain_1' value="" placeholder="BlaBla"><?php if (isset($_POST['boxExplain_1'])) echo $_POST['boxExplain_1'] ?></textarea>
//here goes the js one
<div id="step-box"></div>
<div id="dynamicCheck">
<input class="btnStep" type="button" value="add Step" onclick="createNewElement();" />
<i class="fas fa-plus"></i>
</div>
</div>
I hope it was clear enough, thanks for your help.

character counter not functioning when echoed repeatedly in a table

I'm trying to use the javascript character counter below in multiple textareas within my table. The problem is the counter only functions in the first row of my table. Subsequent rows with textareas echo "250 characters remaining", but do not function as intended. I'm not sure how to assign each character counter with a unique id so it functions in all textareas. Any help would be appreciated.
PHP:
echo "</td><td>";
echo '<form action="peerflagreview.php?foorbar=' . $foobar . '" method="post" id="FlagPeerReview">
<A NAME="#peer' . $foobar . '"> (Report)
<textarea class="PeerFlag" value="" name="PeerFlag" id="PeerFlag2"></textarea>
<input type="hidden" value="Post" name="submit" />
<span id="PeerFlag2Span">250 characters remaining</span>
<input type="submit" value="Submit"></form>';
echo "</td></tr>";
JAVASCRIPT:
<script type="text/javascript">
$("#PeerFlag2").on('change keydown paste input', function(){
updateCounter('#PeerFlag2');
});
function updateCounter(theTextAreaID) {
var remaining = 250 - jQuery(theTextAreaID).val().length;
jQuery(theTextAreaID + 'Span').text(remaining + ' characters remaining.');
}
$('textarea').on('keydown', function(event) {
if (event.keyCode == 13)
if (!event.shiftKey) $('#PeerFlag').submit();
});
</script>
This is a very simple demo so I don't see of much explain needed other than this will target the next span of the textarea in use.
I see you already have jQuery so this demo will also use jQuery.
$(document).ready(function(){
$(".UserInput").on('input', function(){
$(this).next("span").html(250 - this.value.length + " characters remaining");
}).trigger('input');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="UserInput"></textarea><span>this is filled automatically</span><br/>
<textarea class="UserInput"></textarea><span></span><br/>
<textarea class="UserInput"></textarea><span></span><br/>
<textarea class="UserInput"></textarea><span></span><br/>
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

javascript button always disabled

This has probably been answered before, and I'd like to apologize for reposting, but since I'm not sure where to start fixing it, I'm not sure what to try and look up for a solution. So bear with me please.
I've got a form for a CMS where I've used a tutorial to dynamically add fields where I need them. EX: The form loads with 0 field entries for bullet points, but if they want some, they can click a button that says add bullet, and voila, a entry field appears. It's in an array. Submits to the DB just fine. The delete button is disabled if there's no fields displayed. All that works fine. If you start out with no fields, on a fresh form. The problem falls into the edit version of this form.
Here's my code:
<div id="bullets">
<?php
$sql_bullet_display = 'SELECT * FROM exampleDB.prod_feature_bullets WHERE product_name ="'.$row_product_details['product_name'].'";';
$res_bullet_display = mysql_query($sql_bullet_display) or die(mysql_error().'<br />bad query<br />'. $sql_bullet_display);
$newNum = 1;
while($row_bullet_display = mysql_fetch_assoc($res_bullet_display)){
?>
<div id="bullet<?php echo $newNum; ?>" class="clonedInput2">
<input type="hidden" id="bullet_order<?php echo $newNum; ?>" name="bullet[<?php echo $newNum; ?>][bullet_order]" value="<?php echo $newNum; ?>" />
<input type="text" id="bullet_text<?php echo $newNum; ?>" name="bullet[<?php echo $newNum; ?>][bullet_text]" value='<?php echo $row_bullet_display['bullet_text']; ?>' />
<input type="text" id="bullet_subtext<?php echo $newNum; ?>" name="bullet[<?php echo $newNum; ?>][bullet_subtext]" value='<?php echo $row_bullet_display['sub_text']; ?>' />
</div>
<?php
$newNum++;
}
?>
</div>
<div>
<input type="button" id="btnAdd" value="Add Bullet" />
<input type="button" id="btnDel" value="Remove Bullet" />
</div>
and this is the Javascript that goes with it.
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput2').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
$('<div id="bullet' + newNum + '" class="clonedInput2"><input type="hidden" id="bullet_order' + newNum + '" name="bullet[' + newNum + '][bullet_order]" value="' + newNum + '" /><input type="text" id="bullet_text' + newNum + '" name="bullet[' + newNum + '][bullet_text]" /><input type="text" id="bullet_subtext' + newNum + '" name="bullet[' + newNum + '][bullet_subtext]" /></div>').appendTo('#bullets');
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 15 bullets
if (newNum == 15)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput2').length; // how many "duplicatable" input fields we currently have
$('#bullet' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if no element remains, disable the "remove" button
if (num == 0)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
This has worked really well for me in the past, but like I said, it only works on a fresh form that's starting out at 0 bullet entry fields. My problem lies in creating the edit form. I've already got two bullets in the DB that are displayed when you hit edit. The add button shows enabled. The delete button is always disabled when the form first comes up. Even if there's two entries displayed and everything is filled correctly.
However if I click the add button, so a third entry field will show up, it will enable the delete button. Very frustrating. I'm not sure what to go about editing so it'll say: okay, on the page load, we recognize that the DB already filled out two bullets, so the delete button should be active from the start. Every change I've tried so far just breaks the button.
Thanks in advance for the help!
In your javascript code, you have initiliazed the deletebutton to be disabled. you need to check the number of bullets you have created from db...
Modify your last code from:
$('#btnDel').attr('disabled','disabled');
to
if($('.clonedInput2').length<=0){
$('#btnDel').attr('disabled','disabled');
}
Try this to remove the disabled attribute
$("#btnDel").removeAttr("disabled");

Radio button with an "other" text box not inputting value properly using javascript

I'm creating a form using html form controls and javascript to help streamline some processes at work. I've temporarily put the form online here.
In one section of the form, I have a text box associated with a radio button. The other radio buttons in the section display their values properly when the "Display" button is hit at the bottom of the page, but the radio button with the text box does not. It seems that I'm not correctly assigning the value of the text box to the value of the radio button. What am I doing wrong?
Here's the javascript:
<script LANGUAGE="JavaScript" type="text/javascript">
function display() {
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
var radio_paymenttype_val = document.form2.paymenttype[i].value;
}
}
for (var i=0; i < document.form2.contracts.length; i++)
{
if (document.form2.contracts[i].checked)
{
var radio_contracts_val = document.form2.contracts[i].value;
}
}
DispWin = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600')
message = "<h2>Royalty Advance Payment Letter</h2>";
message += "<hr />";
message += "<span STYLE=\'font-family: Garamond\'>";
message += "<p>" + document.form2.agentfirstname.value + " " + document.form2.agentlastname.value + "<br />";
message += document.form2.agencyname.value + "<br />";
message += document.form2.agentaddress1.value + "<br />";
message += document.form2.agentaddress2.value + "<br />";
message += document.form2.agentcity.value + ", " + document.form2.agentstate.value + " " + document.form2.agentzip.value + "<br />";
message += document.form2.agentcountry.value + "<br />";
message += "</p>";
message += "<p>Dear " + document.form2.agentfirstname.value + ",</p>";
message += "<p>Please find enclosed a check in the amount of $";
message += document.form2.paymentamount.value + " representing the amount due upon ";
message += radio_paymenttype_val + " ";
message += document.form2.authorfirstname.value + " ";
message += document.form2.authorlastname.value + "'s <em>";
message += document.form2.booktitle.value + "</em>.";
message += radio_contracts_val + "</p>";
message += "<p>Regards,<br /><br /><br /><br />My Name<br />Associate Editor</p>";
message += "</span>";
DispWin.document.write(message);
}
</script>
And here's the HTML for that section:
<div class="required">
<fieldset>
<legend>Payment Type:</legend>
<label for="payment_sig" class="labelRadio"><input type="radio" name="paymenttype" id="payment_sig" class="inputRadio" value="signature for" /> Signature</label>
<label for="payment_danda" class="labelRadio"><input type="radio" name="paymenttype" id="payment_danda" class="inputRadio" value="delivery and acceptance of" /> Delivery & Acceptance</label>
<label for="payment_pub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pub" class="inputRadio" value="publication of" /> Publication</label>
<label for="payment_pbpub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pbpub" class="inputRadio" value="paperback publication of" /> Paperback Publication</label>
<label for="payment_otherlabel" class="labelRadio"><input type="radio" name="paymenttype" id="payment_otherlabel" class="inputRadio" onclick="this.form.payment_other.focus()" onfocus="this.form.payment_other.focus()" value="" checked="checked" /> Other:</label>
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" />
<small>Remember, this text will be in the middle of a sentence. This text should always end in "of" or "for."</small>
</fieldset>
</div>
Your first for loop goes through and finds the value of the correct radio selected, but in the case of "other" you're not going to have a value assigned. You need to determine when other is selected, then assign radio_paymenttype_val the value of the text box instead. Something to the effect of:
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
// assuming "other" is the only case where this radio's value property would be empty.
var radio_paymenttype_val = (document.form2.paymenttype[i].value != ''
? document.form2.paymenttype[i].value
: document.form2.payment_other.value);
}
}
Update
So excuse the delay (took your form field and ran with it). This is (I believe) what you're looking for. Some things to note:
I don't do any form validation. This is something you probably want to tinker with, and can be pretty simple. In the .click() event, just check something like the following (or you can get more elaborate):
if($('#agentfirstname').val()==''){
alert('Missing First Name');
return;
}
Also, I use something fairly new to jQuery, templates. This makes it easier than var+='html html'+var+'html'; (as you can witness in the <script> tag with the ID 'FormTemplate`).
Finally, I tested this on FF4, Chrome4 and IE8 and it should work, but let me know if it doesn't on whatever environment you use.
Anyways, here's the code, hope this helps!
Place inside <head> element of your document
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<Script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script type="text/javascript">
$(function(){
// bind to the "display" button ('.' means this is a class name reference)
$('.inputSubmit').click(function(e){
// build up the template values
var tmplData = [{
agentFirstName: $('#agentfirstname').val(),
agentLastName: $('#agentlastname').val(),
agencyName: $('#agencyname').val(),
agentAddr1: $('#agentaddress1').val(),
agentAddr2: $('#agentaddress2').val(),
agentCity: $('#agentcity').val(),
agentState: $('#agentstate').val(),
agentZip: $('#agentzip').val(),
paymentAmount: '$'+$('#paymentamount').val(),
paymentType: $('input[name="paymenttype"]:checked').val() != '' ? $('input[name="paymenttype"]:checked').val() : $('#payment_other').val(),
authorFirstName: $('#authorfirstname').val(),
authorLastName: $('#authorlastname').val(),
bookTitle: $('#booktitle').val(),
contracts: $('input[name="contracts"]:checked').val()
}];
// create the template
var template = $('#FormTemplate').template('letter');
// Create a fake div we can push the template to and pass off to popup
var tmplDiv = document.createElement('div');
$(tmplDiv).attr('id','TemplateDiv').css('display','none');
// Write the template and push it off
$.tmpl('letter', tmplData).appendTo(tmplDiv);
// create the window and populate it with the template
var hWindow = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600');
hWindow.document.write(tmplDiv.innerHTML);
// stop any further action
e.preventDefault();
});
});
</script>
Place inside <body> element of your document:
<script id="FormTemplate" type="text/x-jquery-tmpl">
<html>
<head>
<title>Letter</title>
</head>
<body>
<h2>Royalty Advance Payment Letter</h2>
<hr />
<span type="font-family:Garamond;">
<p>
${agentFirstName} ${agentLastName}<br />
${agencyName}<br />
${agentAddr1}<br />
${agentAddr2}<br />
${agentCity}, ${agentState} ${agentZip}<br />
</p>
<p>
Dear ${agentFirstName},
</p>
<p>
Please find enclosed a check in the amount of ${paymentAmount} representing the amount due upon ${paymentType}
${authorFirstName} ${authorLastName}'s <em>${bookTitle}</em>.
${contracts}
</p>
<p>
Regards,<br />
<br />
<br />
<br />
Margaret Maloney<br />
Associate Editor
</p>
</span>
</body>
</html>
</script>
Could you simply set a onblur() for the payment_other to set the radio option's value?
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" onblur="document.getElementById('payment_otherlabel').value=this.value;" />
Then if it is ever set, it will automatically copy the value into the radio option. Then when your Display() function is called, I would think the value would be set.
(Realized I missed the semi-colon at the end of the onblur="" statement.)
Have you tried this yet?

Categories

Resources