How to retrive the values from html and print it using javascript - javascript

This is my html code I want a javascript to get the values from the text box and print it on the same page
<body>
<header>
<h1>Welcome!</h1>
</header>
<form name="myform" method="post" action="#"><table align="center"><tr>
<td>First Name</td>
<td><input type="text" name="fn" id="fn" required="required"/></td></tr><tr>
<td>last Name</td>
<td><input type="text" name="ln" id="ln" required="required"/></td></tr><tr>
<td>DOB</td>
<td><input type="text" name="dob" id="dob" required="required"/></td></tr><tr>
<td>Description</td>
<td><textarea name="fn" cols="16" rows="5" id="txt" required="required"></textarea></td></tr><tr>
<td><input type="button" value="submit" onclick="validate()" /></td>
</tr>
</table>
</form>
</body>
</html>
I tired to print it in the table form using the javascript displayed below .. It is not working can u suggest some other code
val = ''
val += 'First Name: '.append("<tr><td>" + document.getElementById('fn').value + "</td></tr></br>");
val += 'Last Name: ' .append("<tr><td>" +document.getElementById('ln').value + "</td></tr></br>");
+ '<br>';
val += 'DOB: ' + document.getElementById('dob').value + '<br>';
val += 'Description: ' + document.getElementById('txt').value + '<br>';
divprint = document.createElement('div')
divprint.innerHTML = val; document.body.appendChild(divprint)

// grab a reference to the HTML input element
var elem = document.getElementById('fn');
// Retrieve its value (contained text)
var fnValue = elem.value;
// Print on the page
document.write(fnValue)
UPDATE
For other fields is similar to the above code:
var elemLn = document.getElementById('ln');
var LnValue = elemLn.value;
document.write('<br/>' + LnValue);
var elemDob = document.getElementById('dob');
var DobValue = elemDob.value;
document.write('<br/>' + DobValue);

try this ...
Create a div and append it into Body and place the Values in that div..
function validate() {
val = ''
val += document.getElementById('fn').value +'<br>';
val += document.getElementById('ln').value +'<br>';
val += document.getElementById('dob').value +'<br>';
val += document.getElementById('txt').value +'<br>';
divprint = document.createElement('div')
divprint.innerHTML = val;
document.body.appendChild(divprint)
}
USe this for table format
val = ''
val = "<tr><td>first Name: " + document.getElementById('fn').value +'</td></tr>';
val += "<tr><td>Last Name: " +document.getElementById('ln').value +'</td></tr>';
val += "<tr><td>DOB: " +document.getElementById('dob').value +'</td></tr>';
val += "<tr><td>Description: " +document.getElementById('txt').value +'</td></tr>';
divprint = document.createElement('table')
divprint.innerHTML = val;
// divprint.style.border = '1px solid black';
divprint.border = '1';
document.body.appendChild(divprint)

You can use this script before the </body> tag
<script>
function validate() {
return document.getElementById('txt').value;
// or do something with the value...
}
</script>

Add this right after </form>
<div id="emptyDiv"></div>
<script type="text/javascript">
function validate(){
document.getElementById("emptyDiv").innerText = document.getElementById("txt").value;
}
</script>
or the function can have:
document.getElementById("emptyDiv").innerText = document.myform.fn.value;

Related

How to send a table html as a serialize array to database?

