Same Javascript Variable works only when manually entered in - javascript

I've been working on a script to take text from one div on a page and enter it into another. I came across a strange problem. When I alert my FillinId variable I come up with questionTextF. However, when I try to use that value in my next variable, GrabFillinDiv, the value comes back null. If I manually enter in questionTextF instead, everything works. I can't do it this way though, because there are multiple FillinId's to grab content from.
Here's a JSFiddle:
http://jsfiddle.net/hzbdhxvs/
Here's my Javascript:
$(document).ready(function(){
var QuestionTypeName = "MultipleListQuestion-test";
var FillinDivParent = document.getElementById(QuestionTypeName);
var FillinDivChildren = FillinDivParent.getElementsByTagName("div");
for (i=0; i< FillinDivChildren.length; i++){
var FillinId = $(FillinDivChildren[i]).attr("id");
alert(FillinId);
var TplId = FillinId.slice(0,-1);
var GrabFillinDiv = document.getElementById("\"" + FillinId + "\"");
var GrabFillinText = $("\"" + "#"+ FillinId + "\"").html();
alert(GrabFillinDiv.innerHTML);
$("\"" + "#"+ TplId + "\"").html(GrabFillinText);
}
});

You are adding some quotes before and after the id. Don't do that:
for (i=0; i< FillinDivChildren.length; i++){
var FillinId = $(FillinDivChildren[i]).attr("id");
alert(FillinId);
var TplId = FillinId.slice(0,-1);
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+FillinId).html();
$("#"+ TplId).html(GrabFillinText);
}
var QuestionTypeName = "MultipleListQuestion-test";
var FillinDivParent = document.getElementById(QuestionTypeName);
var FillinDivChildren = FillinDivParent.getElementsByTagName("div");
for (i=0; i< FillinDivChildren.length; i++){
var FillinId = $(FillinDivChildren[i]).attr("id");
alert(FillinId);
var TplId = FillinId.slice(0,-1);
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+FillinId).html();
$("#"+ TplId).html(GrabFillinText);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="care-questionType">
<form role="form">
<div id="questionText">
</div>
<div id="PrimaryResponseItemList">
<div class="checkbox" data-repeat="responseItem" id="">
<label id="ResponseLabel">
<input id="ResponseCheckBox" type="checkbox" value=""/>
</label>
</div>
</div>
<div id="OtherResponseItem">
<p id="OtherResponseLabel" ></p>
<div class="input-group">
<label class="input-group-addon">
<input id="OtherCheckBox"type="checkbox">
</label>
<input type="text" id="ResponseOtherSpecifyText" class="form-control-inline care-multipleSelect-otherText" />
</div>
</div>
</form>
</div>
<div style="display:none;">
<div id="MultipleListQuestion-test">
<div id="questionTextF">
<p>Which categories best describe your racial background? (Please choose all that apply)</p>
</div>
<div id="responseItemF" data-repeat="true">
<p>test</p>
<div id="ResponseLabelF">
American Indian or Alaskan Native
</div>
</div>
</div>
</div>

Get rid of the "\"" insertions. Instead of
var GrabFillinDiv = document.getElementById("\"" + FillinId + "\"");
var GrabFillinText = $("\"" + "#"+ FillinId + "\"").html();
Try:
var GrabFillinDiv = document.getElementById(FillinId);
var GrabFillinText = $("#"+ FillinId).html();
http://jsfiddle.net/hzbdhxvs/1/

Related

Concatenate select box selected values

