I am having trouble accessing a variable using angularjs and ionic. I have a page where I am listing an amount of items:
<ion-item ng-repeat="item in items"
item="item"
href=""
style="max-height:70px; padding: 0px 0px 0px 0px;"
>
<div class="containerText" style="position:absolute; float:left; margin-left:60px">
<div class="" style="font-size:11px">
{{item.datea}}
</div>
<div class="" style="margin-top:4px; font-weight:bold; text-align:right">
{{item.value}}
</div>
</div>
(...)
And I want to load the item.value when I press the "download" button that each item row has next to the delete icon:
I am converting all the numbers to strings in the input field to make it easier to control the changes (like adding a decimal point or deleting the last value of that string).
My controller.js has these functions:
$scope.searchText = "0";
(...)
/****************** KEYBOARD FUNCTIONS ************************/
//Adds a number in the field text above the keyboard
$scope.addNumber = function(num) {
//limiting the amount of numbers in the display
if (this.searchText.length < 20)
if (this.searchText == "0")
if (num != '.')
this.searchText=num;
else
this.searchText = (this.searchText) + num;
else
if (num!='.')
this.searchText = (this.searchText) + num;
else if (this.searchText.indexOf('.') == -1)
this.searchText = (this.searchText) + num;
}
//Used to delete the number in the screen and set it to 0
//AKA RESET
$scope.deleteNumbers = function(){
this.searchText= "0";
console.log("ERASING!");
}
//Used to delete the last entered digit/symbol
$scope.deleteLast = function(){
this.searchText = this.searchText.slice(0, -1);
if (this.searchText.length==0)
{
this.searchText = "0";
}
}
//used to load the values of an element of the list to the display
$scope.loadItem = function(valueToAdd){
console.log("Load values ");
$scope.deleteNumbers();
$tempVal = valueToAdd.toString();
$scope.addNumber($tempVal);
console.log("value in this.searchText " + this.searchText);
console.log("value in scope.searchText " + $scope.searchText);
console.log(isNaN($tempVal));
}
And it loads nicely the first execution (only if I have not pressed the coded keyboard before), but after touching my created keyboard, the "load number" function stops working.
My console.log looks like this when I load the page and I press one of thos download buttons:
controllers.js:185 Load values
controllers.js:77 ERASING!
controllers.js:212 value in this.searchText 14458.553
controllers.js:213 value in scope.searchText 14458.553
controllers.js:214 false
As you can see, it says that it is a numeric value that has been loaded into the field, but it let's me add additional numbers or delete the chars of the input string without problem, but if I want to load another value (or even the same previously loaded) it seems that the scope gets messed up as I get this output.
controllers.js:185 Load values
controllers.js:77 ERASING!
controllers.js:212 value in this.searchText 14458.55
controllers.js:213 value in scope.searchText 15429.477
controllers.js:214 false
I have tried modifying at the same time this.searchText and scope.searchText but without result. What can I do to fix this?
Related
I'm attempting to make a dynamic filter on one iframe with two input boxes. Let's call the input boxes "Box 1" and "Box 2". When both boxes are not populated, I would like the iframe to display all of the information. When Box A is populated, I want it to display information on Box A. When Box B is populated as well, I would like both the filters to apply. When only Box B is populated, I would like the iframe to only display Box B's input.
One limitation I have is the changing nature of having one of the input boxes blank. I am limited to assigning a number to the input on the URL (e.g. - col1, op1, val1). If the "salModBox" is blank for instance, it needs to be dynamic enough to assign "serNumPrefBox" with col1, op1, val1). If both are populated, it would need to be col1, op1, val1 for "salModBox" and col2, op2, val2 for "serNumPrefBox". If neither are populated, well, it doesn't need to have col1 or 2 for that matter.
Expected output of the URL would ultimately look like this if both are populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod+"&col2=Variable%20Number%20Two&op2=EQ&val2="+serNoPre+"#/moreinfo/anotherID
Expected output of the URL with one variable populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod (or serNoPre) +"#/moreinfo/anotherID
With both of them blank, it would simply be the original URL source link. This would be a wide open search. A user isn't technically limited to values they can put in either input box.
function salModSnpFilter() {
var salModInput = document.getElementById('salModBox').value;
var serNumPrefInput = document.getElementById('serNumPrefBox').value;
var smSnp = '';
if (salModInput = ' ' and serNumPrefInput = ' ') {"https://en.wikipedia.org/wiki/IFrame"
} else if (salModInput = ' ' and serNumPrefInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput
} else if (serNumPrefInput = ' ' and salModInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + salModInput
} else if (salModInput != ' ' and serNumPrefInput != ' ' {"chttps://en.wikipedia.org/wiki/IFrame"+salModInput+serNumPrefInput
} else {"https://en.wikipedia.org/wiki/IFrame"
}
var salModString = "https://en.wikipedia.org/wiki/IFrame" + salModInput";
var serNumPrefString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput";
var bothString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput + salModInput";
document.getElementById('SM_SNPiFrame').src = salModString;
document.getElementById('SM_SNPiFrame').src = serNumPrefString;
document.getElementById('SM_SNPiFrame').src = bothString;
}
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name = "Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame"
width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
I ultimately used this code and it worked:
function filterSelection() {
var smBoxValue = document.getElementById("salModBox").value;
var snpBoxValue = document.getElementById("serNumPrefBox").value;
if (smBoxValue != "" && snpBoxValue != "") {var combinedModString =
"https://example.com/col1=Serial%20Number%20Prefix&op1=EQ&val1=" +
snpBoxValue +"&col2=Sales%20Model%20BOM%20EDS&op2=EQ&val2=" +
smBoxValue";
document.getElementById('SM_SNPiFrame').src = combinedModString;
}
else if (smBoxValue == "" && snpBoxValue != "") {var snpModString =
"https://example.com/#/col1=Serial%20Number%20Prefix&op1=EQ&val1="
+ snpBoxValue;
document.getElementById('SM_SNPiFrame').src = snpModString;
}
else if (smBoxValue != "" && snpBoxValue == "") {var salModString =
"https://example/col1=Sales%20Model%20BOM%20EDS&op1=EQ&val1=" +
smBoxValue;
document.getElementById('SM_SNPiFrame').src = salModString;
}
else {document.getElementById('SM_SNPiFrame').src =
"https://example.com/";
}
}
Your code seems a bit complex than what your issue is, I'll explain to you how to correct this and use some good practices in JavaScript.
Since you need to handle the values inside the input tags and use them into the iFrame tag, we will do the following:
Global elements first.
Since we will probably need to define only once which DOM element is the iFrame tag and which ones are the input tags, lets have them at the very beginning:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
Also, we define a strings variable that will help us store the input values in the same index as elements array.
Set event listeners for every element.
After defining which elements we want to use, now we should handle the change of its value. The most fast-looking effect is to use keyup event, this will pass the value everytime that the user types:
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
In this event listener, you need to setup what will happen every time this event is fired. I just did a simple function to store the new value into the same index but in different array (strings array).
And after that done, call the function that will update the iFrame tag.
Keep your code simple and functional.
The function salModSnpFilter() doesn't need a lot of if statements and the same string appearing multiple times to handle the new source of the iFrame. Lets keep code simple:
const salModSnpFilter = () => {
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/"; //You can set it to empty: "" if you dont want slashes.
strings.forEach(string => {
if (string !== "") {
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
We define the base URL in a variable at the top and a variable that will hold the string that we will append to the base source.
We iterate over the strings array and add this string to finalString array in the same order of the inputs.
After this, the only thing left to do is to set the source of the iFrame tag.
Final code:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
const salModSnpFilter = () =>{
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/";//You can set it to empty: "" if you dont want slashes.
strings.forEach(string=>{
if(string !== ""){
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name="Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame" width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
Note: The order of the strings and how they are used on the iFrame are the same as the order you added the inputs to the elements array. This means, inputA value will always go before inputB value. Unless you change the order in the elements array.
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
This is a pure JavaScript question no jQuery please.
Trying to make a JavaScript Dartboard score keeper. Running into an issue of printing an incremental list. When you click a part of the dartboard would like to calculate throws 1, 2, and 3. The problem is I would like to print off those throws in incremental list format.
HTML:
<button class="score-section" data-value="20" data-multiplier="1">20</button>
<ul id="dartTotals">
<li>Throw 1: {total}</li>
<li>Throw 2: {total}</li>
<li>Throw 3: {total}</li>
</ul>
JavaScript
document.body.onclick = function(e){
e = e.target;
if (e.className && e.className.indexOf('score-section') != -1) {
var i = 0;
(function increment(){
document.getElementById('dartTotals').innerHTML += "<li> Throw " + ++i + ": " + " total </li>";
}());
}
}
The only thing I've been able to do is add 1 to i and just keep printing that off with out incrementing i. Or run a for loop and print off the list but it does it 3 at a time. Could someone assist in helping to show how I can go about making this incremental list with each click? Thanks in advance.
JSFIDDLE
Update:
Updated Fiddle
On body click the function was getting reset. Moved var i, now called dartThrow out of the function scope and is working as expected.
var dartThrow = 0;
document.body.onclick = function(e) {
e = e.target;
if (e.className && e.className.indexOf('score-section') != -1) {
(function increment() {
document.getElementById('dartTotals').innerHTML += "<li> Throw " + ++dartThrow + ": " + " total </li>";
}());
}
}
You're setting $i to 0 on every click and then increment that value. Just do a variable outside your functions scope and then it should increment properly everytime with the code you already do have. You'll just need a reset when $i reaches your total throw count that you want.
I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful
I have following code to implement simple practice shopping cart using JavaScript. There is a checkout link which calls getcookie() to check the value of the cookies stored. When nothing is in the cookie then click on the link alerts to make input. If non of the values are entered in the input box and hit "add to cart" then validation is done and error message is alerted.
For some reason, the cookie is not taking the value from the input field. I tried quite a while now but was not able to debug the code. Just an empty alert box is shown at last. I appreciate any debugging. Thanks in advance.
<script type="text/javascript">
var value;
var productID;
function setItem(abd) {
value = abd.value;
productID = abd.getAttribute("productID");
var intRegex = /^\d+$/;
var numberOfItems;
if (!intRegex.test(value) || (value <= 0)) {
alert('Please Enter valid numberofitem');
} else {
numberOfItems = value;
}
}
function getCookie() {
if (value == undefined) {
alert("There is nothing in the shopping cart!");
} else {
var cookieArray = document.cookie.split(';');
var printHolder = "";
for (var i = 0; i < cookieArray.length; ++i) {
var pairArray = cookieArray[i].split('=');
alert(pairArray[0]);
}
alert(printHolder);
}
}
function setCookie() {
if (value == undefined) {
alert("Please add number of items in text box");
} else {
document.cookie = productID + "=" + value + "; ";
alert(value + " Product(s) with id " + productID +
" has been added to shopping cart!");
}
}
</script>
Checkout
<input name="item-select" id="item-select"
productid="p001" style="width: 50px" onBlur="setItem(this)" >
<button type="button" onclick="setCookie()">Add to cart.</button>
The result I wanted is something like this at last!
This code works perfectly fine with some changes.
I was using chrome and later found out that
Google Chrome doesn't create cookies when the file is on the local machine and loaded in browser directly using file path.
Rather try with localhost. It is definitely working when you put the code in server. Chrome became pain in a b*t here!
If you were for idea on creating shopping cart with Javascript follow this link.
http://www.smashingmagazine.com/2014/02/create-client-side-shopping-cart/
Your getCookie is likely to give you incorrect results.
var cookiearray= document.cookie.split(';');
var toprint="";
for(var i=0; i<cookiearray.length; ++i)
{
var pairArray= cookiearray[i].split('=');
alert(pairArray[0]);
}
alert(toprint);
Two things wrong here;
1) When you are in your for loop, each time you loop you are alerting the first item in your array at all times pairArray[0] you need to change that to pairArray[i]
2) You are displayed with an empty alert because thats what you have assigned to the toprint variable.
- You assign toprint an empty string before your for loop, then you are alerting that variable without assigning it a new value, so you will be displayed with an empty alert box!
- Also make sure your cookie array is not empty.
Give that a try, enjoy coding :)
Kush