I want to send my javascript and dynamic table to my database as a text variable.
I explained whatever I did:
I used jquery to get the values
Then I stored HTML table values in a java script array
I converted javascript array to JSON format
I sent JSON array to a php script by JQuery AJAX
But, I don’t know how to send it to database?
Here is my code:
function readTblValues() {
var TableData = '';
$('#tbTableValues').val(''); // clear textbox
$('#tblDowntimes tr').each(function(row, tr) {
TableData = TableData +
$(tr).find('td:eq(1)').text() + ' ' // downtime
+
$(tr).find('td:eq(2)').text() + ' ' // equipment
+
$(tr).find('td:eq(3)').text() + ' ' // starttime
+
$(tr).find('td:eq(4)').text() + ' ' // finishtime
+
$(tr).find('td:eq(5)').text() + ' ' // descriptio
+
'\n';
});
$('#tbTableValues').html(TableData);
}
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').html('<br>JS Array: <br>' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#tblDowntimes tr').each(function(row, tr) {
TableData[row] = {
"DOWNTIME": $(tr).find('td:eq(1)').text(),
"equipment": $(tr).find('td:eq(2)').text(),
"startdowntime": $(tr).find('td:eq(3)').text(),
"finishdowntime": $(tr).find('td:eq(4)').text(),
"description": $(tr).find('td:eq(5)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').html('<br>JSON array: <br>' + TableData.replace(/},/g, "},<br>"));
}
function sendTblDataToServer() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbSendTblDataToServer').val('JSON array to send to server: <br<br>' + TableData.replace(/},/g, "},<br>"));
$.ajax({
type: "POST",
url: "test.php",
data: "pTableData=" + TableData, // post TableData to server script
success: function(msg) {
// return value stored in msg variable
$('#tbServerResponse').html('Server Response:<br><br><pre>' + msg + '</pre>');
}
});
}
function print_r(arr, level) {
var dumped_text = "";
if (!level)
level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++)
level_padding += " ";
if (typeof(arr) === 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof(value) === 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
}
return dumped_text;
}
<html>
<head>
</head>
<body>
<form name="data-entry" method="post" action="data-entry.php">
<input id="product-name" name="product-name" />
<input id="product-quantity" name="product-quantity" />
<input name="Downtime" id="Downtime" />
<input name="equipment" id="equipment" />
<input type='time' name='startdowntime' id='startdowntime' />
<input type='time' name='finishdowntime' id='finishdowntime' />
<input type='text' name='description' id='description' />
<input type="button" value="add rows" id="btnAdd" onclick="addDowntime(this)" />
<input type="button" value="remove rows" onclick="deleteSelected()" />
<table id="tblDowntimes" class="downtime">
<tr>
<th><input type="checkbox" id="chkAll" onclick="chkAll_click(this)" /></th>
<th>downtime</th>
<th>equipment</th>
<th>start-time</th>
<th>finih-time</th>
<th>description</th>
</tr>
</table>
<input type="button" value="1. Read Table Values" name="read" onClick="readTblValues()" />
<input type="button" value="2. Store values in JS Array" name="store" onClick="storeAndShowTableValues()" />
<input type="button" value="3. Convert JS Array to json" name="convert" onClick="convertArrayToJSON()" />
<input type="button" value="4. Send json array to Server" name="send" onClick="sendTblDataToServer()" />
<div id="tbTableValues"></div>
<div id="tbTableValuesArray"></div>
<div id="tbConvertToJSON"></div>
<div id="tbServerResponse"></div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
and Here is my php code:
function processJSONArray() {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData);
var_dump($tableData);
}
echo processJSONArray();
With aforementioned code, I manage to get the array in client side, but when I use this code that error is appeared (Undefined variable: tableData)
if(isset($_POST[‘submit’])){
echo $tableData;
}

Logical Operators doesn't work in javascript and about node counts by input value

