Having trouble appending javascript into my html - javascript

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.

"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.

<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

Related

Replace elements in a link using javascript

I have a link to add event to google calendar which is populated from a database, but the date is formatted yyyy-mm-dd, and the time hh:mm, and i cannot alter this, but google calendar will not accept.
Can anyone please help me use javascript and the 'replace' function to remove the'-' and ':' from the html please?
<a href="http://www.google.com/calendar/event?
action=TEMPLATE
&text=Tester12
&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z
&details=Oranges
&location=Newquay
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
many thanks.
Fetch the href link from tag and store it in a variable.
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Tester12&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z&details=Oranges&location=Newquay&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
This will remove all the '-' and ':' from dates parameter string and will store that link in 'finalLink' var.
Hope it helps.
I have been on the sniff for the whole code solution, and witha bit of mix and match, came up with this, AND IT SEEMS TO WORK!!!!!! But please feel free to edit into perfection!
<script>
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Example Event&dates=2018-12-16T10:3500Z/2018-12-16T12:0000Z&details=Trip to town&location=No mans land&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
</script>
Add Event
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.finalLink"), function(link) {
link.href = finalLink;
});
})();
</script>

AJAX Query to Web Service in SharePoint on Button Click

I am trying to have a button on a SharePoint form query the govt SAM web service. Basically, I want to be able to manually enter a value in the form, click an HTML button, to query that value from the open form, and then fill out the rest of the fields automatically and save the record in a SP list. I am just working on the query portion now. I have jquery embedded in my master page.
When I wrote all the logic in the browser console, everything works fine. I cannot get it to mesh up with the button. I get this error in the console.
"Uncaught SyntaxError: Unexpected token <" which makes no sense. Here is my script:
<script>
$("button").click(function () {
var SAM_Title = document.getElementById('Title_fa564e0f-0c70-4ab9-b863-
0177e6ddd247_$TextField').value;
var URL = "https://api.data.gov/sam/v1/registrations/" + SAM_Title +
"0000?api_key=xxxxxxxxxxxxxxxxxxxxxxx";
var SAM_AJAX = $.get(URL);
var SAM_JSON = SAM_AJAX.responseText;
var parsedJSON = JSON.parse(SAM_JSON);
var BusinessName = parse.sam_data.registration.legalBusinessname;
var StreetAddress =
parsedJSON.sam_data.registration.govtBusinessPoc.address.Line1;
var City = parsedJSON.sam_data.registration.govtBusinessPoc.address.City;
var ZIP = parsedJSON.sam_data.registration.govtBusinessPoc.address.ZIP;
}
</script>
Here is what I am putting in my script editor web part:
<html>
<script src="/SiteAssets/SAM_Query.js">
</script>
<body>
<button>Get External Content</button>
</body>
</html>
where SAM_Query.js is the above mentioned script.
I got it to work. The key was line 13 and cleaning up the syntax.
jQuery.noConflict();
jQuery( document ).ready(function() {
console.log( "jquery ready!" );
})
function samWebService() {
SAM_Title = document.getElementById('Title_fa564e0f-0c70-4ab9-b863-0177e6ddd247_$TextField').value;
console.log("DUNS: " + SAM_Title);
URL = "https://api.data.gov/sam/v1/registrations/" + SAM_Title + "0000?api_key=xxxxxxxxx";
console.log("URL: " + URL);
jQuery.ajaxSetup({ async: false });
SAM_AJAX = jQuery.get(URL);
console.log("SAM JSON response: " + SAM_AJAX);
SAM_JSON = SAM_AJAX.responseText;
console.log(SAM_JSON);
parsedJSON = JSON.parse(SAM_JSON);
console.log(parsedJSON);
BusinessName = parsedJSON.sam_data.registration.legalBusinessName;
StreetAddress = parsedJSON.sam_data.registration.mailingAddress.Line1;
City = parsedJSON.sam_data.registration.mailingAddress.City;
ZIP = parsedJSON.sam_data.registration.mailingAddress.Zip;
document.getElementById('Address_bc611d08-c16c-4ad9-a5b8-14388e176aba_$TextField').value=StreetAddress
document.getElementById('City_dd99bc74-382f-406c-aec0-8dc196b2c8ef_$TextField').value = City
document.getElementById('Business_x0020_Name_5eb60d17-9d0b-4243-92f5-81f5534e8bc0_$TextField').value = BusinessName
document.getElementById('ZIP_e078f52b-a0bc-4c95-a622-a16d6491b017_$TextField').value = ZIP
};
And calling the function with a clickable link.
<script src="/siteassets/lib/jquery/jquery.min.js"></script>
<script src="/test/SiteAssets/SAM_Query.js"></script>
Click Me!

Javascript for loop running out of sequence

I have a confusing problem where a line of code in my function is running before a loop which is stated above it. In my HTML I have:
<textarea id="textBox"></textarea>
<button id="submitButton" onclick="parseData()">submit</button>
<div id="put"></div>
And my JS function is:
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
$("#put").html($("#put").html() + "<table>");
for (var i = 0; i < data.length; i++) {
$("#put").html($("#put").html() + "<tr>"+data[i]+"</tr>");
};
$("#put").html($("#put").html() + "</table>");
return;
};
The resulting html in $("#put") is this:
<table></table>
"SiO2 (%)Al2O3 (%)TiO2 (%)CaO2 (%)MgO2 (%) 8.21.25.31.51.8 45.32.52.60.210.5 65.23.48.70.0662.3 20.11.85.42.540.2 18.91.12.34.810.7"
I'm not sure why the final </table> is being placed before the for loop runs, and I'm not sure why the <tr> tags aren't being added within the for loop. Any pointers?
jQuery automatically closes up tags upon insertion. Try this.
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
var put_html = $("#put").html() + "<table>";
data = data.split(tab);
for (var i = 0; i < data.length; i++) {
put_html += "<tr>"+data[i]+"</tr>";
};
put_html += '</table>';
$("#put").html(put_html);
return;
};
However, I notice that you aren't using <td> elements. You might want to look into fixing that too.
Every time you are adding content into the html() property rather than building the entire content and adding it.
Since you are using jQuery you can bind the event using jQuery rather than adding that directly in the HTML
<textarea id="textBox"></textarea>
<button id="submitButton">submit</button>
<div id="put"></div>
$(function(){
$("#submitButton").click(function(){
parseData();
});
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
// Build your html
$("#put").html('htmlstructure');
return;
}
});
Also you can look for something similar like concatenating the string in an array so that you don't create string isntances each time when you append, since strings are immutable.
Good example

