Hi I'm using a CMS which dynamically creates textareas on product pages of an ecommerce site. The text area has a different ID on each different product page. I am in need of some javascript that will check if all textareas on a page are empty and if so display a warning message. I cant assign an id to the text areas so cant use this script I normally use. Any help is much appreciated!
function validate() {
var val = document.getElementById('textarea').value;
if (/^\s*$/g.test(val)) {
alert('Wrong content!');
}
}
Hey Benjamin thanks for your reply, I couldn't get the code working in comments, thinking I'm having a bad day. So as i was trying to say I'm not the greatest at Javascript (but eager to learn!) I've added this to my page but it doesn't appear to work:
<script>
var areas = document.getElementsByTagName("textarea");
// now iterate them for
(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
} </script>
With this as in the body
<div class="description">Further Details <br>
<textarea id="catProdInstructions_6486638" class="productTextarea"></textarea>
</div>
Thanks for your time on this :)
You can use getElementsByTagName to fetch all <textarea>s.
It returns a NodeList of all the text areas currently in the page which you can iterate.
var areas = document.getElementsByTagName("textarea");
// now iterate them
for(var i=0;i<areas.length;i++){
var val = areas[i].value;
if (/^\s*$/g.test(val)) {
// whatever
}
}
The NodeList returned is live , this means that it'll update itself automatically as new textarea elements are added dynamically even if you fetch them with ajax or create them with code.
Related
Trying to make a dynamic div but i don't know how. Wrote a solidity smart contract that accepts an array of struct. In the smart contract i can use a get function to display the data inside. Data in the array is treated like a history, it consists of amount (making a crowdfund site), date, currency used, etc. Since the get function in the smart contract can only extract one part of the array, i thought of putting the get function into the while loop and extract the whole history array..
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
I'm trying to dynamically create another div with the same amount of < a > in the div. If i had 10 sets of data to display in that div, i wish to create only 10 sets of that div. Can createElement() be used to do that? Couldn't find any solution that works. Totally have no idea on how to create it. Can someone please help.
Would it be rational to extract the data from the array using a while loop and putting it in a div to display or would it use too much gas for this to work?
I don't get why would you want to do this, but you can do like this:
$('#set a').each(function(){
$('#set').after( "<div></div>");
});
It selects all of the <a>...</a> inside the <div id="set">...</div> element, and for each one of those inserts a <div></div> element. It inserts the element right next to #set but you can change that to any other element you could select.
I'm supplying jQuery code since you tagged the question as jQuery.
Hope it helps,
You can get the number of anchor tags by using this function getElementsByTagName('a').length from the hosting div. Then use that number to create new divs. This solution is done using vanilla JS.
function createDynamicDivs(){
var newDiv = document.createElement("div");
var noOfAnchors = document.getElementById('set').getElementsByTagName('a').length;
for(var i=0;i<noOfAnchors;i++){
var newContent = document.createElement("a");
newContent.textContent= "Test ";
newDiv.appendChild(newContent);
}
document.getElementById('new').appendChild(newDiv);
}
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
<div id="new"></div>
<button onclick="createDynamicDivs()">Generate</button>
I need to create a link for a set of documents. They are created dynamically, thus the names are also different, f.ex. Test, Test2, so one.
I need to show the link like "Document TestN", where links changed according to the current document. I can now create the links by a href="id" onklick=bla+bla+bla", but the name does not change. Instead of 'Dashboard' I need to get 'Dashboard of "ConcreteSite"', where I can get names by pageHeader:
document.getElementById("pageHeading").appendChild(pageHeading);
<script language="javascript" type="text/javascript">
var siteNameAsParam = window.location.search;
var scrt_var = siteNameAsParam.split("siteName=")[1];
</script>
<p>You are here: Dashboard </p>
Based on your code I think this is what you're after but more detail on what you're trying to do would be great.
<p>You are here: Dashboard </p>
<p>You are here: Dashboard </p>
<script>
document.addEventListener('DOMContentLoaded', function(event) {
var links = document.getElementsByTagName("a");
for (i = 0; i < links.length; i++) {
var siteNameAsParam = window.location.search;
var scrt_var = siteNameAsParam.split("siteName=")[1];
links[i].href = links[i].href + '?siteName=' + scrt_var;
links[i].innerText += ' fred';
}
}, false);
</script>
This does the following:
On page load gets all links on the page
loops through the links and grabs the query strings from the url
splits the query string on siteName
sets each link url to add the query string
updates the links text to append the query string (or undefined if it doesn't exist (see note below)
Note: your code implies you already have a query string in the url of siteName=SITENAMEHERE. Also, depending what you're trying to achieve, there are probably much better approaches. This I hope answers your current question but I think you should review how other achieve what you're after.
Update:
Here is a jsfiddle with a different working sample of what I think you might want. Hopefully it helps. there are comments in the fiddle. I think you want to try doing more when the link is created (set the event listener there, update the text as desired, etc.) instead of on the click event.
I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.
Is there a way to use gdata api to retrieve the list of all labels in a blogger?
I need to create a menu based on that list, but cannot simply list all posts and get it, because it is a busy blog and has more than 2000 posts.
Here is the most easy way to get a list of labels by using json call:
<script>
function cat(json){ //get categories of blog & sort them
var label = json.feed.category;
var lst=[];
for (i=0; i<label.length; i++){
lst[i] = label[i].term ;
}
alert(lst.sort()); //use any sort if you need that
}
</script>
<script src="http://yourblog.blogspot.com/feeds/posts/summary?alt=json&max-results=0&callback=cat"></script>
Just use your blog url.
Very simple, I give you two ways
With Javascript API
First, you must use:
<script type="text/javascript" src="http://www.google.com/jsapi"></ script>
<script type='text/javascript'>
google.load("gdata", "1.x", { packages : ["blogger"] });
</script>
Second, you can use the code below to retrieve the labels
postRoot.entry.getCategories()[i].getTerm()
For more tutorials, you can read from http://www.threelas.com/2012/05/how-to-retrieve-posts-using-blogger.html and http://www.threelas.com/2012/04/basic-blogger-javascript-api.html
With JSON
with json, if you want to learn how to retrieve the list of labels, use this object
json.feed.entry[i].category[j].term
for more detail tutorials, read from http://www.threelas.com/2012/02/basic-blogger-json-feed-api.html and http://www.threelas.com/2012/09/blogger-json-feed-with-jquery-ajax.html
The way I found was using the Blogger's own gadget called Labels. It prints the list of labels and their usage count within some unordered lists(ul) and links(a). You can pull the labels from that after they are loaded using javascript as follows:
$(".list-label-widget-content a").each(function (i, el) {
var labelText = $(el).text();
// do what you want with the labels
});
in the end, remove the Labels div element (<div class='widget Label' id='Label1'>)
Widget to server the same purpose is provided by bloggers itself.
Widget provides various options like -
You can either show all Labels or choose from your existing List
You can sort the Labels alphabetically or by number of times that label is used (frequency).
You can choose to display these as a List or as a cloud (jumbled).
You can see the same in my blog - Link
I don't see a method to get the list of labels in a blog, but you can retrieve all posts (https://developers.google.com/blogger/docs/2.0/json/reference/posts/list) and check the labels field for each of them: https://developers.google.com/blogger/docs/2.0/json/reference/posts#resource
First add the JQuery through the following code in console.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();
Once you are done with this we can take advantage of the JQuery and get the list of labels
Now what I am doing will work for the Blogger Theme Notable and newly added Theme for blogger.
Normally in these themes you will see Labels in the rights side toogle menu of the page.
So What you need it Click on the Label and Click on Show more.
Now Open Browser Debugging console and declare and variable.
var str = "";
Now run the two codes below
1. $('.first-items .label-name').each(function(){str = str + ", "+($(this).text())})
2. $('.remaining-items .label-name').each(function(){str = str + ", "+($(this).text())})
3. str
all the labels you will be get in comma(;) separated format.
I'm trying to write some code in javascript that uses a user's cookies to display a box containing some information. The page opens with some boxes containing news articles from Google News RSS feeds. I'm using a 3rd party app for the RSS; the feed is included in the HTML code as such:
<script language="JavaScript" src="http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed" charset="UTF-8" type="text/javascript"></script>
The user can move the boxes around, and I want to store the box locations using cookies so that if a user revisits the page, the boxes will be in the same location. However, when I try to load the page from the information in the cookies, the boxes are blank. This is an example of what my code looks like (RSS feed for news using keyword "Barack Obama"):
// Render boxes into HTML
function renderItem(container) {
var wrapper = document.getElementById(container);
var div_box = document.createElement('div');
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
var div_box_feed = document.createElement('div');
var feed_script = document.createElement('script');
feed_script.setAttribute('language', 'JavaScript');
feed_script.setAttribute('src', feed_url);
feed_script.setAttribute('charset', 'UTF-8');
feed_script.setAttribute('type', 'text/javascript');
div_box_feed.appendChild(feed_script);
div_box.appendChild(div_box_feed);
wrapper.appendChild(div_box);
}
When the page loads, the box appears but the news articles from the RSS feed are not there and the box is empty. When I look at the source code, however, it is identical to the code of the initial boxes (which did display the news articles).
Does anybody know what's wrong?
Thanks!
You never declared column_div here:
wrapper.appendChild(column_div);
Did you mean:
wrapper.appendChild(div_box);
?
I believe that by default script elements created in this manner have their async attribute set to true, so the rest of your code will execute before your JS has been retrieved.
Where does the column_div variable come from?
You're missing a question mark to separate the post variables from the URL, so the URL is resolving to
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php%20src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
It should be
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed'