Dynamic URL for XMLhttprequest - javascript

I used news API to get news content via json format.
I have html 'input element' which user can select for multiple sources.
what i wanted is if the source is equal to "user selected source or define" then the news content will change according to user selection.
As you can see i don't use jQuery i need to be more comfortable with JS than jQuery for now. so i prefer working with pure JS.
My newsapi: https://newsapi.org
this is my code.
that's working without the user selection functionality.
HTML:
<!--dropDown Category-->
<div class="form-group" id="categorySelector">
<label for="newsCat">Select source:</label>
<select class="form-control" id="newsCat">
<option value="the-next-web">the-next-web</option>
<option value="wired-de">wired-de</option>
<option value="time">time</option>
</select>
</div>
JS code:
var newsRequest,
newsKey = 'XXXXXXXXXXXXXXXXXXX',
newsSource = 'the-next-web'; //defaultSource
//for older broswser
if (window.XMLHttpRequest) {
newsRequest = new XMLHttpRequest();
} else {
newsRequest = new ActiveXObject("Microsoft.XMLHTTP");
} //window.XMLHttpRequest
newsRequest.open("GET", 'https://newsapi.org/v1/articles?source=' + newsSource + '&sortBy=latest&apiKey=' + newsKey);
newsRequest.onreadystatechange = function () {
if ((newsRequest.readyState === 4) && (newsRequest.status === 200)) {
var infoNews = JSON.parse(newsRequest.responseText);
// Action to be performed when the document is read;
var newsHtml = '<ul class="list-group">';
for (var i = 0; i < infoNews.articles.length; i++) {
newsHtml += '<li>';
newsHtml += '<div class="newItem">' + '' + '<img src = "' + infoNews.articles[i].urlToImage + '" alt="' + infoNews.articles[i].title + '" title="' + infoNews.articles[i].title + '">' + '';
newsHtml += '<h3 class="newsTitle">' + infoNews.articles[i].title + '</h3>';
newsHtml += '<p class="newsDes">' + infoNews.articles[i].description + '</p>';
newsHtml += '<p class="newsAuthor">' + infoNews.articles[i].author + '</p>';
newsHtml += '</div>';
newsHtml += '</li>';
} //for loops json
newsHtml += '</ul>';
document.querySelector('.newsParent').innerHTML = newsHtml;
} //newsRequest.readyState
} //newsRequest.readyState
//xmlhtpprequest method open
newsRequest.send();
//i came up with this code..
document.querySelector('#newsCat').onchange = function(selectedSource){
newsSource = selectedSource.value; // by this is still not good because this inside a function
}

Here is an example of onchange callback sent from the select element.
First we want to hook up onchange event to some method, so we add onchange="selectionChanged()" attribute to the <select> tag.
In the method selectionChange we will handle the changes:
Get newsCat element and if it is not null (it can be, before window is loaded) we are getting it's value. Finally we're passing this value to the getNewsFromApi method which actually uses this value, to build api url and get the data from external source.
var newsKey = 'XXXXXXXXXXXXXXXXXXX';
function selectionChanged() {
var categorySelect = document.getElementById('newsCat');
var selectedCategory = categorySelect !== null ? categorySelect.value : 'the-next-web';
getNewsFromApi(selectedCategory);
}
function getNewsFromApi(newsSource) {
var apiUrl = 'https://newsapi.org/v1/articles?source=' + newsSource + '&sortBy=latest&apiKey=' + newsKey;
// here goes your API call
console.log('getting news from: ' + apiUrl);
}
getNewsFromApi('the-next-web');
<div class="form-group" id="categorySelector">
<label for="newsCat">Select source:</label>
<select class="form-control" id="newsCat" onchange="selectionChanged()">
<option value="the-next-web">the-next-web</option>
<option value="wired-de">wired-de</option>
<option value="time">time</option>
</select>
</div>

Related

How to populate a dynamically created select with options

