How to add dynamic fields in ajax post call - javascript

function submitData(productSubtypeId, orderNumber) {
// Get all dynamic input fields belonging to a class so that we can check if a value for those were provided or not
var cells = document.getElementsByClassName(
orderNumber + "-" + productSubtypeId + "-" + "supplData"
);
for (var i = 0; i < cells.length; i++) {
if (
document.getElementById(
orderNumber + "-" + productSubtypeId + "-" + cells[i].name
).value == ""
)
alert(cells[i].name + " is required");
return false;
}
if (
confirm(
"Confirm submitted data for order " +
orderNumber +
"?\nDon't forget to close the order after submitting supplemental data."
)
) {
$.ajax({
url: "FillSupplData.cfm",
type: "post",
data: {
productSubtypeId: productSubtypeId,
orderNumber: orderNumber,
DEPLOY_DATE: document.getElementById(
orderNumber + "-" + productSubtypeId + "-" + "DEPLOY_DATE"
).value,
},
success: function (response) {
// Remove data submit (supplemental) button once data is successfully submitted
$(
"#" + orderNumber + "-" + productSubtypeId + "-" + "fillSupplData"
).remove();
// Disable all supplemental data input fields for this order
//var cells = document.getElementsByClassName(orderNumber + '-' + productSubtypeId + '-' + 'supplData');
for (var i = 0; i < cells.length; i++) {
cells[i].disabled = true;
}
// Make order close button visible
document.getElementById(
orderNumber + "-" + productSubtypeId + "-" + methodInvoked
).style.display = "block";
},
error: function (jqXHR, exception) {
var msg = "An error occurred";
alert(msg);
},
});
}
}
This is part of the HTML code I have :
<table class="order w100p" id="3202643984">
<tbody>
<tr>
<td style="width: 50%; vertical-align: top">
<div>
<table class="order-header">
<tbody>
<tr>
<th style="width: 15%">Order Number</th>
<th style="width: 20%">Scheduled Ship Date</th>
<th style="width: 30%">Customer Name</th>
<th style="width: 20%">Customer Number</th>
<th style="width: 20%">Customer PO</th>
</tr>
<tr>
<td>
<a
id="3202643984-104"
class="orderLink"
style="display: block"
>3202643984</a
>
</td>
<td />
<td>LOGAN COUNTY SHERIFF</td>
<td>1000269359</td>
<td>RG212738</td>
</tr>
</tbody>
</table>
</div>
</td>
<td style="width: 30%; vertical-align: top">
<div id="3202643984-line-items">
<table>
<tbody>
<tr>
<th style="width: 15%">Line Num</th>
<th style="width: 20%">Part Number</th>
<th style="width: 15%">Qty</th>
<th style="width: 50%">Description</th>
</tr>
<tr>
<td>1.1</td>
<td>AAS00100</td>
<td>1</td>
<td>EVIDENCE BWC AS A SERVICE</td>
</tr>
<tr>
<td>2.1</td>
<td>AAS00101</td>
<td>1</td>
<td>VIDEO-AS-A-SERVICE</td>
</tr>
</tbody>
</table>
</div>
</td>
<form id="SupplDataForm" action="FillSupplData1.cfm" method="post" />
<input type="hidden" name="orderNumber" value="3202643984" />
<input type="hidden" name="productSubtypeId" value="104" />
<input type="hidden" name="toolSectionId" value="Watchguard" />
<td style="vertical-align: top">
<div style="padding-bottom: 10px">
<strong>Additional Order Data</strong>
</div>
<div style="width: 150px">
<div>
Deploy Date:
<input
type="date"
id="3202643984-104-DEPLOY_DATE"
name="DEPLOY_DATE"
placeholder="Deploy Date"
value=""
class="3202643984-104-supplData"
style="border: 2px solid lightgray; width: 90%"
size="200"
required
/>
<strong style="color: red; font-size: 24px">*</strong>
</div>
</div>
</td>
<td style="width: 10%; vertical-align: top; padding-top: 40px">
<input
id="3202643984-104-fillSupplData"
style="float: right; width: 125px; margin: 0px 5px"
type="button"
class="button"
value="Submit Data"
onclick="submitData(productSubtypeId = 104, orderNumber = '3202643984');"
/>
<button
type="button"
id="3202643984-104-close"
onclick="manualMethod(productSubtypeId = 104, methodInvoked = 'close', orderNumber = '3202643984');"
style="margin-bottom: 10px; display: none"
>
Close
</button>
</td>
</tr>
</tbody>
</table>
Now the issue I need help with is that the input fields for the orders are dynamic depending on the product sub type they belong to and I need to grab those fields and create variables so that I can submit the values in ajax call.
data: {
productSubtypeId: productSubtypeId,
orderNumber: orderNumber,
DEPLOY_DATE : document.getElementById(orderNumber + '-' + productSubtypeId + '-' + 'DEPLOY_DATE').value
}
Here, I have DEPLOY_DATE but how can I do it so that I don't have to hardcode field name and value. I can have 2-3 different fields here depending on what fields are required for this product sub type.
Thanks for your help in this regard

