Manipulating arrays and appending strings in complicated ways - javascript

I am some what a beginner in jquery/javascript. I am familiar with how it works, but its been a minute since I have worked with it and recently i've been tasked with something that I think jquery/html would be best for.
So I have a list of 500 refund numbers, i put them into a text box, click a button, and they currently go into an array, I know this works as when I alert the array, I see my values.
What I need some guidance with is how can I take the numbers in this array and make it populate a textbox that looks like the below.
send "REFUNDNUMBER1<f1>" #This is our refund number
send "5<f1>" # This LINE will come after every single refund number
So as you can see, i need to append : send " to the front of the refund number, and " to the end of it and then add send "5" to the line beneath it.
Essentially I am trying to generate a script for someone and if this is the wrong place for help I apologize sincerely, I just need some solid direction so that I can understand what I need to do and how to do it. I have very minimal experience with for loops and arrays unfortunately. and javascript for that matter.
Below is my html code/jquery
<div class="home-content">
<div class="home-heading">
<h1><em>Accounting</em> Void Refund Script Generator</h1>
</div>
<div class="row">
<div class="col-md-8">
<form>
Refund Numbers<br>
<textarea cols="38" rows="27" name="refundNumbers" id="refundNumberstxt"> </textarea>
</form>
</div>
<div class="col-sm-4">
<input type="text" name="companyNumb" size="2">
<button type="button" class="btn" id="generateButton">Generate Scripts</button>
</div>
</div>
</div>
$(document).ready(function(){
$("#generateButton").click( function(){
var txtRefundNumbers = $("#refundNumberstxt").val();
var arrayRefundNumbers = txtRefundNumbers.split('\n');
var msg = ""
var arrayVoidRefundsOutput = arrayRefundNumbers.map(function(x) {
for (var i = 0; i < arrayRefundNumbers.length; i++) {
return 'send "' + arrayRefundNumbers [i] + '"\nsend "5"\n';
}
}).join('');
alert(arrayVoidRefundsOutput)
for (var i = 0; i < arrayVoidRefundsOutput.length; i++) {
msg += arrayVoidRefundsOutput + "\n";
}
});
});
The html and jquery are in their own files fyi.
with the help of irkeninvader i was able to get this. I now get this
send "1"
send "5"
send "1"
send "5"
send "1"
send "5"
send "1"
send "5
which is not what im looking for and I am confused,

map lets you modify each value in an array. You should be able to use this to add text to the beginning and end of each refund number.
After using map to add the appropriate text, use join to create one long string again as your output.
var output = textread.map(function(refundNum) {
return 'send "' + refundNum + '"\nsend "5"\n';
}).join('');
I assume I didn't get that quite right but you should be able to modify it to get the correct text before and after each refund number.
The output variable should now contain your result. Do whatever you need to with it (put its contents into another texteara, log/alert it, etc).
That would make your click handler look like this:
$("#generateButton").click( function(){
var txt = $("#refundNumberstxt").val();
var textread = txt.split('\n');
var output = textread.map(function(refundNum) {
return 'send "' + refundNum + '"\nsend "5"\n';
}).join('');
alert(output);
});

Related

Add New Line in textarea by getElementById().value not Working

I'm quite new in Javascript. Sorry if I say some absurd. None of the previous answers I found here worked in my case...
The code gets an index from a selected option from a dropdown list generated by an array loop, and uses this index to post description of a product in a textarea. Ideal would be one in each line. But whenever I add '\n'(added only for visualization by the end of the code) or '
&#10'; the dropdown list itself disapears. Trying '< br>' does not work either.
pr[] is a nested array that contains a description of 10 products (ex adidas soccer ball) in its first position and price at the second.
The function buy() is called by a button onclick event, each time it is called it adds one product to the textarea.
Thanks in advance!
textd=" ";
valord=0;
function buy() {
var e = document.getElementsByTagName("select");
var f = e[0].selectedIndex;
textd +=pr[f][0];
valore = valord += pr[f][1];
document.getElementById("compras").value=textd\n;
document.getElementById("valor").value ="R$ "+ valore+",00";
}
You need to add "\n" to the end of the string while adding text to text area, then this "\n" ensures that row will be displayed in a new line instead of same line.
Look at the following code
<!DOCTYPE html>
<html>
<body>
<script>
function appendText()
{
debugger;
var ele = document.getElementById("textArea");
var text = ele.value;
text += "im clicked\n";
text +="clicked again\n";
text +="clicked third time\n";
text +="clicked forth time";
ele.value = text;
}
</script>
<textarea rows="4" cols="50" id="textArea">
At w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.
</textarea>
<button type="button" onclick="appendText()">Click me </button>
</body>
</html>
You may need to change your code to
textd +=pr[f][0] + "\n";
document.getElementById("compras").value=textd;