I have used Event binding on dynamically created elements? and Get changed value from <select> using jQuery to get to where I am now.
I am creating two Select dropdowns dynamically ('Activity Type' and 'Activity'). I use the selected item from the first dropdown ('Activity Type') to get a list of options for the second dropdown ('Activity'). How do I populate the second dropdown ('Activity') with the list of options please? Note that each line may have a different initial option selected and therefore a different set of options in the second dropdown.
My code is:
$(document).on('click', '#programDetailTablebody button[name="addPDRow"]', function(e) {
e.preventDefault();
var newRows = "";
newRows += "<tr><td class='button'><button type='button' name='addPDRow' class = 'buttonFront'><span class='glyphicon glyphicon-plus'></span></button></td>";
newRows += "<td class='keyvalue'><input class='timeWidth timeClass pdValue' name='timeInput' value='07:00'></input></td>"; //Time
newRows += "<td class='keyvalue'><select class='form-control activityTypeWidth activityTypeClass pdValue' name='activityTypeInput'>" //Activity Type
newRows += "<option value='' disabled selected>Select Activity Type</option>" + activityTypeOptions + "</select>"
newRows += "<td class='keyvalue'><select class='form-control activityWidth activityClass pdValue' name='activityInput'>" //Activity
newRows += "<option value='' disabled selected>Select Activity</option>" + activityOptions + "</select>"
newRows += "<td class='keyvalue'><input class='equipmentClass pdValue' name='equipmentInput'></input></td>";//Equip. Needed
newRows += "<td class='keyvalue'><input class='awardClass pdValue' name='awardInput'></input></td>";//Award
newRows += "<td class='keyvalue'><input class='leadersClass pdValue' name='leadersInput'></input></td>";//Leaders
newRows += "<td class='button'><button type='button' name='removePDRow' class = 'buttonFront'><span class='glyphicon glyphicon-minus'></span></button></td></tr>";
$(newRows).insertAfter($(this).closest('tr'));
});
$('#programDetailTablebody').on( 'change', "select[name='activityTypeInput']", function (e) {
e.preventDefault();
var activityType = $(this).val();
$.ajax({
url : 'PPATActivityListView', ...
.done (unction(responseJson1a){
// JSON response to populate the activities options
dataType: "json";
var activityOptionsNew = "";
$.each(responseJson1a, function() {
activityOptionsNew += '<option value = ' + this.ppa_id + '>' + this.ppa_activity_name + '</option>';
});
alert("activityOptionsNew: " + activityOptionsNew);
this.activityOptions = activityOptionsNew;
})
});
This is the page:
I am getting the expected list of options for the second dropdown. So how do I then insert the options into the select for the second dropdown?
I have changed to use arrow function; however, I get an error "Syntax error on token ">", invalid FunctionExpressionHeader".
.done((responseJson1a) => {
// JSON response to populate the activities options
dataType: "json";
// alert(JSON.stringify(responseJson1a));
var activityOptionsNew = "";
$.each(responseJson1a, function() {
activityOptionsNew += '<option value = ' + this.ppa_id + '>' + this.ppa_activity_name + '</option>';
});
alert("activityOptionsNew: " + activityOptionsNew);
$(this).closest('tr').find('.activityClass').html(activityOptionsNew);
})
You need to declare this ( current select-box) outside your ajax call and then access your select-box like below :
var selector = $(this); //declare this
$.ajax({
//..
.done (function(responseJson1a){
//other codes
selector.closest('tr').find('.activityClass').html(activityOptionsNew);//add htmls
})
You can change your jQuery ajax.done() to use arrow function, and then just replace .activityClass with activityOptionsNew
.done ((responseJson1a) => {
...
$(this).closest('tr').find('.activityClass').html(activityOptionsNew);
})

How to display data below each other in javascript

Hi guys please direct me how to this I want my result appear below each other please refer to my code below:
function displayData(e)
{
var html = '';
var html2 = '';
$searchcontainer = $('#searchcontainer');
var mapDiv = document.getElementById('mapContainer'), i = 0,
dataIndex, tooltipDiv, key
mapMarkers = $(mapDiv).find('.e-mapMarker'), index = 0;
for (i = 0; i < mapMarkers.length; i++)
{
if (e.target.parentNode.parentNode == mapMarkers[i])
{
index = i;
}
}
html += '<div id="infocontainer">';
html += '<div class="p-image"><img src="src/images/retrofit.png"/></div>';
html += '<div class="popupdetail">';
html += '<div class="p-name"> Site Name: ' + flsSites[index].site_name + '</div>';
html += '<div class="p-name"> Site Status: ' + flsSites[index].status + '</div>';
html += '<div class="p-name"> Country: ' + flsSites[index].country_name + '</div>';
html += '</div>';
html += '</div>';
$searchcontainer = $('#searchcontainer');
if (!$(this).data('rightCont')) {
$(this).data('rightCont', $('<div class="rightcontainer">' +
'<img id="productimage" src="src/images/retrofit.png" onClick="DisplayProfileCard()"/>' +
'<div id="imagedetail">' +
'<span class="details">Product Type' + Sites[index].serial_number + '</span>' +
'<span class="details">Version / Size <img class="row_one_icon lightbulb_icon" id="lightbulb" src="src/images/lightbulb1.png" onClick="LightBulb()" /><img id="convert" class="row_one_icon arrow_icon" src="src/images/arrow_Off.png" onClick="Conversion()"/><img id="lightning" class="row_one_icon" src="src/images/lightningOff.png" onClick="Lightning()"/><img id="bullseye" class="row_one_icon bullseye" src="src/images/bullseye_off.png" onClick="BullsEye()"/></span>' +
'<span class="details">Estimated annual Spend <img class="row_one_icon ribbon" src="src/images/ribbon1.png"/><img class="row_one_icon map" src="src/images/map1.png"/><img class="row_one_icon paper_stack" id="paper" src="src/images/paper_stack_Off.png" onclick="PaperStack()"/><img class="row_one_icon chain" id="chain" src="src/images/chain_Off.png" onClick="ChainLink()"/></span>' +
'<span class="details">Site name / manufacturer</span>' +
'<span class="details">Selling Sales Eng</span>' +
'</div></div>').appendTo($searchcontainer));
}
$searchcontainer.find('.rightcontainer').removeClass('background');
$(this).data('rightCont').addClass('background');
now my code here works like this if I hover over a marker in the map it will display the result to my searchcontainer div but if I hover another item it will display the other result BUT it will overwrite the previous result instead of displaying it below
Many thanks in advance
Your call to $(this).data overwrites the contents of rightCont each time it is executed. Read more on the JQuery API. The .appendTo(...) call should be sufficient.
That being said, using string manipulation to create HTML code is stylistically terrible. Look at something like Vue.js, Handlebars, Angular, React, or just any other frontend MVC framework- they are tools designed for easily binding Javascript data to HTML, rather than manually inserting it using string manipulation.

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

For loop to change value of dropdown menu in jQuery

I currently have a drop down menu that lists all the years from 1970 to present. At the moment this is in some embedded JavaScript within the HTML. I'm trying to use an external file to perform the same function with jQuery, but I'm having difficulty.
This is the current method to display the drop down menu:
<h4 class="form_title">Time Span</h4></br>
<label for="select" class="col-lg-2 control-label">From:</label>
<div class="col-lg-3">
<select class="form-control" name="timeStart" id="select">
<option value="" selected disabled>Select</option>
<script type="text/javascript">
// get current year and then use loop to populate options
var year = new Date().getFullYear();
for(i = year; i >= 1970; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
};
</script>
</select>
</div> <!-- col-lg-3 -->
This works fine but I want to separate the logic from the view. I have tried removing the script entirely from this file and then adding the following in my JavaScript file like so:
var year = new Date().getFullYear();
$("#select").change(function() {
console.log("Calling function successfully...");
for(i = year; i >= 1970; i--) {
document.write('<option value="' + i + '">' + i + '</option>');
}
});
I put the console.log in there to see if the function is even being called when I select the menu (which it isn't). I have been trying many variations on this but can't figure out what I'm doing wrong (probably several things). Should I be selecting the select tag or the option tag?
Move your code into ready and use append to add option to the select.
var year = new Date().getFullYear();
$(document).ready(function () {
console.log("Calling function successfully...");
var options = '';
for (i = year; i >= 1970; i--) {
options += '<option value="' + i + '">' + i + '</option>';
}
$('#select').append(options);
});
You need to append the options you want to render as children to the select element:
$(document).ready(function() {
console.log("Calling function successfully...");
var options = ''
for(i = year; i >= 1970; i--) {
options += '<option value="' + i + '">' + i + '</option>';
}
$("#select").append(options);
});
Since you're using JQuery, you'll need to make sure to wrap your code in $(document).ready(function() {});
If you don't, it'll just try and run immediately on load. Wrapping it in that will ensure that the select box is rendered before trying to run your code.
You can see an example of how this works here.
http://jsbin.com/rebahiwupi/1/edit
$(document).ready(function() {
var sel = $('select');
var start_year = 1970;
for(var i=start_year;i<=new Date().getFullYear();i++) {
sel.append('<option value="'+i+'">'+i+'</option>');
}
});
Another version that uses while loop.
var year = new Date().getFullYear(), $options = $();
while (year >= 1970) {
var option = year--;
$options = $options.add($('<option/>', { 'value': option, 'text': option }));
}
$('#select').append($options);

Dropdown list returning selected value Empty

I use to populate Dropdown using javascript:
function populateDDL(ddl_id) {
var option_str = "";
var x;
for(x in datalist){
option_str += " <asp:ListItem Value='" + datalist[x] + "' Text='" + datalist[x] + "'></asp:ListItem>"
}
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}
This is sure the datalist is not empty and also Dropdown list populated perfectly..but dnt know why after clicking on my page add button I am not getting the selected value.
Thanks
You should use client side select list control rather than server control to whome you are trying to fill at client side. Its surprised ...
But you should use select control
function populateDDL(ddl_id) {
var option_str = "<select id='ddl_id'>";
var x;
for(x in datalist){
option_str += " <option value='" + datalist[x] + "'>" + datalist[x] + "</option>";
}
option_str += "</select>";
var country_div = document.getElementById(ddl_id);
country_div.innerHTML = option_str;
}

Categories

Resources