jQuery replaceWith issue

I have an iframe to a third party system and which, when called, updates a database record and then displays a confirmation message. I'd like to change the text of the confirmation using jQuery, but cannot seem to get it working. This is the code I have so far. The call to the third party system works but the replacement text doesn't appear. Any pointers, please? Thank you.
<script type="text/javascript">
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return ''; }
return results[1] || '';
}
var lidval = $.urlParam('lid');
var cidval = $.urlParam('cid');
var cyidval = $.urlParam('cyid');
//construct url
var crmurl ='http://somerandomhost.com/Portal/index.php?task=unsusbscribe&lid='+lidval+'&cid='+cidval+'&cyid='+cyidval;
jQuery(function($){
$('#crm').attr('src', crmurl);
});
</script>
<iframe frameborder="0" id="crm" scrolling="no" width="100%" src=""></iframe>
<script type="text/javascript">
function($){
$('crm').replaceWith('Replacement text goes here');
};
</script>
if you want to show the string into the irframe try this:
PURE JS:
var doc = document.getElementById('crm').contentDocument;
doc.body.innerHTML = 'Replacement text goes here';
jQuery:
var doc = $('#crm')[0].contentDocument;
$(doc.body).html('Replacement text goes here')
To change content of an iframe you can Try below code
var ifr = $('#crm')[0].contentWindow.document,
ifbody = $('body',ifr);
ifbody.html('Replacement text goes here');

How to extract all hyperlink titles from big html string using javascript?

I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>
It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));
To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle

Categories