Looks like you've got everything you need in the <form> itself.
Use the .serialize() function to capture all the <form> element data. I would also recommend listening to the submit event rather than a button click so you have a direct reference to the form
$("table.order form").on("submit", (e) => {
e.preventDefault(); // prevent normal submit
const form = $(e.target); // <form> ref
const cells = form.find("[class$='-supplData']");
// get the names of any empty inputs
const emptyData = cells
.filter((_, { value }) => value === "")
.map((_, { name }) => name)
.get();
if (emptyData.length) {
alert(`${emptyData.join(", ")} required`);
return false;
}
const orderNumber = form.find("[name='orderNumber']").val();
if (
!confirm(
"Confirm submitted data for order " +
orderNumber +
"?\nDon't forget to close the order after submitting supplemental data."
)
) {
return false;
}
$.post("FillSupplData.cfm", form.serialize())
.done((response) => {
form.find("button[type=submit]").remove();
form.find("button[type=button]").show();
cells.prop("disabled", true);
})
.fail((_, ...errors) => {
console.warn(...errors);
alert("An error occurred");
});
});
The only change to the HTML would be for your buttons
<button
id="3202643984-104-fillSupplData"
style="float: right; width: 125px; margin: 0px 5px"
type="submit"
class="button"
value="Submit Data"
/>
<button
type="button"
id="3202643984-104-close"
onclick="manualMethod(104, 'close', '3202643984');"
style="margin-bottom: 10px; display: none"
>
Close
</button>

var formData = {
productSubtypeId: 108,
orderNumber: 5673856
};
What I wanted was to add a property to an object that I am passing in ajax. That can be achieved like this :
formData['newPropertyName'] = document.getElementById(orderNumber + '-' + productSubtypeId + '-' + 'newPropertyName').value;

Related

How to count how many attribute name&values by user wrote in html