Get text between tags using javascript

I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.

Multiple values for one <option>

I'm trying to gain a better js-knowledge, and got a little problem.
I want to give a option more than one vaule, and from what i could find other places, arrays with split was the best solution. But I can't get it to work.
One side of the script is supposed to calculate a price, dependent on the selected destionation, while the other is the name on the destinaton.
<form name="ORDER" method="post" >
<select name="destination" id="destination_trV">
<OPTION VALUE="10,Cannes"> Cannes</option>
</form>
I want one part to grab the "10" to use this calculation purposes, and another to grab "Cannes" to write.
var dest_1 = (document.getElementById("destination_trV").value);
var vari_1 = dest_1.split(",",1);
var vari_2 = dest_1.split(",",1,2);
this is supposed to write out "10"
document.getElementById("linje5").innerHTML="Priceclass: " + vari_1 + "<br>";
this is supposed to write out "Cannes"
document.getElementById("linje6").innerHTML="Destination: " + vari_2 + "<br>";
But this doesn't work :)
What would happen if one of those values were to contain a , character? You'd need some form of encoding to preserve the original data. Instead of trying to jam multiple values into a single attribute, you'd be better off splitting those values into separate [data-*] attributes:
...
<option value="Cannes" data-destination="Cannes" data-price-class="10">Cannes</option>
...
That way, when you want the values, you can select the element and get the attribute values separately:
(function () {
var opt,
destination,
priceClass;
opt = document.getElementById("destination_trV");
destination = opt.getAttribute('data-destination');
priceClass = opt.getAttribute('data-price-class');
document.getElementById('linje5').innerHTML = 'Priceclass: ' + priceClass + '<br>';
document.getElementById('linje6').innerHTML = 'Destination: ' + destination + '<br>';
}());
Split does not work that way MDN split
string.split([separator][, limit])
Just do the split once
var vals = dest_1.split(",");
var vari_1 = vals[0];
var vari_2 = vals[1];
A better way would be to use data attributes.

Jquery adding items to a list without reloading page

I'm pretty stuck on how this should be achieved, mostly down to my lack of javascript knowledge. This is the code I'm looking at:
http://jsfiddle.net/spadez/VrGau/
What I'm trying to do is have it so a user can type add a "responsibility" in the responsibility field, then click add and have it appear in a list above it. The user can do this for up to 10 responsibilities.
The result would look something like this:
**Responsibility List:**
- Added responsibility 1
- Added responsibilty 2
*responsibility field - add button*
Can anyone explain how this should be done, it seems like it would have to involve ajax. I would really appreciate some more information or even an example.
Thank you.
EDIT: Here is a little bit more clarification. I want this data to be sent to the server as a list of items. I have seen examples of this being implemented, and here is a screenshot:
The user types in something in the text box, then clicks "add" and then it appears in a list above it. This information is what is submitted to the server.
Maybe this one can help also, this limits only 10 list
var eachline='';
$("#send").click(function(){
var lines = $('#Responsibilities').val().split('\n');
var lines2 = $('#Overview').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += '- Added ' + lines[i] + '\n';
}
}
$('#Overview').text(eachline);
$('#Responsibilities').val('');
});
Try it here
http://jsfiddle.net/markipe/ZTuDJ/14/
Something like that maybe?
http://jsfiddle.net/VrGau/10/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#send'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
$responsibilityList.val(newVal+'\n');
$responsibilityInput.val('');
}
}
$inputButton.click(addResponsibility);
Add id for textarea fields
<textarea rows="4" cols="50" placeholder="Responsibilities" id="resplist"></textarea>Add responsibility<br />
<textarea rows="4" cols="50" placeholder="How to apply" id="inputresp"></textarea>
You need Jquery. Use this js code
var i=0;
$("#send").click(addresp);
function addresp()
{
if (i<10)
{
$("#resplist").val($("#resplist").val()+$("#inputresp").val()+'\n');
$("#inputresp").val("");
i++;
}
}
http://jsfiddle.net/br0nsk1y/bDE9W/
It depends on if you want to post data to the server or not. If only in the client side you can do like this.
$("#send").on("click", function(event){
if($("#list li").size() < 10){
$("#list").append("<li>" + $("#responsibilities").val() + "</li>");
}
});
http://jsfiddle.net/VrGau/7/

Pass variable in document.getElementByid in javascript

I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product

Categories