converting form to plain text - javascript

I have a page that generates forms depending on user choice. I want to know if there is a way to convert the form into plain text? Ex. The form has 4 fields, each has a label. I would like to take all the labels/fields and print them to the user as follows:
label1 field1
label2 field2
label3 field3
label4 field4
Is there a way to do so?

You can use jQuery to generate basic output, for example:
var texts = [];
$("form label").each(function() {
var oLabel = $(this);
var oInput = oLabel.next();
texts.push(oLabel.text() + " - " + oInput.val());
});
var plainText = texts.join("<br />");
$("#Output").html(plainText);
This will iterate over all the form labels, then take the next element of each label which is the input.
Live test case.

If you don't mind an extra file, with PHP.
You'd need to make a small php file to echo all the form information like this:
<?php
$label1 = "label1";
$label2 = "label2"; //Set all labels here
$label3 = "label3";
$label4 = "label4";
echo $label1 . " " . $_POST['field1'] . "<br />"; //Change to get depending on your method.
echo $label2 . " " . $_POST['field2'] . "<br />";
echo $label3 . " " . $_POST['field3'] . "<br />";
echo $label4 . " " . $_POST['field4'] . "<br />";
echo "Done.";
?>
and put that in it's own file. Set the form's action attribute to that file and it will print out all the data.

One method, without a JavaSCript library, is:
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(){
var labels = document.getElementsByTagName('label');
if (!document.getElementById('container')){
var container = document.createElement('ol');
container.id = 'container';
}
else {
var container = document.getElementById('container');
while (container.firstChild){
container.removeChild(container.firstChild);
}
}
for (var i=0,len=labels.length; i<len; i++){
if(document.getElementById(labels[i].getAttribute('for'))){
var newLi = document.createElement('li');
var iText = document.createElement('span');
newLi.innerHTML = labels[i].innerHTML;
iText.innerHTML = document.getElementById(labels[i].getAttribute('for')).value;
newLi.appendChild(iText);
container.appendChild(newLi);
}
}
document.getElementsByTagName('body')[0].appendChild(container);
return false;
};
JS Fiddle demo.
References:
node.appendChild()
document.createElement().
document.getElementById().
document.getElementsByTagName().
element.getAttribute().
element.innerHTML.
for () {...}.
node.firstChild.
node.removeChild().
while () {...}.

You may get the value for labels and fields in javascript using
var label1 = getElementById("id").name
Create a string formatted as you want to show the user and show all the values with
document.write(string);

Related

JQuery and the editableSelect package is not allowing me to Filter a select menu with a RegExp. JavaScript and jQuery nub or novice

Here is a select list built using PHP, MariaDB, and HTML:
echo "<select name='companylist' id='companylist' size='86' value='' tabindex='1' >";
echo "<option value=''></option>";
echo "<option value='0-Create a New Company'>0-Create a New Company</option>";
foreach ($companyResult as $company) {
echo "<option id='".$company['Company_Key']."'
value='".$company['Company_Key']."'>".$company['Company_Names']."</option>";
}
echo "</select>";
It builds a dropdown list that is appropriate for my application.
Next, I built this testing script to find out if I was on the right track in the use of RegExp to filter the dropdown select list dynamically, and it works well, for its purpose. I only built it because the list following it is giving me fits.
echo "<script>";
echo "$('#companylist option').each(function() {
var Val = this.text;
var Filter='W';
var CompRegex = new RegExp('^'+Filter);
if(CompRegex.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
})";
echo "</script>";
This above gives me the following console output:
RegExp with Filter has found the following Val starting with this Filter: W
Val = Welch Tile
RegExp with Filter has found the following Val starting with this Filter: W
Val = West Michigan Molding
RegExp with Filter has found the following Val starting with this Filter: W
Val = WL Molding of MI
This is a good start.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('select.editable-select', function (e, li) {
console.log('value = ' + document.getElementById('companylist').value);
console.log('li.val() = '+li.val());
getCustomer_Names(li.val());
getTool_Numbers(li.val());
getPart_Name(li.val());
newCompany_Name();
})";
echo "</script>";
This above script loads other menus, as expected, once the user selects an item.
The next script here simply will not let me get the option text that the user sees in the list. I have 5 days into this, because I am new to JQuery and not a master of Javascript either, but I do read all kinds of sites for help, including reference guides, and the support boards (thank you for this one!), but I would like a happy ending soon. Any help, as stated, would be very appreciated.
echo "<script>";
echo " $('#companylist')";
echo " .editableSelect()";
echo " .on('input.editable-select', function () {
$(this).each(function() {
var Val = this.text;
var Filter = this.value;
var CompRegExp = new RegExp('^'+Filter);
console.log('Val = '+Val);
console.log('Filter = '+Filter);
console.log('CompRegExp = '+CompRegExp);
if(CompRegExp.test(Val)){
console.log('RegExp with Filter has found the following Val starting with this
Filter: '+Filter);
console.log('Val = ' + Val);
}
else {
// remove from select list
}
});
});";
echo "</script>";
This above script gives me
Val = undefined
Filter = a
CompRegExp = /^a/
It is the "Val = undefined" that is my undoing.
I also took a long-view of this problem and wrote a jQuery/JavaScript program that clears the dropdown list and then recreates the options by having a PHP program re-query the database to get the values that match a SQL LIKE 'Input%' which I will include to show you the depth of effort here. The problem here is that I could not get the dropdown menu to stay open even though I issued .editableSelect('show'); as instructed in the editableSelect git website to open the dropdown menu and show the modified list, although, if I clicked in the field and moved the cursor around, it would pop the menu open with the values that matched the return from MariaDB. It follows:
echo "<script>
function getCompany_Names(comp_val)
{
if(document.getElementById('companylist').value.substring(0,8) != '0-Create'){
$('#companylist').editableSelect('clear');
var xhttp;
if (comp_val === null || comp_val === '' ) {
$('#companylist').editableSelect('add', '<option value=></option>');
$('#companylist').editableSelect('add', '<option value=0-Create a New Company>0-Create a
New Company</option>');
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var select = $('#companylist');
var c_text = this.responseText;
console.log('comp_ctext = ' + c_text);
c_text = JSON.parse(c_text);
$.each($(c_text),function(key,value){
if (value.compname == 'One or more Company Names are Probably Not Entered.')
{
$('#companylist').editableSelect('add','<option value=' + 'One or more Company
Names are Probably Not Entered.' + '>One or more Company Names are Probably Not
Entered.</option>');
}
else
{
console.log('<option id=\'' + value.compkey + '\' value=\'' + value.compkey + '\'>'
+ value.compname + '</option>');
$('#companylist').editableSelect('add','<option id=\'' + value.compkey + '\'
value=\'' + value.compkey + '\'>' + value.compname + '</option>');
}
}); // end .editableSelect('add',...)
}
};
xhttp.open('GET', 'getCompany_Names.php?q='+comp_val, true);
xhttp.send();
}
}
</script>";
This is all because my patron does not like the default filter behavior of the editableSelect package where it matches what is typed to any values anywhere in the dropdown and wants some dropdowns to come up matching the input to the results from first character onward with something like (exactly like) a regex of /^input_variable/.
Thank you for your time.
R
its not a solution, just easier to ask something..i'll delete more later
i dont understand this syntax: no selector before .on??
.on('input.editable-select', function () {
$(this).each(function() {
i see $(this) that means you have more input?
the problem with these lines:
var Val = this.text;
var Filter = this.value;
what is Val? because this.text is not functional for input? (its the reason Val => undefined)
this.value gives what you type in input
This is WAY more complicated than my core problem actually is. I have posted another question that is just my actual failure. It is at: [https://stackoverflow.com/questions/66801231/the-use-of-https-github-com-indrimuska-jquery-editable-select-for-editable-sel]
I think I have an example of an example page the creator put together and it has a function their I am only just starting to understand, but it is all about adding values to the list. I will study it and post my results on the core issue page. Thank you to all who tried to help. Here's one for brevity.

I want to add html text filed value in other text filed value will changed

I want to set PHP variable in HTML text field during other text field value will be changed.
<input type="text" class="form-control" name="refrence" id="refrence" onkeydown="myFunction(event)"
placeholder="Reference" autocomplete="off">
javaScript
<script>
function myFunction(event) {
var x = event.keyCode;
if (x == 17) {
var name = document.getElementById("companyName");
var address = document.getElementById("address");
alert("df");
name.value = "<?php echo $invoiceValues['order_receiver_name']; ?
>;
address.value = "<?php echo invoiceValues['order_receiver_address']; ?>;
}
}
</script>
php code
public function getrefer() {
$sqlQuery = "SELECT * FROM " . $this->invoicevendortable
. " WHERE reference = '" . $_SESSION['refrence'] . "'";
return $this->getData($sqlQuery);
}
You need to read the current value via JS; PHP only gets parsed on page load!
var refDomElement = document.querySelector( '#reference' )
, useDomElement = document.querySelector( '#companySomething' )
useDomElement.value = refDomElement.value

How to turn extracted href into hyperlink

I'm working on a tagging part on a site similar to Facebook. The idea is that whenever someone types # in the post area, a drop down menu appears containing all of his friends. He then picks who he wants to tag and clicks on that person's profile. I have a javascript function which detects when # is pressed, and then calls another js function which then in turn sends an ajax request to a php file for the list. And this part works great.
So when the user clicks on someone from their friend list, I set it up so that an href part containing the friend's username is extracted from the php file as plain text, and then displayed as a text string right after the # character in the post area (I prevented following to the profile after clicking with return: false). So, for example, when someone wants to choose John Smith, he presses #, the list appears, he picks John Smith, clicks on his profile, the list disappears, and then the username appears after #, like this: #john_smith
Now the trouble is that I would want to make john_smith after # into a hyperlink that would lead to John Smith's profile, instead of it being just plain text. And I've been really struggling to find a solution. Any help would be much appreciated.
Thanks a lot! :)
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
**//js functions**
function userTag(user) { // for ajax
$.post("includes/handlers/ajax_user_tag.php", {userLoggedIn:user},
function(data){
$('.tag_results').html(data);
});
}
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var x = $(this).attr('href');
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.val(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}
**//js code**
$("#post_text").keydown(function (e) { // listens for #
if(e.which == 50)
userTag('<?php echo $userLoggedIn; ?>');
if(e.which != 50)
$('.tag_results').html("");
});
$('.tag_results').hover(function(e) { //calls textTag function on hover
textTag();
});
**//Empty div populated by ajax results**
<div class="tag_results">
</div>
EDIT:
I found out what the problem was, purely by accident. In the file with the php classes, strip_tags was used for all posts. So what I wanted to do was practically impossible with that turned on. Now it's working as it should. Thanks everyone for help! :)
I don't believe that your click event is capturing the click, because your php is dynamically creating the list element. Also your function, textTag() doesn't actually apply the event until that function is run, so it could be creating issues. Change your JS to -
$(document).on('click', '.displayTag a', function() {
var href = $(this).attr('href');
//other code applying href to new anchor tag in proper format
});
First I would change a little bit the PHP response in order to make it easier to get the firend's full name.
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div class='fullname'>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
Then I would modify the JS function
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var fullname = $(this).find('.fullname').text();
var x = ''+fullname +'';
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.html(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}

How to get a anchor link text inside a javascript and calling with arguments

I wrote a function like to get a user from server and i got it . Now i create a links for each users using a href inside java script . This is working fine . Now i want to execute a function when i user click the link (with the corresponding user name)
var User_id = document.querySelector(".sidebar-name");
//getting array of user
function list(user){
User_id.innerHTML = "";
for( i = 0; i < user.length; i++ ){
User_id.innerHTML+= "<a href='#' onclick = 'javascript:calluser(this);' style='text-decoration:none'>" + user[i] + "</a>" + "<br />";
}
}
function calluser(this){
alert(user);
// i need to print the corresponding username or anchor text .
// how can i solve this ?
}
I tried with id inside a href . But this is not unique so it won't work . How can i solve this ?
"function calluser(this) " Is a Syntax error.
Rename "this" with something else like "a":
var User_id = document.querySelector(".sidebar-name");
function list(user){
User_id.innerHTML = "";
for(var i=0; i<user.length; i++){
User_id.innerHTML+= "<a href='jacascript:void();' onclick='javascript:calluser(this);' style='text-decoration:none'>" + user[i] + "</a>" + "<br />";
}
}
function calluser(a){
alert(a.text);
}

PHP - Onchange reload page with value of select

I am working on PHP. I have three dynamic dropdown boxes. On the basis of first selected value I change the content of second select box and same case for the third. I have achieved this functionality through javascript. The problem I am having is my code works perfectly on localhost but when I upload the code on the online server the page keeps on reloading. Let me first share my code so that you can have an idea of what I am talking about
javascript
<script>
var valnew = <?php echo $cat3; ?> ;
function reload() {
var val = form.cat.options[form.cat.options.selectedIndex].value;
var text = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'douglas-college.php?cat=' + val + '&text=' + text
}
function reload3(form) {
var val = form.cat.options[form.cat.options.selectedIndex].value;
val2 = form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'douglas-college.php?cat=' + val + '&cat3=' + val2;
}
function reload4(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
}
</script>
<?php
$query1 = mysql_query("SELECT * FROM course");
echo "<select name='cat' class='input-large form-control' onchange=\"reload(this.form)\">";
if (!isset($_GET['cat'])) {
echo '<option>Select one</option>';
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
} else {
while ($row = mysql_fetch_array($query1)) {
echo '<option value="' . $row['courseID'] . '">' . $row['courseName'] . '</option>';
}
}
echo "</select>";
?>
I have added only one selectbox php code right now. I can share the whole code upon request. I have checked the page by using only one dropdown but still page keeps on refreshing. Means the page is keep on reloading again and again
The real problem is that in :
http://smithdeveloper.com/test/js/sitefunction.js
$('select').change(function() {
$('option').css('background', 'white');
$('option:selected').css('background', '#ff87c3');
}).change();
U trigger .change() on all select elements.
So thats why onchange events are called immediately after page load.
So every time page loads u call change event and listen to change event and fire reload() function
first ditch the inline onchange="" events inside select tags..
Than remove your script from begining of the file and save this in file that you include in the end of the page, sitefunction.js inside document.ready hook.
Here is mine jsfiddle and I changed your functions a bit..
$('[name=cat]').on('change', function(){
var val1 = form.cat.options[form.cat.options.selectedIndex].value;
var txt1 = form.cat.options[form.cat.options.selectedIndex].text;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val1 + '&text=' + txt1
});
$('[name=subcat]').on('change', function(form) {
var val2 = form.cat.options[form.cat.options.selectedIndex].value;
var txt3= form.subcat.options[form.subcat.options.selectedIndex].value;
self.location = 'http://smithdeveloper.com/test/douglas-college.php?cat=' + val2 + '&cat3=' + txt3;
});
$('[name=subcat3]').on('change', function(form) {
var val3 = form.subcat3.options[form.subcat3.options.selectedIndex].value;
var text = form.subcat3.options[form.subcat3.options.selectedIndex].text;
self.location = 'course-title.php?inst_id=' + val3 + '&coursecode=' + valnew;
});
http://jsfiddle.net/mkdizajn/wLz2g3sw/
hth, cheers, k

Categories