I'm trying to make node counter by id, node name, and attribute name&value!
Here I would like to check if every is empty then show "HERE IS NO VALUE OF YOU ENTERED".
here in the end of I try to use <&&> but it doesn't work!
also is that impossible to use just tag instead of in the end of the code? when i tried, it show eror :(
** I have no idea of how to count attribute name&value number..**
I'm realy begginer of javascript ! thank you in advance guys!!
this is my form html.
function javascript_click() {
/* 자바스크립트 id값 찾기 */
if (document.getElementById("value1").value) {
var val = document.getElementById("value1").value;
if (document.getElementById(val)) {
//var myNodelist = document.getElementById("val").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 노드명 찾기 */
else if (document.getElementById("value2").value) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 attribute 찾기 */
/* 자바스크립트 속성명&값 찾기 */
else if (
document.getElementById("value3").value &&
document.getElementById("value4").value
) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
} else if (
(document.getElementById("value1").value &&
document.getElementById("value2").value &&
document.getElementById("value3").value &&
document.getElementById("value4").value) == 0
) {
document.getElementById("cnt").innerHTML += "THERE IS NO VALUE OF YOU ENTERED<br>";
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>id</td>
<td><input type="text" id="value1"></td>
</tr>
<tr>
<td>node name</td>
<td><input type="text" id="value2"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">자바스크립트</button>
</div>
You may do validation like this:
if (document.getElementById("value1").value!=='') {
let val1 = document.getElementById("value1").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val1 + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}

Don't show the correct value JAVASCRIPT ARRAY

Today I was working to script, when I wanted to test it, I could see that it didn't works correctly it show the value [object Object] and not the real value (It didn't change the value too). It shows: Click here for see the picture
Its necessary click on "Edit" near of Google or Yahoo. I want to show the correct value when I click "Edit" near Google and Edit it when I click edit. I tried to change the value Checked[Item] for Checker[Name] but it only shows undefined.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.Checker.splice(item, 1, name.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
json:
var Checker = [{
name:"Google",
url: "google.es",
},
{
name:"Yahoo",
url: "yahoo.com",
}
]
Add another input tag for each attribute of Checkers objects.
<input type="text" id="edit-name">
<input type="text" id="edit-url">
And set each input separately
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
Working code:
var Checker = [{
name: "Google",
url: "google.es",
},
{
name: "Yahoo",
url: "yahoo.com",
}
]
document.getElementById('edit').style.display = 'none';
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el2.value;
var name = el.value;
if (url && name) {
Checker[item].name = name;
Checker[item].url = url;
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
<html>
<head>
<title>SSL Checker</title>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-url">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
You are getting correct output with [object Object], because Object.toString() returns exactly [object Object].
To represent your object in a custom format you can change the part of your SSL.Edit() method where you do el.value = Checker[item] to something like
el.value = Checker[item].name; // To show the name
el.value = Checker[item].url; // To show the url
el.value = Checker[item].url + ' ' + Checker[item].url; // To show both

write data in some text

i have following code
<html>
<script type="text/javascript">
function writeit()
{
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
tbox.value = '';
}
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
tbox.value = '';
}
}
</script>
<form name="a_form">
Product name:
<input type="text" id="a_tbox_1" name="a_tbox" value="" />
price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</html>
main idea of program is that i should give me possibilites to write two value product name and price and click after write ii it should write these informations in some text how to do it?please help
function writeit()
{
var strValue = '';
var tbox = document.getElementById('a_tbox_1');
if (tbox)
{
//tbox.value = '';
// add:
strValue = 'name: ' + tbox.value;
}
if(strValue != '')
strValue += ', ';
tbox = document.getElementById('a_tbox_2');
if (tbox)
{
//tbox.value = '';
// add:
strValue += 'price: ' + tbox.value + ' € :)';
}
alert(strValue);
// or do whatever you want with it...
}
Your questin is not clear, but try the code below and see if its what you are looking for:
<html>
<head>
<title></title>
<script type="text/javascript">
function writeit() {
var tbox = document.getElementById('a_tbox_1'), tbox2 = document.getElementById('a_tbox_2');
if (tbox.value && tbox2.value){
alert('product = ' + tbox.value + " :: price = " + tbox2.value);
// sendData('action.php?product=' + tbox.value + '&price=' + tbox2.value); (you can send your data via ajax)
tbox.value = '';
tbox2.value = '';
return false;
}
}
</script>
</head>
<body>
<form name="a_form">
Product name: <input type="text" id="a_tbox_1" name="a_tbox" value="" />
Price : <input type="text" id="a_tbox_2" name="a_tbox" value="" />
<input type="button" name="btn" value="write it" onclick="writeit()" />
</form>
</body>
</html>

JavaScript to show extra form fields

I have a form that has a block called "Product", containing text inputs. Inside that block, the user can press "add item" and have the JS show one more field. Till now everything works.
I've tried to add a function for adding a new "Product" block but no luck. Do you have any hints for me?
Product
Item: <input> Price: <input>
Item: <input> Price: <input>
<a>add item</a> <- this works
<a>add Product</a> <- this is the part that I can't figure out :(
Any help will be appreciated.
Thank you!
Update:
Here is the JS for the Item and Price fields:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("b.add-item").click(function () {
if(counter>5){ alert("Max 6 items allowed"); return false; }
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<span class="item">' +
'<label>Item:</label>'+
'<input type="text" name="item1[]" id="textbox' + counter + '" value="" >' +
'<label> Price:</label>'+
'<input type="text" name="price1[]" id="textbox' + counter + '" value="" >' +
'</span>'
);
newTextBoxDiv.appendTo(".items");
counter++;
});
$("b.remove-item").click(function () {
if(counter==1){alert("No more textbox to remove");
return false; } counter--;
$("#TextBoxDiv" + counter).remove();});
$("#getButtonValue").click(function () { var msg = ''; for(i=1; i<counter; i++){ msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); }alert(msg); });
});
</script>
Maybe make a table and add new rows?
HTML:
<table id="myTable">
<tr>
<th>Item</th>
<td><input /></td>
<th>Price</th>
<td><input /></td>
</tr>
<tr>
<th>Item</th>
<td><input /></td>
<th>Price</th>
<td><input /></td>
</tr>
</table>
<a onclick="add_row(); return false;">Add Product</a>
JavaScript:
function add_row()
{
var table = document.getElementById('myTable');
if(!table) return;
// Table row
var row = document.createElement('row');
table.appendChild(row);
// "Item:"
var th1 = document.createElement('th');
th1.innerText = 'Item:'
row.appendChild(th1);
// Item input
var td1 = document.createElement('td');
row.appendChild(td1);
var input1 = document.createElement('input');
td1.appendChild(input1);
// "Price:"
var th2 = document.createElement('th');
th2.innerText = 'Price:'
row.appendChild(th2);
// Price input
var td2 = document.createElement('td');
row.appendChild(td2);
var input2 = document.createElement('input');
td1.appendChild(input2);
}
I think this should work...

Categories

Resources