Load a script for the elements of an array - javascript

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.

Related

Clear table data <td> in editable table on focus using JavaScript or jQuery

I need to clear the data in a HTML td onfocus, similar to how it works in HTML input, but in an editable table that uses JQuery tabledit. Reason being that it is a CRUD table and it populates the table with data from a Db. If I want to edit one of the td, I don't want to have to delete the existing data, but rather when I click on the td, the value is set to "" and I can then just type the new data in.
<td><?php echo $row['payment_company']; ?></td>
I have tried as below, but it doesn't set the data value to empty
<td onfocus="this.value=''"><?php echo $row['payment_company']; ?></td>
So, this is what I am attempting to do the equivalent of:-
<input type='text' id='name' value = 'Hello' onfocus = 'this.value = ""' />
Update:
Because it's not working in my code here the generated HTML from the browser dev tools:
<td onclick="this.textContent='';" class="tabledit-view-mode">
<span class="tabledit-span">onclick textContent</span>
<input
class="tabledit-input form-control input-sm"
type="text"
name="payment_method"
value="onclick textContent"
style="display: none;"
disabled=""
>
</td>
A td has no value - you could use innerHTML or textContent instead. Furthermore the focus event fires if you give the element a tabindex. Alternatively you could use a click event.
Working example:
<table>
<td onfocus="this.innerHTML='';" tabindex="0">onfocus innerHTML / </td>
<td onfocus="this.textContent='';" tabindex="0">onfocus textContent</td>
<td onclick="this.innerHTML='';">onclick innerHTML / </td>
<td onclick="this.textContent='';">onclick textContent / </td>
</table>
To use jQuery-Tabledit you need to select the generated child input and empty its value. You could do this inline:
<td onfocus="this.querySelector('input').value = '';" tabindex="0">inline</td>
or with a function call:
<td onfocus="emptyCell(this);" tabindex="0">function</td>
function emptyCell(scope) {
$(scope).find('input').val('');
}
Working example:
$('#test-table').Tabledit({
editButton: false,
hideIdentifier: true,
columns: {
identifier: [0, 'id'],
editable: [[1, 'onfocus1'], [2, 'onfocus2'], [3, 'onclick1'], [4, 'onclick2']]
}
});
function emptyCell(scope) {
$(scope).find('input').val('');
}
.tabledit-remove-button {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.jqueryscript.net/demo/Creating-A-Live-Editable-Table-with-jQuery-Tabledit/jquery.tabledit.js"></script>
<table id="test-table">
<thead>
<tr>
<th>#</th>
<th>onfocus1</th>
<th>onfocus2</th>
<th>onclick1</th>
<th>onclick2</th>
</tr>
</thead>
<tbody>
<tr>
<td>row 1</td>
<td onfocus="this.querySelector('input').value = '';" tabindex="0">inline</td>
<td onfocus="emptyCell(this);" tabindex="0">function</td>
<td onclick="this.querySelector('input').value = '';">inline</td>
<td onclick="emptyCell(this);">function</td>
</tr>
</tbody>
</table>
You can do this. It should help
In your html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table>
<tr>
<td onclick="erase()">we</td>
</tr>
</table>
<script src="script.js"></script>
</body>
</html>
In your script.js
function erase() {
event.target.innerHTML = ""
}

Adding several lines of HTML to page using 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

How to get the dropdowns in jquery to work for the subsequent times without any on change event?

I have a main textbox(Months), on the change of which, a dropdown menu is created for another textbox(Days). Once I have these populated, I save it. Now when I go back to edit it, I directly want to change the option in the Days textbox, but since the dropdown of Days is triggered on change of the textbox "Months" I do not get the dropdown of days.
The following is my code:
function editValues() {
//initializations
$('.Months').on("change", function(){
monthsValueSet = this.value;
//pass monthsValueSet to database to retrieve values
$('.Days').html("");
for(i=0;i<data.length;i++){
$('.Days').append('<option>' + data[i].days + '</option');
}
});
}
//code for Save button
//code for edit
$("#daysMonthsTable").on("click", ".edit-months", function(event){
editValues();
});
My HTML code is:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<tr>
<td>
<div class="Months">
<table>
<tbody>
<tr>
<td><label>Months</label></td>
<td ><input type="text" class="Months"></td>
</tr>
</tbody>
</table>
</div>
</td>
<td>
<div class = "Days">
<table>
<tbody>
<tr>
<td><label>Days</label></td>
<td><input type="text" class="Days"></td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</body>
</html>
Do following
$("#daysMonthsTable").on("click", ".edit-months", function(event){
editValues();
$('.Months').trigger("change");
});

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
});

Table drop down selections not respecting Div

I have a container Div and within this I have a number of tables, the tables don't respect the div container size when I have a drop down menu being called. I cannot figure this one out, If I display the class the drop down filters are on to block, it respects the div. If i display it inline it ignores it! and over flow the container. Please help!
<table cellspacing="0" cellpadding="1" border="0">
<tr>
<!--START: catFilter_Filter-->
<td class="item1" style="border-right:1px solid #ccc;" >
<select name="catFilter" id="Select1" onchange="setCatFilter(this.value, document.frmsortby, false);">
<option value="">[catFilterName]</option>
<!--START: catFilter_Filter_Item-->
<option value="[catFilterId]-*-[catFilterName]-*-[catFilterChildId]-*-[catFilterChildName]-*-[catid]-*-">[catFilterChildName] ([numItems])</option>
<!--END: catFilter_Filter_Item-->
</select></td>
<!--END: catFilter_Filter-->
</tr>
</table>
<input type="hidden" name="hdnCatFilter" id="hdnCatFilter" value="[catFilter]" />
<script type="text/javascript">
function setCatFilter(strFilter, objForm, removeSubsequent)
{
if (removeSubsequent)
{
//alert(strFilter);
objForm.hdnCatFilter.value = strFilter;
}
else
{
objForm.hdnCatFilter.value = objForm.hdnCatFilter.value + '#' + strFilter;
}
//alert(objForm.hdnCatFilter.value);
objForm.submit();
}
function removeCatFilter()
{
var objForm = document.frmsortby;
objForm.hdnCatFilter.value = "";
objForm.submit();
}
</script></td>
</tr>
Your table is close before including the <input> and the <script> tags. You have a rogue </td> and </tr>. Move </table> after the last </tr>.

Categories

Resources