Thanks in advance! I am building an application using asp.net web form that have one dropdownlist and two listbox, which needs to be clone whenever a button is click. My problem is I'm currently hard coding a lot of code and I will like to make it more dynamic. Can everyone help me figure this out?
Here is an example of what my current script is doing.
Code:
$(document).ready(function() {
var clone = (function() {
var cloneIndex = 0;
var template = $('#categoryTemplate').text();
return function() {
return template.replace(/ID/g, ++cloneIndex);
}
})();
//Start off with 1 category.
categories.append(clone());
var sbClone1 = new StringBuilder();
$(document).on('change', '#MainContent_ddlWarehouse1', function () {
var myele = '';
sbClone1.strings[0] = [];
var mystring = '';
myele = $(this).val();
sbClone1.strings[0] = 'SELECT top 10 ' + myele + ', PART_CODE, WAREHOUSE, UNIT_OF_MEASURE, MOVEMENT_DATE, MOVEMENT_CODE, [IC_MOVE_QUANTITY] FROM [dbo].[IC_MOVEMENTS] WHERE MOVEMENT_DATE between "' + startDateTextBox.val() + '" and "' + endDateTextBox.val() + '" AND WAREHOUSE = "' + myele + '" ';
mystring = sbClone1.toString();
$('#MainContent_hfConcatString').val(mystring);
document.getElementById("MainContent_Label1").innerHTML = mystring;
});
$(document).on('change', '#MainContent_lbMovementCode1', function () {
var myele = '';
sbClone1.strings[1] = [];
var mystring = '';
myele = $(this).val();
sbClone1.strings[1] = 'AND MOVEMENT_CODE IN "' + myele + '" ';
mystring = sbClone1.toString();
$('#MainContent_hfConcatString').val(mystring);
document.getElementById("MainContent_Label1").innerHTML = mystring;
});
$(document).on('change', '#MainContent_lbUnitofMeasure1', function () {
var myele = '';
sbClone1.strings[2] = [];
var mystring = '';
myele = $(this).val();
sbClone1.strings[2] = ' AND UNIT_OF_MEASURE IN "' + myele + '" ';
mystring = sbClone1.toString();
$('#MainContent_hfConcatString').val(mystring);
document.getElementById("MainContent_Label1").innerHTML = mystring;
});
$(document).on("click", 'button.add', function() {
categories.append(clone());
});
});
<script type="text/template" id="categoryTemplate">
<div class="category" id="DatasetID">
<div class="row">
<!-- Warehouse Category -->
<div class="col col-lg-4">
<div class="form-group">
<label class="control-label" for="WarehouseID">Warehouse</label>
<asp:DropDownList ID="ddlWarehouseID" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="Please Select"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
<!-- MovementCode Category -->
<div class="col col-lg-4">
<div class="form-group">
<label class="control-label" for="MovementCodeID">Movement Code</label>
<asp:ListBox ID="lbMovementCodeID" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</div>
</div>
<!-- UnitofMeasure Category -->
<div class="col col-lg-4">
<div class="form-group">
<label class="control-label" for="UnitofMeasureID">Unit of Measure</label>
<asp:ListBox ID="lbUnitofMeasureID" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</div>
</div>
</div>
</div>
</script>
There is no need to iterate through the options, try following:
var string = $("[name=cars]").val().join(", ")

Trying to remove each line of HTML element using a newly created button

var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var IncomeList = document.getElementById("incomeList");
var ExpenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
var DButton = document.createElement("button");
var t = document.createTextNode("Delete");
//document.body.appendChild(DButton);
DButton.appendChild(t);
// Converts the fake (non-existant)numbers into real (functionable) numbers
var aValue = parseFloat(Amount.value);
// if the operator is +, budget and income will increase by whatever you type in the value
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
// The value that was typed along with description in will appear in the Income list in each line
IncomeList.innerHTML = IncomeList.innerHTML + Desc.value + ": " + aValue;
IncomeList.appendChild(DButton);
IncomeList.innerHTML = IncomeList.innerHTML + "<br>";
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
ExpenseList.innerHTML = ExpenseList.innerHTML + Desc.value + ": " + aValue;
ExpenseList.appendChild(DButton);
ExpenseList.innerHTML = ExpenseList.innerHTML + "<br>";
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget;
document.getElementById("incomeTotal").innerText = income;
document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>
Hi, this is a budget tracker I made to practice JavaScript. So whenever users type a description and an amount and press submit, the list will show up along with a delete button that erases each line. How should I approach this method? Because the button is newly created by createElement, I do not know how to make this a handler...Thank you.
Append a row container instead of concatenating to the HTML string, and then you can attach a listener to the button that calls .remove() on the row.
It's often a good idea to avoid assigning to innerHTML when possible - it will corrupt all existing Javascript references to any elements inside. If you want to assign text alone, use textContent rather than innerHTML or createTextNode. (it's faster, safer, and more predictable)
var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var incomeList = document.getElementById("incomeList");
var expenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
const parent = Operator.value === "+" ? incomeList : expenseList;
const row = parent.appendChild(document.createElement('div'));
var DButton = row.appendChild(document.createElement("button"));
DButton.textContent = 'delete';
DButton.onclick = () => row.remove();
var aValue = parseFloat(Amount.value);
row.appendChild(document.createTextNode(Desc.value + ": " + aValue));
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget; document.getElementById("incomeTotal").innerText = income; document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>

GetElementById from node object

