buttons don't work after append - jquery - javascript

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

Related

Loop for issue javascript won't run

So this exercice is about outputing a word by the number typed in the input section simple but i find this problem the loop for won't work if there is any help i will be greatfull
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script defer>
function Verifer() {
var ch = document.querySelector("input").value
var nbr = document.getElementById("nb").value
if ((nbr > 0) && (ch != "")) {
for (let i = 1; i >= nbr; i++) {
var txt = ""
txt += "<h1>" + ch + "</h1> <br>"
document.getElementById("d2").innerHTML = txt
}
} else {
alert("Retype plz")
}
}
</script>
</head>
<body>
// the first input is to type a String //the seconde input to type the number of repetition of this String
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
//This part is dedicated to the output of the function
</div>
</body>
change
var nbr = document.getElementById("nb").value
to
var nbr = parseInt(document.getElementById("nb").value)
Is this what you want to do? Your question is a bit vague.
function Verifer() {
var ch = document.querySelector("input").value;
var nbr = document.getElementById("nb").value;
nbr = parseInt(nbr); //Parse to int
console.log(nbr);
if (nbr === NaN || !ch) { //Validate
document.getElementById("nb").value = "invalid";
return;
}
var txt = ""; //Set var in scope around for loop
for (var i = 1; i <= nbr; i++) { //repeat when i is less or equal to nbr
txt += "<h1>" + ch + "</h1> <br>" //Append txt
}
document.getElementById("d2").innerHTML = txt; //Add txt to element html
}
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
</div>

Velocity/Java script form not retaining the input

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%;">

Max-Length for multiple text areas using php and Javascript

I am trying to display the number of characters left in multiple text areas. Although I have different ID's for the text areas, the max length is prompted only for the 2nd text area and not for the first. My code is as shown below
<textarea id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef = document.querySelector("#txtBox1");
var counterRef = document.querySelector("#counterBox1");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
The result is as below (What I have):
What I want :
Looks like the variables txtBoxRef and counterRef are in the same scope area, you declared twice.
<textarea id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef1 = document.querySelector("#txtBox1");
var counterRef1 = document.querySelector("#counterBox1");
txtBoxRef1.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef1.value.length);
if(remLength < 0)
{
txtBoxRef1.value = txtBoxRef1.value.substring(0, 160);
return false;
}
counterRef1.value = remLength + " characters remaining...";
},true);
</script>
check Fiddle
Try this:
<textarea id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef=document.querySelector("#txtBox");
var counterRef=document.querySelector("#counterBox");
txtBoxRef.addEventListener("keyup", function(){
var remLength=0;
remLength=160 - parseInt(txtBoxRef.value.length);
if(remLength < 0){
txtBoxRef.value=txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value=remLength + " characters remaining...";
}, true);
</script>
<textarea id="txtBox1"></textarea>
<input type="text" id="counterBox1"/>
<script>
var txtBoxRef1=document.querySelector("#txtBox1");
var counterRef1=document.querySelector("#counterBox1");
txtBoxRef1.addEventListener("keyup", function(){
var remLength=0;
remLength=160 - parseInt(txtBoxRef1.value.length);
if(remLength < 0){
txtBoxRef1.value=txtBoxRef1.value.substring(0, 160);
return false;
}
counterRef1.value=remLength + " characters remaining...";
}, true);
</script>
Your code can be optimized if you give it a thought.

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

trying to do calculation of 2 input fields update in real-time

I am trying to calculate 2 input fields and display the result in real-time in div totalPrice
no matter what I've tried can't get it to work
thx
<script src="jquery-1.11.1.min.js">
jQuery('#field2').on('input propertychange paste', function() {
var op1 = document.getElementById('field1');
var op2 = document.getElementById('field2');
var result = document.getElementById('totalPrice');
if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
result.value = 0;
result.value = parseInt(result.value);
result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
}
var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
});
</script>
<form action="" id="cakeform" onsubmit="return false;">
<input type="text" value="" size="20" name="field1" id="field1" class="rsform-input-box">
<input type="text" value="" size="20" name="field2" id="field2" class="rsform-input-box">
<div id="totalPrice"></div>
</form>
What about this http://jsfiddle.net/20Lgz8ey/2/
$('#field1,#field2').on('input propertychange paste', function() {
$('#totalPrice').html(parseFloat($("#field1").val()!=''?$("#field1").val():0)+parseFloat($("#field2").val()!=''?$("#field2").val():0));
});
also
<script src="jquery-1.11.1.min.js"></script>
<script>
code ....
</script>
$(document).ready(function () {
jQuery('#field2, #field1').on('input propertychange paste', function () {
var op1 = document.getElementById('field1');
var op2 = document.getElementById('field2');
var result = document.getElementById('totalPrice');
if (op1.value == "" || op1.value != parseFloat(op1.value)) op1.value = 0;
if (op2.value == "" || op2.value != parseFloat(op2.value)) op2.value = 0;
result.value = 0;
result.value = parseInt(result.value);
result.value = parseInt(result.value) + parseInt(op1.value) + parseInt(op2.value);
var divobj = document.getElementById('totalPrice'); divobj.style.display = 'block'; divobj.innerHTML = "Total $" + result.value;
})
});
try this if it helps you.

Categories

Resources