I would like to make a function which counts how many attributes I have with Attribute name&value I entered in html.
I don't know how to count by Attribute name&value!
like when i put "type" and "text" in this html then show 2!
I am very new to javascript! if you help me it would be very thankful! thanks
function javascript_click() {
if (document.getElementById("value3").value && document.getElementById("value4").value ) {
var attName=document.getElementById("value3").value;
var attValue=document.getElementById("value4").value;
if((attName && attValue) !==''){
var val3 = document.getElementById("value3");}
else {
document.getElementById("cnt").innerHTML +=
"wrong value of ID <br>";
}
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>Attribute name</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute value</td>
<td><input type="text" id="value4"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">javascript</button>
</div>
Every time the user is entering a pair of attributes I'm pushing the attributes in an array attRy.
attRy.length will give you the number of attributes pairs.
let attRy = []
function javascript_click() {
if (value3.value && value4.value ) {
var attName = value3.value;
var attValue = value4.value;
if(attName !=='' && attValue !==''){
attRy.push(attName + ": " +attValue);
cnt.innerHTML = attRy.length +" attributes:<br>";
attRy.forEach((a) =>{
cnt.innerHTML += a + "<br>"
})
}
else {
cnt.innerHTML +=
"wrong value of ID <br>";
}
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>Attribute name</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute value</td>
<td><input type="text" id="value4"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">javascript</button>
</div>
I hope I understand you right
function javascript_click() {
if (document.getElementById("value3").value && document.getElementById("value4").value) {
var attName = document.getElementById("value3").value;
var attValue = document.getElementById("value4").value;
var value = "[" + attName + "=" + attValue + "]";
var num2 = document.querySelectorAll(value).length;
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + num2 + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>Attribute name</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute value</td>
<td><input type="text" id="value4"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">javascript</button>
</div>

I want to append my data below the table and search when user clicks in the product id field

I have created a table and I want to add the data below the table but data is being added at the top,
I have written a search property when user enters the product id the data should be shown and can't figure out where my code went wrong,
I want to add serch field to all the buttons should I write the code many times is there any solution?
$(document).ready(function() {
var url = "http://34.201.147.118:3001/getAllData";
$.getJSON(url, function(data) {
console.log(data);
//console.log("AllData")
var obj = data['AllData'];
//console.log(obj)
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>" +
"<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child"> tr</tr>');
}
});
});
function goodCall() {
$(document).ready(function() {
$("#id").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
}
body {
background-image: url("banner.jpg");
background-size: 100%;
}
#mytable {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
width: 100%;
}
#mytable td,
#customers th {
border: 1px solid #ddd;
padding: 8px;
}
#mytable tr:hover {
background-color: #ddd;
}
#mytable th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Page Content -->
<div style="margin-left:25%">
<h1 style="color:white;">TITLE DETAILS</h1>
<div class="w3-container" id="add">
<div class="" style="color:white;">
<form name="test_form" id="101">
<table class="table borderless">
<tr>
<th>Title Identifier</th>
</tr>
<tr>
<td style="border:none">
<b>PRODUCT ID</b>
<br>
<input type="text" id="id" style="color:black;" required></td>
<td style="border:none"></td>
<td style="border:none">
<b>PRODUCT TITLE</b>
<br><input type="text" id="title" style="color:black;" required></td>
</tr>
<tr>
<td style="border:none">
<br> <b>director </b>
<br> <input type="text" id="ter" style="color:black;" required>
</td>
<td style="border:none"></td>
<td style="border:none">
<b>producer</b>
<br> <input type="text" id="media" style="color:black;" required>
</td>
</tr>
</table>
</form>
<input type="button" onclick="goodCall()" value="Search" style="color:Red;">
<table id='mytable'>
<tr>
<th>ID</th>
<th>PRODUCTTITLE</th>
</tr>
<div>
<br><br>
</div>
</table>
</div>
</div>
</div>
Here you have a basic functional example https://jsfiddle.net/0Lvqcd8t/39/
You should change this:
var tr = "<tr>" +
"<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child"> tr</tr>');
for this:
var tr = "<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child">'+ tr+'</tr>');
In the first case you are creating <tr><tr class="child><td></td></tr> (first <tr> is wrong) and browser will render something like <tr>tr</tr><tr class='child'>empty</tr> also, tr var in first example is not interpreted as variable, so you should place it like +tr+. I've made a basic filter function at the end that works with id.

Comparing two values with dynamic rows using javascript

I have an html code with multiple rows containing two values.Using javascript,I am able to compare the two values for only one row.How can I do the same for dynamically generated rows.
HTML:
<tbody id="appendrow" class="appendrow">
<input type="text"
data-field="quantity"
required
class="form-control"
name="units_ordered[]"
id="units_ordered0"
value=""/>
<input type="text"
data-field="inventory"
class="form-control"
name="inventory"
id="inventory0"
value="" />
</tbody>
Javascript:
var counter = 1;
$(window).load(function () {
$(function () {
$('#addRow').click(function () {
var row = $(' <tbody id=\'appendrow\' class=\'appendrow\'><tr><td> <input type=\'text\' required class=\'form-control\' name=\'sku[]\' onclick=\'filtersku(this,' + counter + ');\'> <input type=\'hidden\' id=\'product_id' + counter + '\' name=\'product_id[]\'/></td> <td> <input type=\'text\' readonly data-field=\'vendorsku\' id=\'vendor_sku' + counter + '\' name=\'vendorsku[]\'class=\'form-control\'></td> <td><input class=\'form-control\' data-field=\'quantity\' type=\'text\' required id=units_ordered' + counter + '\' name=\'units_ordered[]\' /></td> <td><input class=\'form-control\' type=\'text\' data-field=\'price\' required name=\'vendor_unit_price[]\' id=\'vendor_price' + counter + '\'></td> <td><input name=\'discount_percent[]\' data-field=\'discount\' class=\'form-control\' ><input type=\'hidden\' data-field=\'discountnumber\' class=\'form-control\' id=\'discountnumber\' ></td><td><input type=\'text\' readonly data-field=\'tax\' id=\'tax_id' + counter + '\' class=\'form-control\' name=\'tax_id[]\' /></td><td> Rs. <span data-field=\'taxPrice\' id=\'taxPrice' + counter + '\' >0</span><input type=\'hidden\' data-field=\'taxPriceInput\' id=\'taxPriceInput' + counter + '\' class=\'taxPrice\' value = \'0\'/> </td> <td><input type=\'text\' class=\'form-control\'data-field=\'total\' name=\'subtotal[]\'/><input type=\'hidden\' data-field=\'totalbeforetax\' class=\'form-control\' id=\'subtotalbeforetax\' /></td><td><button type=\'button\' class=\'btn btn-danger\' name=\'delete[]\' onclick=\'javascript:deletefun(this);\'><i class=\'fa fa-trash\' aria-hidden=\'true\'></i></button></td></tr></tbody>');
$('#example').append(row);
counter++;
});
});
});
function validation() {
var ordered = parseInt(document.getElementById('units_ordered0').value);
var inventory = parseInt(document.getElementById('inventory0').value);
if (inventory == -1) {
return true;
}
else {
if (ordered <= inventory) {
return true;
}
else {
document.getElementById('error').innerHTML = ('Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory).fontcolor('red');
return false;
}
}
}
Please note the correct structure of the HTML5 Table. Here is a clean HTML5 Table structure:
<table>
<caption>Table Caption</caption>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Header Row 1</th>
<th>Header Row 2</th>
<th>Header Row 3</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer Row 1</td>
<td>Footer Row 2</td>
<td>Footer Row 3</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Body Row 1</td>
<td>Body Row 2</td>
<td>Body Row 3</td>
</tr>
</tbody>
</table>
And about your question:
var counter = 1;
document.getElementById( 'addRow' ).addEventListener( 'click', function ( e ) {
var table = document.getElementById( 'myTable' ),
row = table.insertRow( counter ),
cell1 = row.insertCell( 0 ),
cell2 = row.insertCell( 1 );
cell1.innerHTML = '<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered' + counter + '" required/>';
cell2.innerHTML = '<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory' + counter + '"/>';
counter++;
e.preventDefault()
} )
document.getElementById( 'validate' ).addEventListener( 'click', function ( e ) {
validation();
e.preventDefault()
} )
function validation() {
var ordered = document.querySelectorAll( 'input[id^="units_ordered"]' ),
inventory = document.querySelectorAll( 'input[id^="inventory"]' );
document.getElementById( 'error' ).innerHTML = ''
ordered.forEach( function ( item, index ) {
var ordered_val = Number( item.value ) || 0,
inventory_val = Number( inventory[ index ].value ) || 0
if ( inventory_val == -1 ) {
return true
} else {
if ( ordered_val <= inventory_val ) {
return true
} else {
document.getElementById( 'error' ).innerHTML += 'Row ' + +( index + 1 ) + ': Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory_val + '<br/>';
return false
}
}
} )
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 300px
}
td, th {
border: 1px solid #86af49;
text-align: left;
padding: 0
}
th {
padding: 5px;
color: #fff;
background-color: #86af49
}
input[type="text"] {
box-sizing: border-box;
width: 100%;
border: 0;
outline: none
}
#error {
color: red;
font-size: .75em
}
<p>
<button type="button" id="addRow">Add Row</button>
<button type="button" id="validate">Validation</button>
</p>
<table id="myTable">
<thead>
<tr>
<th>Ordered</th>
<th>Inventory</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered0" required/>
</td>
<td>
<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory0"/>
</td>
</tr>
</tbody>
</table>
<p id="error"></p>

Model class only popups on first button when used in append

I am using Material UI to build a website. I have append a list with data and it also has a popup on button. But the popup works only on first button click.
I want to make a new popup on every button click. Also here is a error from console.
"Uncaught DOMException: Failed to execute 'showModal' on 'HTMLDialogElement': The element already has an 'open' attribute, and therefore cannot be opened modally.
at HTMLDivElement."
Here is HTML
<div id="order">
<dialog style="width: 40%;" class="mdl-dialog">
<div class="mdl-dialog__content">
<table id="table" style="width: 100%;" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Material</th>
<th>Quantity</th>
<th>Unit price</th>
</tr>
</thead>
<tbody style="width: 100%;" id="producttable">
</tbody>
</table>
</div>
<div class="mdl-dialog__actions">
<button type="button" class="mdl-button close">Confirm Order</button>
<button type="button" class="mdl-button">Order Shipped</button>
<button type="button" class="mdl-button">Order Delivered</button>
<button type="button" class="mdl-button">Order Canceled</button>
</div>
</dialog>
</div>
Here is JS
$("#order").append(
'<div style="padding-top:6px; padding-bottom:6px; margin-bottom: 16px;" class="card-wide mdl-card-order mdl-shadow--2dp"><h3 id="orderID" style="margin: 16px;" class="mdl-card__title-text">' +
'<a style="float: left; width: 65%;">Order ID : ' + orderid + ' </a><a style="float: right; width: 35%;">Date : ' + orderDate +
'</a></h3><div style="margin-left: 16px;"><p id="client_name" style=" font-size: 18px;"> Name - ' +
name + '</p><p id="client_email" style=" font-size: 18px;">Phone - ' + phone +
'</p><p id="client_email" style=" font-size: 18px;">Address - ' + address +
'</p></div><div class="mdl-card__menu"></div><div id="dialog" class="mdl-card__actions mdl-card--border"> <a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" onclick="purchaseList(' + orderid + ')"> Purchase List </a></div></div>');
function purchaseList(listid) {
var starCountRef = firebase.database().ref('Orders/' + listid).child('foodItems');
starCountRef.on('child_added', snapshot => {
var snaps = snapshot.val();
var itemPrice = snaps.price;
var itemName = snaps.productName;
var itemQuantity = snaps.quantity;
console.log(itemName);
$("#producttable").append(
'<tr><td class="mdl-data-table__cell--non-numeric">' + itemName + '</td><td>' + itemQuantity + '</td><td>' + itemPrice + '</td></tr>'
);
});
var dialog = document.querySelector('dialog');
var showDialogButton = document.querySelector('#dialog');
if (!dialog.showModal) {
dialogPolyfill.registerDialog(dialog);
}
showDialogButton.addEventListener('click', function () {
dialog.showModal();
});
dialog.querySelector('.close').addEventListener('click', function () {
var element = document.getElementById("producttable");
while (element.lastChild) {
element.removeChild(element.lastChild);
}
dialog.close();
});
}
Dont know if it is the point but
dialog.querySelector('.close').addEventListener(...
wont work with multiple classes. You have to use the
classList.contains('close')
for example but i would just give an id to the .close element to get it easy
<button type="button" id ="close" class="mdl-button">Confirm Order</button>
dialog.querySelector("#close");
or even better generate your HTML tag elements in JS to have direct access like
const closeBtn = document.createElement("button");
closeBtn.className = "mdl-button";
closeBtn.type = "button";
dialog.querySelector(".mdl-dialog__actions").append(closeBtn);
closeBtn.addEventListener("click", (e)=>{
//Todo on click
})

multiple buttons on jquery html

There is a problem with the below code. The second button show it does not work. It doesn't open anything.
The problem is for sure the Show ..if I changed it to class , both do not work.
And I would like in each row the text to be left without any margin , but I couldn't fixed it
<!DOCTYPE html>
<html>
<body>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cafeteria Orders Management System</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
label,
input {
display: block;
}
input.text {
margin-bottom: 12px;
width: 95%;
padding: .4em;
}
fieldset {
padding: 0;
border: 0;
margin-top: 25px;
}
td {
max-width: 120px;
white-space: nowrap;
}
h1 {
font-size: 1.2em;
margin: .6em 0;
}
div#users-contain {
width: 300px;
margin: 20px 0;
}
div#users-contain table {
margin: 1em 0;
border-collapse: collapse;
width: 100%;
}
div#users-contain table td,
div#users-contain table th {
border: 9px solid #eee;
padding: .6em 120px;
text-align: left;
}
.ui-dialog .ui-state-error {
padding: .3em;
}
.validateTips {
border: 1px solid transparent;
padding: 0.3em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
var dialog, form,
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function() {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
Ok: function() {
dialog.dialog("close");
}
},
close: function() {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function(event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function() {
dialog.dialog("open");
});
});
</script>
</head>
<body>
<div id="dialog-form" title="Order Details">
<p class="validateTips">Spicy Sandwitch</p>
<p class="validateTips">More</p>
<form>
<fieldset>
<label for="name">More Comments</label>
<p class="validateTips">Sandwitch only lettuce</p>
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<div id="users-contain" class="ui-widget">
<h1>Order List:</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Surname</th>
<th>Address</th>
<th>Telephone</th>
<th>Time/Date</th>
<th>Order Details</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr>
</td>
<td>John Doe</td>
<td>Lykavitou 12, 2109 Aglantzia</td>
<td>99123456</td>
<td>21:00 21/11/16</td>
<td>
<button id="create-user">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
<tr>
</td>
<td>Andreas Georgiou</td>
<td>Grigori Auxentiou 12, 2109 Aglantzia</td>
<td>99654789</td>
<td>20:00 21/11/16</td>
<td>
<button id="create-user">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
</tbody>
</table>
</div>
</body>
</html>
change in the button attribute id, u cant use more than one id with the same name on your website, you can use class instead of. For example
<button class="create-user">Show</button>
and in the js u must call to the class
$(".create-user")
As was suggested, you will want to use the class attribute and selector.
Working example: https://jsfiddle.net/Twisty/5n2h03nL/
HTML
<div id="users-contain" class="ui-widget">
<h1>Order List:</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Surname</th>
<th>Address</th>
<th>Telephone</th>
<th>Time/Date</th>
<th>Order Details</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>Lykavitou 12, 2109 Aglantzia</td>
<td>99123456</td>
<td>21:00 21/11/16</td>
<td>
<button id="create-user-1" class="showDialog">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
<tr>
<td>Andreas Georgiou</td>
<td>Grigori Auxentiou 12, 2109 Aglantzia</td>
<td>99654789</td>
<td>20:00 21/11/16</td>
<td>
<button id="create-user-2" class="showDialog">Show</button>
</td>
<td align="center">
<input type="checkbox" class="case" name="case" value="1" />
</tr>
</tbody>
</table>
</div>
jQuery
$(".showDialog").button().on("click", function() {
dialog.dialog("open");
});
In regards to your other comment, you will need to provide more info. If you want the "Show" button to launch the dialog with custom details each time, those details need to be provided from some place. You can make use of data attributes on the row, like <tr data-comments=""> or make an AJAX call to a database. We can't just write that for you, you need to figure out where you want to store those details and how you want to collect them when the button is clicked.
In regards to this question, I suspect you've got the answer. So I would mark one as a answer, take a stab at your next issue, and if needed create a new question.

Categories