Velocity/Java script form not retaining the input - javascript

I am having trouble with velocity scripts which is not returning the childDoc(s) values after clicking the Apply button (child doc value disappears). I am new to Velocity and the Javascript.
Below is the part of the code that uses a form.
#set($levelRow = "levelRow")
#set($newLevelRow = "newLevelRow")
{pre}
<script>
function removeLevel(prefix) {
var levels = updateCommon(false, prefix);
var removeRow = document.getElementById(prefix + "levelRow" + levels);
removeRow.parentNode.removeChild(removeRow);
if(levels > 2)
setActionImageVisibility(levels - 1, "visible", prefix);
}
function addLevel(prefix) {
var levels = updateCommon(true, prefix);
var lastLevelRow = document.getElementById(prefix + "levelRow" + levels);
var newLevelRow = document.getElementById(prefix + "newLevelRow");
var newLevelInput = newLevelRow.getElementsByTagName("input")[0];
var toInsertRow = lastLevelRow.cloneNode(true);
toInsertRow.setAttribute("id", prefix + "levelRow" + (levels + 1));
var toInsertInputs = toInsertRow.getElementsByTagName("input");
var toInsertInput = null;
var toInsertOutput = null;
for (var i = 0; i < toInsertInputs.length; i++) {
var input_id = toInsertInputs[i].getAttribute("id");
if (input_id == (prefix + "query" + (levels))) {
toInsertInput = toInsertInputs[i];
} else if (input_id == (prefix + (levels))) {
toInsertOutput = toInsertInputs[i];
}
}
toInsertInput.setAttribute("id", prefix + "query" + (levels + 1));
toInsertInput.value = newLevelInput.value;
toInsertOutput.setAttribute("id", prefix + (levels + 1));
toInsertOutput.name = prefix + (levels + 1);
toInsertOutput.value = toInsertInput.value.replace("/#/", "/redirect/");
newLevelInput.value = "";
newLevelRow.parentNode.insertBefore(toInsertRow,newLevelRow);
setActionImageVisibility(levels, "hidden", prefix)
setActionImageVisibility(levels + 1, "visible", prefix)
}
function updateCommon(add,prefix) {
var levelsInput = document.getElementById(prefix + "levelsInput");
var levels = levelsInput.getAttribute("value") - 1 + 1;
if(add) {
levelsInput.setAttribute("value", levels + 1);
} else {
levelsInput.setAttribute("value", levels - 1);
}
return levels;
}
function setActionImageVisibility(level,visibility,prefix) {
var img = document.getElementById(prefix + "levelRow" + level).getElementsByTagName("img")[0];
img.style.visibility = visibility;
}
function submitFunction() {
var input_prefixes = new Array();
var docElements = document.getElementsByTagName("input");
for (docElement in docElements) {
var indexLevels = docElement.indexOf("levels");
var levelsAtEnd = (indexLevels + "levels".length) == docElement.length;
var hasPrefix = docElement.length > "levels".length;
if ((-1 < indexLevels) && levelsAtEnd && hasPrefix) {
input_prefixes.push(docElement.substring(0,indexLevels));
var input_prefix = docElement.substring(0,indexLevels);
var levelsInput = document.getElementsByName(docElement).item(0);
for (var i=1; i < parseInt(levelsInput.value) + 1; i++) {
var input = document.getElementById(input_prefix + "query" + String(i));
var output = document.getElementsByName(input_prefix + String(i)).item(0);
output.value = input.value.replace("/#/", "/redirect/");
}
}
}
}
</script>
{/pre}
#macro(loadParameter $id)
#set($_id = "$id")
#set($parameter = false)
#set($parameter = $request.getParameter($_id))
#end
#macro(VariableInputTable $paramBaseName $parametersRedirect)
#set($parameterPrefix = "${paramBaseName}")
#loadParameter("${parameterPrefix}levels")
#set($levels = $parameter)
#set($requiresParamInit = !$levels)
#if($requiresParamInit)
#set($defaultQueries = [""])
#set($levels = ${defaultQueries.size()})
#set($initParameters = "${parameterPrefix}levels=${levels}") ## this assumes that it is setting the only parameters on the page
#foreach($query in $defaultQueries)
#set($initParameters = "$initParameters&${parameterPrefix}${velocityCount}=$query")
#end
#set($parametersRedirect = "${parametersRedirect}${initParameters}")
#else
#set($int = 0)
#set($levels = $int.valueOf($levels))
#showTable()
#end
#end
#macro(showTable)
#set($queries = [])
#set($linkRoles = [])
#set($sorts = [])
<input id="${parameterPrefix}levelsInput" type="hidden" name="${parameterPrefix}levels" value="$levels"></input>
<table cellpadding="0" border=0>
#foreach($level in [1..$levels])
#loadParameter("${parameterPrefix}${level}")
<tr id="${parameterPrefix}${levelRow}$level">
<td style="border-width:1px;border-style:solid;padding:1px">
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" oninput="submitFunction()" #if($parameter)value="$parameter.replaceAll('"','\\"')#end">
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" style="width: 100%;">
</td>
<td style="vertical-align:middle;text-align:center;">
<img src="/polarion/ria/images/control/minus.gif" alt="Remove" title="Remove" style="cursor:pointer#if(($velocityCount != $levels) || (2 > $levels));visibility:hidden#end" onclick="removeLevel('${parameterPrefix}')" id="${parameterPrefix}removeImg$level"></img>
</td>
</tr>
#if($parameter)#set($void = $queries.add($parameter))#end
#set($void = $linkRoles.add([]))
#set($void = $sorts.add("id"))
#end
<tr id="${parameterPrefix}${newLevelRow}">
<td style="border-width:1px;border-style:solid;padding:1px">
<input style="border-style:none" id="${parameterPrefix}newQuery" type="text" size="50">
</td>
<td style="vertical-align:middle;text-align:center;">
<img src="/polarion/ria/images/control/plus.gif" alt="Add" title="Add" style="cursor:pointer" onclick="addLevel('${parameterPrefix}')"></img>
</td>
</tr>
</table>
#end
I think something wrong with below part.
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" oninput="submitFunction()" #if($parameter)value="$parameter.replaceAll('"','\\"')#end">
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" style="width: 100%;">
Form looks like:

I have managed to fix this by changing the code.
#if($parameter) #set( $childDocurl = $parameter.replaceAll('"','\\"'))#end
<input style="border-style:none" id="${parameterPrefix}query$level" type="text" size="50" value="${childDocurl}" oninput="submitFunction()" >
<input type="hidden" class="polarion-TextBox" name="${parameterPrefix}${level}" id="${parameterPrefix}${level}" value="${childDocurl}" style="width: 100%;">

Related

Cascading dropdown list in HTML

Ok I edited the question with below update.
I tried with below script but it seems not working. Please someone can show me what is wrong with below code.
<script>
var myselect = document.getElementById("start2");
document.getElementById("end1").onchange = createOption()
function createOption() {
var selectEnd = document.getElementById("end1");
var value = selectEnd.options[select.selectedIndex].value;
var objOption = document.createElement("option");
objOption.text = value + 1;
objOption.value = value +1;
//myselect.add(objOption);
myselect.appendChild(objOption);
}
</script>
What I want to do is there are 2 select list form with id End1 and Start2. I want when select list End1 onchange, value from End1 will be passed to Start2 with added 1. But, it has nothing happened.
I have solved this problem. I want to share it. But, can I post it here as answer? Or need I to add in my first entry above?
<html>
<body id="myBody">
<table>
<%
for i = 1 to 5
%>
<tr>
<td>
<select id = "start<%=i%>" onChange="startChange(this.id)">
<option value=""></option>
</select>
</td>
<td>
<select id = "end<%=i%>" onChange="endChange(this.id)">
<option value=""></option>
</select>
</td>
</tr>
<%
next
%>
</table>
<script>
const serialEnd =+document.getElementById("start1").innerText + 100;
document.getElementById("myBody").onload = function() {optionLoad("end1")};
function optionLoad(id){
var lastno = +id.substring(3,4);
var selectElement = document.getElementById("end" + lastno + "");
var serialStart = +document.getElementById("start" + lastno + "").value;
for (var serial = serialStart + 1; serial <= serialEnd; serial++) {
selectElement.add(new Option(serial));
}
}
function endChange(id) {
var lastno = +id.substring(3,4);
var selectStart = document.getElementById("start" + ( lastno + 1 ) + "");
var selectEnd = document.getElementById(id);
var options = selectEnd.options[selectEnd.selectedIndex];
var objOption = document.createElement("option");
if (lastno != 5){
removeOptions(document.getElementById("start" + ( lastno + 1 ) + ""));
objOption.text = +options.value + 1;
objOption.value = +options.value + 1;
selectStart.add(objOption);
}
}
function startChange(id){
var lastno = +id.substring(5,6);
removeOptions(document.getElementById("end" + lastno + ""));
optionLoad("end" + lastno + "");
}
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for(i = L; i >= 1; i--) {
selectElement.remove(i);
}
}
</script>
</body>
</html>