I have the an html code which resembles this:
<div id="abc">
<div class="class1">some data</div>
<div class="class2">
<input type="number" id="row1-id1" />
<input type=number" id="row1-id2" />
</div>
<div class="class2">
<input type="number" id="row2-id1" />
<input type=number" id="row2-id2" />
</div>
</div>
I want to read all input tag and create a list from it. The input tag needs to be inside the div with class class2 which in turn should be under #abc.
I have written the following code to read them.
var rows = document.getElementById('abc').getElementsByClassName('class2');
for (var i=0;i<rows.length;i++) {
var id1 = rows[i].getElementById('row'+(i+1)+'-id1);
var id2 = rows[i].getElementById('row'+(i+1)+'-id2);
.......
.......
}
Now when i try to do the above i get an error saying 'getElementById is not a function'.
How do i access the element with specific Id inside the node?
First of fix the mistakes in your code. Your missing 2 " in your html, and 2 ' in your javascript.
Second, then use querySelector like: rows[i].querySelector('#row' + (i + 1) + '-id1'). Then your code works fine.
Demo
var rows = document.getElementById('abc').getElementsByClassName('class2');
for (var i = 0; i < rows.length; i++) {
var id1 = rows[i].querySelector('#row' + (i + 1) + '-id1');
var id2 = rows[i].querySelector('#row' + (i + 1) + '-id2');
console.log(id1)
}
<div id="abc">
<div class="class1">some data</div>
<div class="class2">
<input type="number" id="row1-id1" />
<input type="number" id="row1-id2" />
</div>
<div class="class2">
<input type="number" id="row2-id1" />
<input type="number" id="row2-id2" />
</div>
</div>
Please Note that since Id's should be unique, then you can always just use var id1 = document.getElementById('row' + (i + 1) + '-id1');

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

is it possible to make accordion title navigate to a new page?

i was wondering if i can make the title of an accordion a button as well without the button feeling?
here is a picture of the accordion title and some data inside it?
i want to click on the text that is in the title to navigate to a page...
using phonegap/cordova v1.9. Visual studio 2010 express for windows phone/html,CSS,javascript (c#)
any help will be appreciated :) im open to a solution in anyway, including jquery's
title is
inboxentry1 POS556445
I have made the accordion in a bunch of div's that stacked into eachother...
tell me if i must add anything else to help with the solution!
here is some html for the accordion!
<div id="AccordionContainer" class="AccordionContainer"></div>
<div onclick="runAccordion(1)">
<div class="Accordiontitle" onselectstart="return false;">
<input type="button" href="ItemPages.html">inbox entry1</input>
<br/>
<a>POS556446x</a>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent" style="background-color:white; color:grey;">
<form>
<p>
<label for="create" >Created by :</label>
<input type="text" style="margin-left:60px;" size="22" id="create"/>
</p>
<p>
<label for="createdate" >Created Date :</label>
<input type="text" style="margin-left:43px;" size="22" id="createdate"/>
</p>
<p>
<label for="process" >Process name :</label>
<input type="text" style="margin-left:36px;" size="22" id="process"/>
</p>
<p>
<label for="transtype">Transaction type :</label>
<input type="text" style="margin-left:20px;" size="22" id="transtype"/>
</p>
<p>
<label for="lastact">Last action :</label>
<input type="text" style="margin-left:61px;" size="22" id="lastact"/>
</p>
<p>
<label for="lastuser">Last user :</label>
<input type="text" style="margin-left:73px;" size="22" id="lastuser"/>
</p>
<p>
<label for="lastupd">Last update :</label>
<input type="text" style="margin-left:55px;" size="22" id="lastupd"/>
</p>
<p>
<label for="duration">Duration :</label>
<input type="text" style="margin-left:78px;" size="22" id="duration"/>
</p>
<p>
<label for="saved">Saved :</label>
<input type="text" style="margin-left:93px;" size="22" id="saved"/>
</p>
<p>
<label for="adhoc">Ad hoc user :</label>
<input type="text" style="margin-left:53px;" size="22" id="adhoc"/>
</p>
</form>
</div>
here is my .js file
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}
You probably want to make some changes here. A few classes have been added and the button tag changed as it wasn't correct. Your want to remove the inline event you have for the accordion and stick it where commmented below.
<div class="AccordionRun">
<div class="Accordiontitle" onselectstart="return false;">
<input class="AccordionLink" type="button" href="ItemPages.html" value="inbox entry1">
<br/>
<a>POS556446x</a>
</div>
</div>
Then you can get it and add a click event to it...
var goToPage = function(elem) {
elem.onclick = function() {
alert('Go to page...');
window.location = elem.href;
};
};
var runAccordion = function(elem) {
elem.onclick = function() {
alert('Run Accordion...');
// Your accordion code goes here...
};
};
var buttons = document.getElementsByTagName('input');
for(var i=0; i < buttons.length; i++) {
if (buttons[i].className == 'AccordionLink') {
goToPage(buttons[i]);
}
}
var divs = document.getElementsByTagName('div');
for(var i=0; i < divs.length; i++) {
if (divs[i].className == 'AccordionRun') {
runAccordion(divs[i]);
}
}
jsfiddle.net/FKt4K/2
If you'd like to navigate to an other page on click of an input field, here's a simpe work-around.. Just bind it to a mouseup-event like so (needs a jQuery implemention):
UPDATED CODE
HTML:
<input class="followThisRel" type="button" rel="http://yoursite.com/">
JS:
$(function() {
$('input.followThisRel').on('click', function() {
var url = $(this).attr('rel');
window.location = url;
});
})

Categories

Resources