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.
Related
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.
In short, I'm trying to figure out how to change an HTML drop down based upon a selection made in another HTML dropdown. Something like this is the end product.. where you select something in the first box, and the second box populates based upon that first option.
However, I've become stuck at how to populate that second box with the code I have. It's not as simple as adding as the code creates arrays for all the options you have.
Some of the snippets I have are laid out like this.. (Javascript first)
function setModelLevels(mdlselc){
var selection = mdlselc;
if (selection == "nam_ncep" || selection == "nam_4km_ncep" || selection == "gfs_ncep" || selection == "rap_ncep" || selection == "wrf_nmm_ncep" || selection == "wrf_arw_ncep"){
levelDyMenuItems = new Array();
numDyLevelMenuItems = 0;
makeDyLevelMenuItem("sfc","***Surface***","","level")
makeDyLevelMenuItem("sfc","Surface","SELECTED ","level")
makeDyLevelMenuItem("pcp","Precip","","level")
makeDyLevelMenuItem("windvector","Wind Vector","","level")
makeDyLevelMenuItem("windgust","Wind Gusts","","level")
makeDyLevelMenuItem("ref","Simulated Reflectivity","","level")
} //Ends Model check
} //Ends setModelLevels
(HTML next)
<TR><TD>
<SELECT NAME="model" CLASS="controls1" onchange=setModelLevels(document.controls.model[document.controls.model.selectedIndex].value);>
<SCRIPT>
createMenuItems();
for (i = 1; i <= numModelMenuItems; i++) { document.writeln('<OPTION ' + modelMenuItems[i].modelDefault + 'VALUE="' + modelMenuItems[i].modelValue + '">' + modelMenuItems[i].modelLabel) }
</SCRIPT>
</SELECT>
</TD></TR><TR><TD>
<SELECT NAME="level" id="levelsel" CLASS="controls1">
<SCRIPT>
for (i = 1; i <= numDyLevelMenuItems; i++) { document.writeln('<OPTION ' + levelDyMenuItems[i].levelLabel + 'VALUE="' + levelDyMenuItems[i].levelValue + '">' + levelDyMenuItems[i].levelLabel) }
</SCRIPT>
</SELECT>
</TD></TR>
(The code isn't mine, it's a somewhat publicly available weather model animator that I'm messing around with on my side.)
So basically, when you change the dropdown with the NAME="model", it drops the name of the model into the setModelLevels code. That sees what model you've selected, and makes an array with the necessary parameters to drive the rest of the page.
The problem comes with the fact that the created array never displays back into the main webpage. I would assume I need to push my newly created array into the HTML document.. but I've only done that with jquery before. And I cannot use jquery for this due to the restrictions we have on our pcs.
I'm looking for any help here.. I'm a bit of a novice of a coder and I'm trying my hardest not to edit/rewrite the code here.
Thanks.
Addendum
The makeDyLevelMenuItem basically makes the array of menu items to list. It looks like this..
function makeDyLevelMenuItem(levelDyValue,levelDyLabel,levelDyDefault,levelDyClass) {
numDyLevelMenuItems++;
levelDyMenuItems[numDyLevelMenuItems] = new levelDyMenuItem(levelDyValue,levelDyLabel,levelDyDefault,levelDyClass);
}
Here is the JS code in which I am splitting a String using ":" . So a String given by:
Habit #1: Have you established dedicated business checking account(s)?
Would split into:
[0]=Habit #1
and
[1]=Have you established dedicated business checking account(s)?
Now I want to apply CSS to [0].
titles=document.getElementsByClassName("title");
for(var i=0;i<titles.length;i++){
titles[i].innerHTML.split(":")[0].style.cssText="color:aqua;";
}
Any modification you guys suggest to the existing code?
You can replace the fist part of the string like so:
var titles=document.getElementsByClassName("title");
for(var i=0;i<titles.length;i++){
var blueFoo = titles[i].innerHTML.split(":")[0];
var text = titles[i].innerHTML;
var newHTML = text.replace(blueFoo,'<span style = "color:blue">' + blueFoo + '</span>');
titles[i].innerHTML = newHTML;
}
For example:
var titles=document.getElementsByClassName("title");
titles= "<span>" + titles;
titles=titles.replace(":", ":</span">);
document.getElementsByClassName("title").innerHtml = titles;
I think this could work.
I think you have to wrap the first characters to the ":" with a <span class=""> and give them a css class.
<p><span class="blue">Habit #1:</span> Have you ... </p>
Mike
I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/
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