Generated row of table event listener not working instantly

I have a table like this :
I have added an event listener assetTableEvent() to each text box in the table. My issue is when I add new row to the table, i also add the corresponding event listener to it assetTableEvent(), but the total value does not pop while entering value, it shows only when next row has values entered.
function assetTableEvent() {
let total = 0;
for (var k = 0; k < document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
I even tried calling assetTableEvent() every time there is a change, but it just does not work. Can somebody help me in Javascript how to make dynamically added rows correspond to event listener like above rows.
HTML for Asset table:
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>
And add row event listener :
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
Trying to use incremental IDs is more work than it is worth, especially when you start removing rows.
I suggest you use classes instead and delegate the event listener to the table itself. When an input event occurs you get the closest row and query for the elements within that row for the row total, then query all of the rows totals for the master total
Basic example with functional add row
const table = document.querySelector('#myTable'),
cloneRow = table.rows[0].cloneNode(true);
table.addEventListener('input',(e) => {
if (e.target.matches('.qty, .price')) {
const row = e.target.closest('tr'),
price = row.querySelector('.price').valueAsNumber || 0,
qty = row.querySelector('.qty').valueAsNumber || 0;
row.querySelector('.amt').value = qty * price;
setTotalAmt()
}
});
document.querySelector('#add-row').addEventListener('click', (e) => {
table.appendChild(cloneRow.cloneNode(true))
});
function setTotalAmt() {
const sum = [...table.querySelectorAll('.amt')].reduce((a, el) => a + (+el.value || 0), 0)
document.querySelector('#total').value = sum;
}
<button id="add-row">
Add Row
</button>
Total:<input id="total" />
<table id="myTable">
<tr>
<td>Qty:
<input type="number" class="qty" value="0" />
</td>
<td>Price:
<input type="number" class="price" value="0" />
</td>
<td>Amt:
<input class="amt" readonly value="0" />
</td>
</tr>
</table>
#charlietfl 's solition is more elegant but if you wonder what is the problem in your code, you should change the < to <= in k < document.getElementById("assetTable").rows.length; part
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
Here is the working example:
document.getElementById("addRow").addEventListener("click", function () {
var table = document.getElementById("assetTable");
var row = table.insertRow();
for (let j = 0; j < 4; j++) {
var tb = document.createElement("INPUT");
var value = "", idNum = "";
if (j == 0) {
tb.setAttribute("type", "text");
tb.value = value;
}
else {
tb.setAttribute("type", "number");
}
//Setting textbox id
switch (j) {
case 0:
idNum = "a";
break;
case 1:
idNum = "v";
break;
case 2:
idNum = "o";
break;
case 3:
idNum = "t";
break;
}
tb.id = idNum + (table.rows.length);
if (tb.id.includes('t')) {
tb.setAttribute("readOnly", "true");
}
tb.classList.add("assetTBox");
let cell = row.insertCell(j);
tb.addEventListener("input", assetTableEvent, false);
cell.appendChild(tb);
}
});
function assetTableEvent() {
let total = 0;
for (var k = 0; k <= document.getElementById("assetTable").rows.length; k++) {
var a = document.getElementById("v" + k);
var o = document.getElementById("o" + k);
var t = document.getElementById("t" + k);
if (a == null || o == null) {
continue;
}
if (a.value.length > 0 && o.value.length > 0) {
t.value = Number.parseInt(a.value - o.value);
total = (Number.parseInt(t.value) + Number.parseInt(total));
document.getElementById("totalAssets").value = Number.parseInt(total);
}
}
}
<div id="calcContainer">
<div id = "headingText" >
Child Maintenance Calculator
</div>
<div id="startPage">
<button id="startBtn">Start</button>
</div>
<div id="asset">
<table id="assetTable">
<tr>
<th>Asset</th>
<th>Value</th>
<th>Own</th>
<th>Total</th>
</tr>
</table>
<div id="totalAssetsDiv">
<Label for ="totalAssets">Total Assets</Label>
<input type="number" id = "totalAssets" readonly="true">
<br>
</div>
<div id ="rowOps">
<br> <button id="addRow" class = "addDel">Add Row</button>
<button id="removeRow" class = "addDel1">Delete Row</button><br>
</div>
</div>

Javascript Dynamic Accordion Help needed

I have my mock up here https://codepen.io/anon/pen/WzMpga?editors=0010
I need help in making the last column as clickable button and on the click(action), the hierarchy of the employee should expand in the first column.
Also, if you could guide me how to get the that +/- icon on the button click if it has a parent
function createAccordion(oneEmployee) {
var returnValues = [];
var accordionButton = document.createElement("button");
accordionButton.className = "accordion";
accordionButton.setAttribute("value", oneEmployee.resolverGroups);
accordionButton.setAttribute("onClick", "populateResolverGroups('"+oneEmployee.resolverGroups+"', '" + oneEmployee.employee + "')");
watchingRGs[oneEmployee.employee] = oneEmployee.resolverGroups;
watchResolverGroup("", oneEmployee.employee);
var accordionTextNode = document.createTextNode(oneEmployee.employee);
accordionButton.appendChild(accordionTextNode);
returnValues[0] = accordionButton;
var accordionDiv = document.createElement("div");
accordionDiv.className = "panel";
if (oneEmployee.reports.length > 0) {
for (var empInd = 0; empInd < oneEmployee.reports.length; empInd++) {
var thisEmpAcc = createAccordion(oneEmployee.reports[empInd]);
accordionDiv.appendChild(thisEmpAcc[0]);
accordionDiv.appendChild(thisEmpAcc[1]).click();
}
}
returnValues[1] = accordionDiv;
if(oneEmployee.resolverGroups.length > 0 ) {
accordionButton.click();
}
return returnValues;
}
function populateResolverGroups(resolverGroups, employeeName) {
document.getElementById('resolvergroups').innerHTML = "";
var rgList = resolverGroups.split(',');
for (var rgInd = 0; rgInd < rgList.length; rgInd++) {
var cbox = document.createElement('input');
cbox.setAttribute("onclick", "watchResolverGroup('"+rgList[rgInd]+"', '"+employeeName+"')");
cbox.type = "checkbox";
cbox.name = rgList[rgInd];
cbox.value = rgList[rgInd];
cbox.id = rgList[rgInd];
//cbox.checked = true;
//keeps track of the RGs that are checked
if (watchingRGs[employeeName] !== undefined) {
if (watchingRGs[employeeName].includes(rgList[rgInd])) {
cbox.checked = true;
}
}
var cboxTextNode = document.createTextNode(rgList[rgInd]);
var linebreak = document.createElement("br");
document.getElementById('resolvergroups').appendChild(cbox);
document.getElementById('resolvergroups').appendChild(cboxTextNode);
document.getElementById('resolvergroups').appendChild(linebreak);
}
}
function watchResolverGroup(resolverGroupName, employeeName) {
var selectedRGs = [];
if (watchingRGs[employeeName] !== undefined) {
selectedRGs = watchingRGs[employeeName];
}
if (resolverGroupName.length > 0) {
if (selectedRGs.includes(resolverGroupName)) {
selectedRGs.splice(selectedRGs.indexOf(resolverGroupName), 1);
} else {
selectedRGs.push(resolverGroupName);
}
}
watchingRGs[employeeName] = selectedRGs;
document.getElementById("selected_resolvergroups").innerHTML = "";
for (var key in watchingRGs) {
var val = watchingRGs[key];
for (var rgInd = 0; rgInd < val.length; rgInd++) {
var tempTextNode = document.createTextNode(val[rgInd] + " -> " + key);
var linebreak = document.createElement("br");
document.getElementById("selected_resolvergroups").appendChild(tempTextNode);
document.getElementById("selected_resolvergroups").appendChild(linebreak);
}
}
}
How to proceed with that?
For Open Close Hiracrhy this will help you
http://mleibman.github.io/SlickGrid/examples/example5-collapsing.html
Example
If you want to build your own take a look at this fiddle it will help
JS Fiddle
<table id="mytable">
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span>Item 1</td>
<td>123</td>
</tr>
<tr data-depth="1" class="collapse level1">
<td><span class="toggle"></span>Item 2</td>
<td>123</td>
</tr>
</table>

buttons don't work after append - jquery

buttons won't work after appended elements take up same Y position, why is this happening? I took the advice of other posts and made my onclick functions a certain way but I am still having issues
js:
var welldataArray = [];
var productiondataArray = [];
var radioSearchPartB = 0;
var productionjsonarray = [];
$(document).ready(function() {
$(document).on('click', '.clearButton', function (){
$('#result1').empty();
$('#block1').val("");
$('#block2').val("");
$('#block3').val("");
$('#block4').val("");
$('#block5').val("");
});
$(document).on('click', '.searchButton', function(){
//validate
if(radioSearchPartB == 1){
var block1 = $("#block1").val().toUpperCase();
var firstcharBlock1 = block1.substring(0,1);
var secondcharBlock1 = block1.substring(1,3);
var secondParsed = parseInt(secondcharBlock1);
var block2 = $("#block2").val();
var block3 = $("#block3").val();
var block4 = $("#block4").val().toUpperCase();
var firstcharBlock4 = block4.substring(0,1);
var secondcharBlock4 = block4.substring(1,3);
var msg = "";
if(firstcharBlock1!= 'A' && firstcharBlock1!= 'B' && firstcharBlock1!= 'C' && firstcharBlock1!= 'D'){
msg+="First text box Invalid Format: First character Range A-D\n";
}
if(secondParsed < 1 || secondParsed > 16 || isNaN(secondParsed) || !($.isNumeric(secondcharBlock1))){
msg+="First text box Invalid Format: Second Character Range 1-16\n";
}
if(parseInt(block2) < 1 || parseInt(block2) > 126 || block2.length == 0 || isNaN(parseInt(block2)) ){
msg+="Second text box Invalid Format: Must be a number 1-126\n"
}
if(isNaN(parseInt(block3)) || parseInt(block3) < 1 || parseInt(block3) > 24 || block3.length == 0){
msg+="Third text box Invalid Format: Must be a number 1-24\n";
}
if(firstcharBlock4 != 'W' || parseInt(secondcharBlock4) < 4 || parseInt(secondcharBlock4) > 6){
msg+= "Fourth text box Invalid Format: W and then a number 4-6\n";
}
if(msg.length > 0){
alert(msg);
return;
}
//then
$('#result1').empty();
var i = 0;
productionjsonarray = [];
while(i < productiondataArray.length){
var jsonObject = {
"location": productiondataArray[i++].trim(),
"date": productiondataArray[i++].trim(),
"oilproduction": productiondataArray[i++].trim(),
"waterproduction": productiondataArray[i++].trim(),
"gasproduction": productiondataArray[i++].trim()
}
productionjsonarray.push(jsonObject);
}
var assemble = block1 + "-" + block2 + "-" + block3 + "-" + block4;
var check = false;
for(var i = 0; i < welldataArray.length; i++){
if(welldataArray[i].trim() == assemble){
for(var j = 0; j < productionjsonarray.length; j++){
if(productionjsonarray[j].location.trim() == welldataArray[i].trim()){
$('#result1').append(productionjsonarray[j].location.trim() + " "
+ productionjsonarray[j].date.trim() + " " + productionjsonarray[j].oilproduction.trim()
+ " " + productionjsonarray[j].waterproduction.trim() + " " + productionjsonarray[j].gasproduction.trim() + "<br>");
check = true;
}
}
}
}
if(check == false){
alert("No match to search");
return;
}
} else {
//validate
var block5 = $("#block5").val().toUpperCase();
var firstcharBlock5 = block5.substring(0,1);
var secondcharBlock5 = block5.substring(1,3);
var secondParsed5 = parseInt(secondcharBlock5);
var msg = "";
if(firstcharBlock5!= 'A' && firstcharBlock5!= 'B' && firstcharBlock5!= 'C' && firstcharBlock5!= 'D'){
msg+="text box Invalid Format: First character Range A-D\n";
}
if(secondParsed5 < 1 || secondParsed5 > 16 || isNaN(secondParsed5) || !($.isNumeric(secondcharBlock5))){
msg+="text box Invalid Format: Second Character Range 1-16\n";
}
if(msg.length > 0){
alert(msg);
return;
}
//then
var check = false;
$('#result1').empty();
for(var i = 0; i < welldataArray.length; i++){
if(welldataArray[i].trim().indexOf(block5.trim()) >= 0){
$('#result1').append(welldataArray[i] + " " + welldataArray[i+1] + " " + welldataArray[i+2] + " " + welldataArray[i+3] + " " + welldataArray[i+4] + " " + welldataArray[i+5] + "<br>");
check = true;
}
}
if(check == false){
alert("No match to search");
return;
}
var i = 0;
productionjsonarray = [];
while(i < productiondataArray.length){
var jsonObject = {
"location": productiondataArray[i++].trim(),
"date": productiondataArray[i++].trim(),
"oilproduction": productiondataArray[i++].trim(),
"waterproduction": productiondataArray[i++].trim(),
"gasproduction": productiondataArray[i++].trim()
}
productionjsonarray.push(jsonObject);
}
}
});
$.ajax({
type: "GET",
url: "welldata.xml",
dataType: "xml",
success: function(xml){
$(xml).find('welldata').each(function(){ //code provided by stack overflow: http://stackoverflow.com/questions/6542187/xml-to-javascript-array-with-jquery
var location;
var welldepth;
var perfdepth;
var perfzone;
var stroke;
var strokepermin;
location = $('location', this).text();
welldepth = $('welldepth', this).text();
perfdepth = $('perfdepth', this).text();
perfzone = $('perfzone', this).text();
stroke = $('stroke', this).text();
strokepermin = $('strokepermin', this).text();
welldataArray.push(location);
welldataArray.push(welldepth);
welldataArray.push(perfdepth);
welldataArray.push(perfzone);
welldataArray.push(stroke);
welldataArray.push(strokepermin);
});
}
});
$.ajax({
type: "GET",
url: "productiondata.xml",
dataType: "xml",
success: function(xml){
$(xml).find('productiondata').each(function(){
var location;
var date;
var oilproduction;
var waterproduction;
var gasproduction;
location = $('location', this).text();
date = $('date', this).text();
oilproduction = $('oilproduction', this).text();
waterproduction = $('waterproduction', this).text();
gasproduction = $('gasproduction', this).text();
productiondataArray.push(location);
productiondataArray.push(date);
productiondataArray.push(oilproduction);
productiondataArray.push(waterproduction);
productiondataArray.push(gasproduction);
});
$( "#searchButton" ).click(function() {
radioSearchPartB = $('input[name=searchChoice]:checked').val()
});
}
});
});
function loadPartB(){
document.getElementById("block1").maxLength = "3";
document.getElementById("block2").maxLength = "3";
document.getElementById("block3").maxLength = "2";
document.getElementById("block4").maxLength = "2";
document.getElementById("block5").maxLength = "3";
radioSearchPartB = $('input[name=searchChoice]:checked').val();
$('#result1').html('');
$('#result1').empty();
if(radioSearchPartB == 2){
$("#1stblocks").hide();
$("#1stex").hide();
$("#2ndblocks").show();
$("#2ndex").show();
} else {
$("#1stblocks").show();
$("#1stex").show();
$("#2ndblocks").hide();
$("#2ndex").hide();
}
}
html:
<!DOCTYPE html>
<html class="colorful">
<head>
<meta charset="utf-8">
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="css/final.css">
<script src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="final.js"></script>
</head>
<body onload="loadPartB()">
Cameron Steinburg 734972
<br>
<h1>This is Part B</h1>
<br>
<h2>Oil Well Database</h2>
<div id="result1"></div>
<br>
<input type="radio" name="searchChoice" value="1" checked onchange="loadPartB()"> Search by specific location
<input type="radio" name="searchChoice" value="2" onchange="loadPartB()"> Search by section
<br>
<br>
<table id="1stblocks">
<tr>
<td><input type="text" id="block1">-</td>
<td><input type="text" id="block2">-</td>
<td><input type="text" id="block3">-</td>
<td><input type="text" id="block4"></td>
<td></td>
</tr>
</table>
<div id="1stex">
ex. B15-98-17-W5
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<table id="2ndblocks">
<tr>
<td><input type="text" id="block5"></td>
</tr>
</table>
<div id="2ndex">
ex. B15
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<div>
<input type="submit" value="Search" class="searchButton">
<input type="submit" value="Clear" class="clearButton">
</div>
<br>
<br>
<h3>Main Page Part C Part D</h3>
</body>
</html>
Well, your buttons works if you remove onload="loadPartB()" from body and call the loadPartB(); in your document.ready()
$(document).ready(function() {
loadPartB();
$(document).on('click', '.clearButton', function (){
$('#result1').empty();
$('#block1').val("");
$('#block2').val("");
$('#block3').val("");
$('#block4').val("");
$('#block5').val("");
});
you can use delegate() as :
$(document).delegate('click', '.clearButton', function (){
// your code
});
document : http://api.jquery.com/delegate/
this event alway set to new elements

User inputs information into text box which makes allows user to select multiple words and creates different Titles based on the selections

I am gaining user input from four different areas and I want to take those options and convert them to an array which will loop through and display different variations of the words selected. The problem I am having is that the array will not cycle through the variables when passed through it unless they are already pre-defined.
<!DOCTYPE html>
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<h2>Example</h2>
<p>When you type into Core Words you want to put words that cannot change such as: Logitech
</br> For Word Combinations you want to use words such as: Brand New or Power Adaptor
</br> For Swapped Words you might want to use: Gaming instead of Performance or vice versa
</br> For Synonyms you want to use words that mean the same thing such as for = 4 or at = #</p>
<h3>Core Words</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCore"/>
<button id="addCore">Insert</button>
<label for="coreContain">Select as many as you like:</label>
<select id="coreContain" name="coreContain" multiple></select>
<button id="checkCore" onclick="checkCore()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCore").click(function()
{
$("#coreContain").append('<option value="' + $("#newCore").val() + '">' + $("#newCore").val() + '</option>');
});
});
$('#coreContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var coreOptions = new Array();
$('form').submit(
function()
{
$('#coreContain > option:selected').each(
function(i)
{
coreOptions[i] = $(this).val();
});
//window.alert(coreOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs Word Combinations -->
<h3>Word Combinations</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCombo"/>
<button id="addCombo">Insert</button>
<label for="comboContain">Select as many as you like:</label>
<select id="comboContain" name="comboContain" multiple></select>
<button id="checkCombo" onclick="checkWordCombo()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCombo").click(function()
{
$("#comboContain").append('<option value="' + $("#newCombo").val() + '">' + $("#newCombo").val() + '</option>');
});
});
$('#comboContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var comboOptions = new Array();
$('form').submit(
function()
{
$('#comboContain > option:selected').each(
function(i)
{
comboOptions[i] = $(this).val();
});
//window.alert(comboOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can swap -->
<h3>Words that can be Swapped</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSwap"/>
<button id="addSwap">Insert</button>
<label for="swapContain">Select as many as you like:</label>
<select id="swapContain" name="comboSwap" multiple></select>
<button id="checkSwap" onclick="checkSwap()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSwap").click(function()
{
$("#swapContain").append('<option value="' + $("#newSwap").val() + '">' + $("#newSwap").val() + '</option>');
});
});
$('#swapContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var swapOptions = new Array();
$('form').submit(
function()
{
$('#swapContain > option:selected').each(
function(i)
{
swapOptions[i] = $(this).val();
});
//window.alert(swapOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can be use as Synonyms -->
<h3>Words that can be used as Synonyms</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSyn"/>
<button id="addSyn">Insert</button>
<label for="synContain">Select as many as you like:</label>
<select id="synContain" name="comboSyn" multiple></select>
<button id="checkSyn" onclick="checkSyn()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSyn").click(function()
{
$("#synContain").append('<option value="' + $("#newSyn").val() + '">' + $("#newSyn").val() + '</option>');
});
});
$('#synContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var synOptions = new Array();
$('form').submit(
function()
{
$('#synContain > option:selected').each(
function(i)
{
synOptions[i] = $(this).val();
});
//window.alert(synOptions);
return false;
});
</script>
</fieldset>
</form>
<button onclick="generate_title()">Generate Titles</button>
<button onclick="displayList()">Click Me</button>
<script>
function displayList()
{
alert(coreOptions+ " " +comboOptions +" " +swapOptions+ " " +synOptions);
}
</script>
<div id="display"></div>
</body>
</html>
External Javascript
var check = ["Facebook", "MySpace", "Twitter"];
//document.getElementById("coreOptions");
//var checkX = check.splice(" ");
var checkY = document.getElementById("swapOptions");
var input_keywords =
[
[check, check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 24;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(input_keywords);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}

Categories

Resources