How to create dynamic textarea which includes php $_POST code - javascript

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.

Related

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

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-

javascript continue refreshing page after api load

I'm trying to send a request and get answer from my own synonyms api. The api works very well. And the javascript is getting the answer, but it keeps refreshing the page and in the end there's no output in my html.
This is my html script:
<form method="POST">
<input type="text" class="question" />
<button class="gen-syn">Generate synonyms</button>
<input type="submit" value="Save"/>
</form>
And this is my javascript:
$(document).on('click','.gen-syn',function(){
var questionVal = $(".question").val();
if (questionVal == ''){
$(".question").focus();
}
else {
$.ajax({
type :'POST',
url : "http://192.168.1.9:5000/synonyme_word/"+questionVal,
success : function(response){
var divSynonymes = $(document.createElement('div'));
$(".question").after(divSynonymes);
for (var a in response){
$(divSynonymes).append('<h1 class="titre-textareal-question-icona-go " value=>'+a+'</h1>'+
'<div class="form-group row" >'+
'<div class="col-sm-12 listeSyn">'+
'</div>'+
'</div>'
);
for (syn in response[a]){
var synonyme = response[a][syn]
$(".listeSyn").append(
'<input type="checkbox" name="checkboxes[249]" id="frm-test-elm-110-100" autocomplete="off" />'+
'<div class="btn-group">'+
'<label for="frm-test-elm-110-100" class="btn btn-primary">'+
'<span class="fa fa-check-square-o fa-lg"></span>'+
'<span class="fa fa-square-o fa-lg"></span>'+
'<span class="content">'+synonyme+'</span>'+
'</label>'+
'</div>');
}
}
},
});
return False;
}
});
I didn't make any reload, but the navigator keeps reloading after calling the api (when I click on Generate synonyms button)
Get rid of the <form> altogether. Its behaviour messes with your code. Just use a <div>.
This should fix your issue.
<input type="text" class="question" />
<button class="gen-syn">Generate synonyms</button>
<input type="submit" value="Save"/>
you need only one button to make a API call and then your JS code is creating dynamic div and other elements to show the synonyms.
Hope this helps.

Automatically copy text when clicked on input area (multiple lnputs) Javascript

I'm trying to get input area to copy text when the user clicks on it. The code itself is selecting correct text but when i add copy function it won't copy correct text. Problem is that this is a template which website use to add elements to the website (so multiple submissions will use same code).
echo '<div class="input-group input-group-sm">';
echo '<span class="input-group-addon input-label-' . strtolower($server->status_text) . '"><i class="fa fa-server" aria-hidden="true"></i> ' . $server->status_text . '</span>';
echo '<input type="text" onclick="this.select()" value="' . $server->address . (($server->connection_port != '25565') ? ":" . $server->connection_port : null) . '">';echo '</div>';
Output on site:
<div class="input-group input-group-sm">
<span class="input-group-addon input-label-online"><i class="fa fa-server" aria-hidden="true"></i> Online</span>
<input type="text" onclick="this.select()" class="form-control" value="Server IP">
</div>
Edit: It looks like i will need to do this via button as using "onclick" is crashing my website. Not sure how to do it with button and without some sort of ID system. The servers are listed via "table" if that helps.
This should work for you:
<input type="text" onclick="this.select(); document.execCommand('Copy');" class="form-control" value="Server IP">
The code you were trying has unescaped parentheses.
This works with multiple input elements: https://jsfiddle.net/xx0gs6Lw/
EDIT
That must be only syntax error then, can you post your exact code? It should look something like this:
echo '<input type="text" onclick="this.select(); document.execCommand(\'Copy\');" value="' . $server->address . (($server->connection_port != '25565') ? ":" . $server->connection_port : null) . '">';

Help with appendTo() jquery function on form

I am a beginner, so keep that in mind.
so what I currently have working is my form successfully adds another input to the form, however it appears out of the form div. Basically I want it to appear within the div and above the submit button.
how do I do this?
here is main appendTo in my javascript:
var i = $('input').size() + 1;
$('a#add').click(function() {
$('<input type="text" value="user' + i + '" />').appendTo('form');
i++;
});
here is the form html as on request.
<div id="stylized" class="myform">
<form name="addstudents" method="post" action="add_students.php">
<div id="formHeader">
<h1>Add student(s)</h1>
<p>Please enter student's HEMIS number</p>
</div>
<label>Student: <span class="small">Enter HEMIS number</span> </label>
<input type='text' name="user_1">
<input type="submit" class="Mybutton" id="mybutton" name="submit" value='Submit Student(s)'>
<div class="spacer"></div>
</form>
AddRemove</div>
Any help would be greatly appreciated.
thanks
NEW PROBLEM: REMOVING!
here is my current remove JS, it simply removes the submit button first :(
$('a#remove').click(function() {
if(i > 3) {
$('input:last').remove();
i--;
}
});
$('a.reset').click(function() {
while(i > 2) {
$('input:last').remove();
i--;
}
});
Thanks again
You can use this snippet to insert the input before the button:
$('form #idofsubmitbutton').before($('<input type="text" value="user' + i + '" />'))
EDIT:
I played around with jsfiddle.com after your last edit and came upp with this:
var i = $('input').size() + 1;
$('a#add').click(function() {
$('div#stylized form input:submit').before($('<input type="text" value="user' + i + '" />'))
i++;
});
With the example html you posted this works. When I press the add link new inputs appear before the submit button.
If you still got problems you might have elements with duplicate ids.
var i = $('input').size() + 1;
$('a#add').click(function() {
$('<input type="text" value="user' + i + '" />').appendTo('div#divId');
i++;
});
This is not a "PHP form", once it's on the client, it's just HTML/CSS/Javascript. PHP is on the server.
.appendTo('form'); appends to the form TAG, not a "form div". If you have a DIV named "form" you need to use .appendTo('#form');

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