Adding several lines of HTML to page using Javascript - javascript

I have an HTML page that displays some information. In javascript, I have a var submitted, that as you can see below, will add a line of text to my HTML if it meets a certain condition.
<script type="text/javascript">
if (submitted == "yes") {
document.write("<div>SHOW ONLY IF SUBMIITED</div>");
}
</script>
Thing is, I want to add several lines of HTML code to my page and I've come to understand that document.write is not the appropriate method to do this. However, every alternative I've found doesn't seem to work for me.
Here's a snippet of the HTML I want to add:
<form>
<table>
<tr>
<td>Surname</td>
<td>Given name</td>
</tr>
<tr>
<td><input type="text" name="ln" value=""/></td>
<td><input type="text" name="gn" /></td>
</tr>
</table>
</form>
The full code is much longer.
My page:
<script type="text/javascript">
if (submitted == "yes") {
document.write("<div>SHOW ONLY IF SUBMIITED</div>");
}
</script>
<body>
<div class="Title" style="display:block; width=100%;">
<h1>FORM TITLE</h1>
</div>
<div id="injecthere"></div>
..... the rest of my html code
</body>
The code needs to be injected on page load, not by any input from the user (no buttons, etc)
How can I add my code to my HTML page WITHOUT jQuery (basic java only pls)?

You can use .innerHTML property of the element
var submitted="yes"
var code=`<form>
<table>
<tr>
<td>Surname</td>
<td>Given name</td>
</tr>
<tr>
<td><input type="text" name="ln" value=""/></td>
<td><input type="text" name="gn" /></td>
</tr>
</table>
</form>`;
if (submitted == "yes") {
document.querySelector("body").innerHTML+=code
}
<body></body>

Here' a way to do it that employs javascript's "template literal" syntax -- using backticks (`) -- to enclose your markup.
function addStuff(){
const formHTML = `
<table>
<tr>
<td>Surname</td>
<td>Given name</td>
</tr>
<tr>
<td><input type="text" name="ln" value=""/></td>
<td><input type="text" name="gn" /></td>
</tr>
</table>`;
const newForm = document.createElement("form");
newForm.innerHTML = formHTML;
document.querySelector("body").appendChild(newForm);
}
#existing-content {
height: 50px;
width: 400px;
margin: 10px;
padding: 10px;
border: 1px solid gray;
}
<button onclick="addStuff()">Append HTML to Page</button>
<div id="existing-content">Existing content</div>
If you want to support browsers that don't support template literals, you might end up using tedious iterations of createElement (and/or createTextNode) with appendChild to add each node to the DOM one at a time, starting with the most deeply nested element and working your way out.
If for some reason your page doesn't have a body element, this would work to find what element to append the new markup to:
document.querySelector("#existingContent").parentNode.appendChild(newForm);

Basically what you want to do is designate a DOM element that you can inject the dynamically built HTML into - you do that by setting or appending to it's innerHTML property:
const buttonEl = document.querySelector('#htmlBtn');
const targetEl = document.querySelector('#target');
let divId = 0;
buttonEl.addEventListener('click', (e) => {
//innerHTML is what you want to use instead of document.write
targetEl.innerHTML += `<div id=dynamic-html-${divId}>Added HTML ${divId}</div>`;
divId += 1;
});
<input id="htmlBtn" type="button" value="Add some HTML to the DOM" />
<div id="target"></div>

You have the js property innerHTML. So it will look like:
<script type="text/javascript">
if (submitted == "yes") {
document.getElementByID("myDivID").innerHTML = '<form><table><tr><td>Surname</td><td>Given name</td></tr><tr><td><input type="text" name="ln" value=""/></td><td><input type="text" name="gn" /></td></tr></table></form>';
}
</script>
<div id="myDivID"></div>

var submitted = "yes";
function showFormIfNeeded() {
if (submitted === "yes") {
var form = document.getElementById("myForm");
form.style.display = "block";
}
}
#myForm {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body onload="showFormIfNeeded()">
<form id="myForm">
<table>
<tr>
<td>Surname</td>
<td>Given name</td>
</tr>
<tr>
<td><input type="text" name="ln" value="" /></td>
<td><input type="text" name="gn" /></td>
</tr>
</table>
</form>
</body>
</html>
Try this

Related

add values in a textarea using a add button & it should be displayed in other textarea appended in a new row

How to add values in a textarea using a add button & that values should be displayed in other textarea using HTML5
<script src="http://code.jquery.com/jquery-1.11.3.min.js">
jQuery('#constraint_btn').click(function(){
var newVal = jQuery('#consEditor_txtarea').attr('value');
jQuery('#new_html').show();
jQuery('#new_consEditor_txtarea').attr('value',newVal);
});
</script>
<table>
<tr>
<td valign="top"><label>Constarint Editor </label></td>
<td><textarea id="consEditor_txtarea"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="button" name="" id="constraint_btn" value="Add Constraint" /></td>
</tr>
<tr id="new_html">
<td><label>Added Constraints </label></td>
<td><textarea id="new_consEditor_txtarea"></textarea></td>
</tr>
</table>
You need to close the script tags with the src and start a new script tag - if there is a src attribute, then you cannot have content inside the script
You need https (and preferably update the jquery to a newer version) in the jQuery source
You did not call the fields the same in the code as in the HTML
You need to execute the code after the page has loaded or the fields rendered - here I wrapped in the $(function() {}) load event handler
#new_html {
display: none;
}
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(function() {
$('#constraint_btn').click(function() {
let oldVal = $('#consEditor_txtarea').val().trim();
let newVal = $('#new_consEditor_txtarea').val().trim();
const vals = newVal.split("\n").filter(item => item);
if (oldVal) vals.push(oldVal);
$('#consEditor_txtarea').val(""); // remove
$('#new_html').show();
$('#new_consEditor_txtarea').val(vals.join("\n"));
});
});
</script>
<table>
<tr>
<td valign="top"><label>Constraint Editor </label></td>
<td><textarea id="consEditor_txtarea"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="button" name="" id="constraint_btn" value="Add Constraint" /></td>
</tr>
<tr id="new_html">
<td><label>Added Constraints </label></td>
<td><textarea id="new_consEditor_txtarea"></textarea></td>
</tr>
</table>

Traversing through a html table

I have a table with this structure:
<table>
<tr>
<td>link1</td>
<td>link2</td>
<td>link3</td>
<td><input type = "checkbox" onclick = "func()"></td>
</tr>
</table>
function func(){
//I have to alert link1 here.
}
Can anybody tell me how to do this?
Thanks in advance.
EDIT 1: There are multiple rows of the same type and clicking on a particular check-box should alert the corresponding <a> text.
you can do like this with jquery. Just change the number of the eq. And all table with input with class of checkbox it will run. you can play with it.
$('.checkbox').on('click',function(){
var e = $(this).closest('table').find('td a');
alert(e.eq(0).text());
});
table{
border: 1px solid red;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table1">
<tr>
<td>link1</td>
<td>link2</td>
<td>link3</td>
<td><input type = "checkbox" class="checkbox"></td>
</tr>
</table>
<table class="table2">
<tr>
<td>link4</td>
<td>link5</td>
<td>link6</td>
<td><input type = "checkbox" class="checkbox"></td>
</tr>
</table>
Since you are using jQuery, use a jQuery handler in which you can find the a value in the same row
jQuery(function($) {
$('#my-table input[type="checkbox"]').change(function() {
alert($(this).closest('tr').find('td:first-child a').text())
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="my-table">
<tr>
<td>link-1-1</td>
<td>link-1-2</td>
<td>link-1-3</td>
<td>
<input type="checkbox">
</td>
</tr>
<tr>
<td>link-2-1</td>
<td>link-2-2</td>
<td>link-2-3</td>
<td>
<input type="checkbox">
</td>
</tr>
</table>

javascript redirection only on second try

I wrote a little "webpage" to start streams on my xbmc with jsonrpc. Now the problem I am facing is that i always have to send the form request twice to make it work. could it be that I am using the window.open function wrong? or am I missing something?
<html>
<body>
<head>
<script type="text/javascript">
function postFunction() { // inside script tags
var vForm = document.getElementById("frmGui");
var vStrServer = "";
var vStrFile = "";
var vStrPost = "http://";
vStrServer = vForm.idServer.value;
vStrFile = vForm.idFile.value;
vStrPost += vStrServer+"/jsonrpc?request={\"jsonrpc\":\"2.0\", ";
vStrPost += "\"id\":0, \"method\": \"Player.Open\", \"params\":{\"item\""
vStrPost += ":{\"file\":\""+vStrFile+"\"}}}";
window.open(vStrPost,"_self");
}
</script>
</head>
<table>
<tr>
<form id="frmGui" name="gui" action="#" onSubmit="postFunction(this)" methode="POST">
<td><input id="idServer" name="server" type="text" value="IP_ADRESS"/></td>
</tr>
<tr>
<td><input id="idFile" name="file" type="text"/></td>
</tr>
<tr>
<td><input type="submit"/></td>
</tr>
</form>
</table>
</body>
</html>
Try to put it into window.onload(cb).
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload
Why you passed argument whene you call postFunction() ? it has not argument upon decliration right way is
<form id="frmGui" name="gui" action="#" onSubmit="postFunction()" methode="POST">
remove this inside postFunction brace

Jsfiddle code not working in localhost wamp

i have implemented validation for fundtransfer in jsfiddle.
it works fine in jsfiddle but not working in localhost.
i am using wamp.
here is my jsfiddle link - http://jsfiddle.net/BzdfN/31/
but when i am implementing this in localhost.its not working.
my html code is
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="validate.js"></script>
<title> Infy Bank Fund Transfer Entry Page </title>
</head>
<body>
<table class="layout" border="0" width="90%" align="center">
<form name="addcust" method ="POST" action ="http://localhost:8080/myapp/jsp/AddCustomerJSP.jsp">
<td colspan="2">
<table border="0" width="70%" align="center">
<tr>
<td align="center" colspan="2">
<div class="heading2">Infy Bank</div>
</td>
</tr>
<tr>
<td align="center" colspan="2"><p class="heading3">Fund transfer</p></td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<td>Payers account no<span class="mandatory">*</span></td>
<td><input type="text" name="text10" id="text10" size="25" />
<div width="100%" id="equal"></div>
</td>
</tr>
<!--<tr>
<td>Payees account no<span class="mandatory">*</span></td>
<td>
<input type="text" name="name" value=2008 maxlength="25">
</td>
</tr>
<tr>
<td>Amount<span class="mandatory">*</span></td><td><input type="text" Value=500 name="state" maxlength="25"></td>
</tr>
<tr>
<td>Description<span class="mandatory">*</span></td><td><input type="text" name="pin" value=self maxlength="6"></td>
</tr>
<tr>
<td><span class="mandatory">*mandatory field</span></td>
<td><input type="submit" name="AccSubmit" value="Submit" onClick="return validatebal();">
<input type="reset" name="res" value="Reset"></td>
</tr>-->
</form>
</table>
<p align="right">Home</p>
</body>
</html>
and my validate.js is
$("#text10").keyup(function(){
$("#text10").blur();
$("#text10").focus();
});
$("#text10").change(function(){
var name = $('#text10').val();
var numbers = /^[0-9]+$/;
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (name == "" || name == " " )
{
$("#equal").show();
$("#equal a").html("please enter account number");
}
else if(name.match(numbers))
{
$("#equal").hide();
$("#equal a").html("correct account number"); // alert('All Boxes have elements.');
}
else if(name.match(specialChars))
{
$("#equal").show();
$("#equal a").html("correct account number"); // alert('All Boxes have elements.');
}
else
{
$("#equal").show();
$("#equal a").html("please check your account number correctly");
}
});
So guys can you what i am doing wrong.
please help
start your jQuery with:
$( document ).ready(function() {
.../ and end with:
});
maybe this will solve your problem
In jsfFiddle your code is executed on the onload event.
But with including validate.js in the head the content of the script is execute right at the place where you placed <script src="validate.js"></script>. So your jQuery selectors don't find any elements, because they are not in the DOM at the time the script is executed.
You have different possibilities.
Wrap the content of your validate.js into jQuery(function() { /*your code of validate.js **/ })
Another possibility is to place <script src="validate.js"></script> at the end of your document instead placing it in the head.
You can use delegated events like $(document).on("keyup","#text10", function() { /* .... */ }); that way it does not matter if #text10 is in the DOM at this time.
wrap your validate.js code in jQuery ready function as follows should solve the issue:
$(document).ready(function() {
// validate.js code
});

Load a script for the elements of an array

I am trying to create a dynamic form where you can order something.
In basic form, we have one row, but if you want to order more things we can dynamically without reloading the page, add the new row. So far everything is working properly for me, but in this form we have two dropdown ("input select") lists. These drop-down lists are dependent on each other and do not know how to load them the relationship between them and the option of choice. I have tried many different examples from the internet, but always work correctly only the first default row. Dynamically created rows are no longer dependent on one another.
If I am doing something wrong, and you know a better way, please show me this way.
I ask you for help, because I really depend on that. Thank you in advance. ;)
Update
Hmm .. Now I understand, but I do not know much how to use it in my web page code. Will show you the web page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><br>
<html><br>
<head><br>
<title>Dynamic forms</title><br>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><br>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><br>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script><br>
<script language="javascript" src="chainedselects.js"></script><br>
<script language="javascript" src="exampleconfig2.js"></script><br>
</head>
<body onload="initListGroup('vehicles', document.formm.elements['group[]'], document.formm.elements['product[]'], 'cs')">
<script type="text/javascript">
$(document).ready(function(){
var i = 2;
var templateRow = jQuery.format($("#template").val());
function addRow() {
var ii = i++;
$(templateRow(ii)).appendTo("#listProducts tbody");
$("#removeProduct_" + ii).click(function(){
$("#row_" + ii).remove();
});
}
$("#addProduct").click(addRow);
});
</script>
<!-- Template row in the table -->
<textarea id="template" style="display:none;" cols="1" rows="1">
<tr id="row_{0}" valign="top">
<td>{0}.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="remove.png" id="removeProduct_{0}" alt="remove"></td>
</tr>
</textarea>
<!-- This summary table -->
<form name="formm" action="parser.php" method="post">
<table id="listProducts" name="list">
<thead>
<tr>
<th>Nr</th>
<th>Group</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>+/-</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="3" align="left">
<input type="submit" name="send" value="Send" style="width: 100px;">
</th>
</tr>
</tfoot>
<tbody>
<tr valign="top">
<td>1.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="add.png" id="addProduct" alt="add"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
This is a parser.php:
<?php
$data = array();
$data['Groups'] = $_POST['group'];
$data['Products'] = $_POST['product'];
$data['Prices'] = $_POST['price'];
$data['Quantity'] = $_POST['quantity'];
$result = print_r($data,true);
echo "<pre>$result</pre>";
?>
Here is link to all code.
The click events are not attached to the newly created rows, so you need to make sure that any new rows, after they are created have click events attached to them.
function dependantFunction() {
/* code */
}
function addNewRow() {
var a=document.createElement("div");
var b=document.createElement("img");
b.src="images/add.png";
b.addEventListener("click", dependantFunction, false);
a.appendChild(b);
document.getElementById("rowholder").append(a);
}
Then all new rows should have all the necessary events attached to them.

Categories

Resources