Only 1 result from JSON array - javascript

In my getValueByKey function, I want to output 5 different items and their attributes, but my for loop only seems to allow me to choose one at a time.
When I change to i = 4 it will go to the 5th item. I just want to output all instead of choosing just one.
Any help is appreciated. Thank you very much.
window.onload = function() {
var getJSON = function (url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.setRequestHeader("X-Algolia-Application-Id", apiApplicationId);
xhr.setRequestHeader("X-Algolia-API-Key", apiKey);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
var search = document.getElementById('search');
search.addEventListener('keyup', function() {
getJSON(apiEndpoint, function(data) {
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
document.getElementById('item-wrapper').innerHTML =
'<div class="col-sm-4">' +
'<img src="path/to-image.jpg">' +
'</div>' +
'<div class="col-sm-8">' +
'<ul>' +
'<li><strong>Bag Brand:</strong> <span id="search-results-brand"></span></li>' +
'<li><strong>Bag ID:</strong> <span id="search-results-id"></span></li>' +
'<li><strong>Bag Color:</strong> <span id="search-results-color"></span></li>' +
'<li><strong>Bag Description:</strong> <span id="search-results-description"></span></li>' +
'<li><strong>Bag Material:</strong> <span id="search-results-material"></span></li>' +
'<li><strong>Bag Price:</strong> $<span id="search-results-price"></span></li>' +
'</ul>' +
'</div>';
output_id = getValueByKey('id', data.hits);
output_brand = getValueByKey('brand', data.hits);
output_color = getValueByKey('color', data.hits);
output_description = getValueByKey('description', data.hits);
output_material = getValueByKey('material', data.hits);
output_price = getValueByKey('price', data.hits);
document.getElementById("search-results-brand").innerHTML = output_brand;
document.getElementById("search-results-id").innerHTML = output_id;
document.getElementById("search-results-color").innerHTML = output_color;
document.getElementById("search-results-description").innerHTML = output_description;
document.getElementById("search-results-material").innerHTML = output_material;
document.getElementById("search-results-price").innerHTML = output_price;
}, function(status) {
alert('Something went wrong.');
});
});
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/common.css">
<script type="application/ecmascript" src="js/common.js"></script>
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Test</h1>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-sm-12">
<input placeholder="search bags" id="search">
</div>
</div>
</div>
<div class="container">
<div class="row item-row" id="item-wrapper"></div>
</div>
</body>
</html>

You are return data[i][key]; . Do not return untill loop finishes.
function getValueByKey(key, data) {
var i, len = data.length;
var result =[];
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
result.push(data[i][key]);
}
}
return result;
}
Edit for your question in the comment
As per my understanding your question, you can try something like this.I did not test this code. Let me know if there are any errors.
var items;
for(var i=0; i<output_id.length; i++){
items +='<div class="col-sm-4">' +
'<img src="path/to-image.jpg">' +
'</div>' +
'<div class="col-sm-8">' +
'<ul>' +
'<li><strong>Bag Brand:</strong>'+output_brand[i]+'<span id="search-results-brand"></span></li>' +
'<li><strong>Bag ID:</strong>'+output_id[i]+' <span id="search-results-id"></span></li>' +
'<li><strong>Bag Color:</strong>'+output_color[i]+' <span id="search-results-color"></span></li>' +
'<li><strong>Bag Description:</strong>'+output_description[i]+' <span id="search-results-description"></span></li>' +
'<li><strong>Bag Material:</strong>'+output_material[i]+' <span id="search-results-material"></span></li>' +
'<li><strong>Bag Price:</strong> '+output_price[i]+'$<span id="search-results-price"></span></li>' +
'</ul>' +
'</div>';
}
document.getElementById('item-wrapper').innerHTML =items;

Related

TypeError when parsing Blogger API response: Cannot read property 'url' of undefined

I'm parsing JSON feed from the blogger API but its throwing following error:
37:59 Uncaught TypeError: Cannot read property 'url' of undefined
Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.
Javascript Code:
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/');
var postTimestamp = json.feed.entry[i].published.$t;
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= '+ postTimestamp +'>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
//document.write(item);
document.getElementById("news").appendChild(item);
console.log(item);
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
<div id="news"></div>
JsFiddle: https://jsfiddle.net/645pg9rz/
If you run console.log(json.feed.entry) in your fiddle, you'll see that there is no key called media$thumbnail in the returned objects. That is why your code is failing at var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/'); - it is trying to access the url property of an item that doesn't exist.
Perhaps the API used to use that key and no longer does, or there are just no thumbnails available in the entries you requested. I don't see a new key with an image file other than the Blogger logo.
Updated: the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)
there are no pictures in the object that came to you. It's the only icon that comes. I put them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="row" id="news"></div>
<script>
function mycallback(json) {
console.log(json)
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, 400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].author[0].gd$image.src;
var postTimestamp = json.feed.entry[i].published.$t;
console.log(postImage)
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= ' + postTimestamp + '>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
document.getElementById("news").innerHTML += item;
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
</body>
</html>

How can i call javaScript function in iOS Swift

i am trying to get html string from a web view. i try to get html string from web view like,
let html = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
print(html)
in this code i get all Html code without the input value what i given after web loading.
on the other hand there is function which that will give me full html code with input value. but i was unable to call javascript function in my swift code.also my javaScript function have a parameter which one i want to call.
i was try to call javaSript function like this,
let pp = webView.stringByEvaluatingJavaScript(from:"draft")
But its not working. i want to get all of html including input value.
Here is a Screenshot how it's done in android.
i was attach all of my html code here
<!DOCTYPE html>
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html charset=UTF-8'/>
<link type='text/css' rel='stylesheet' href='file:///android_asset/bootstrap.min.css'>
<script src="file:///android_asset/jquery.min.js"></script>
<title>Quick Inspection</title>
<style>
textarea{
resize: none;
}
</style>
</head>
<body style='background: #fff3d6'>
<div class='container-fluid' style='padding-top: 10px; padding-left: 0px; padding-right: 0px; background: #fff3d6'>
<div class='container'>
<div class='row'>
<form id='rendered-form'>
<div class='rendered-form'>
<div class='fb-textarea form-group field-textarea-1505524302868'>
<label for='textarea-1505524302868' class='fb-textarea-label'>1. Description of Work</label>
<textarea class='form-control textarea' name='textarea-1505524302868' id='textarea-1505524302868'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524384468'>
<label for='textarea-1505524384468' class='fb-textarea-label'>2. Work Status</label>
<textarea class='form-control textarea' name='textarea-1505524384468' id='textarea-1505524384468'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524405168'>
<label for='textarea-1505524405168' class='fb-textarea-label'>3. Progress</label>
<textarea class='form-control textarea' name='textarea-1505524405168' id='textarea-1505524405168'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524418785'>
<label for='textarea-1505524418785' class='fb-textarea-label'>4. Observation</label>
<textarea class='form-control textarea' name='textarea-1505524418785' id='textarea-1505524418785'></textarea>
</div>
<div class='fb-textarea form-group field-textarea-1505524433458'>
<label for='textarea-1505524433458' class='fb-textarea-label'>5. Recommendation</label>
<textarea class='form-control textarea' name='textarea-1505524433458' id='textarea-1505524433458'></textarea>
</div>
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
</div>
<div id="jsonvalue" style="visibility: hidden; display:inline;"></div>
</body>
<script>
var getJsonData = $("#jsonvalue").text();
if(getJsonData != ""){
SetJsonValue();
}
function getHtml()
{
var Alldata = $('form').serializeArray();
var JsonString = JSON.stringify(Alldata);
$("div#jsonvalue").text(JsonString);
var allCode = document.documentElement.outerHTML;
return allCode;
}
function SetJsonValue()
{
var getJsonData = $("#jsonvalue").text();
var obj = $.parseJSON(getJsonData), dataObj = {};
len = obj.length;
for (i = 0; i < len; i++) {
var f_name = obj[i].name;
var f_value = obj[i].value;
var result = f_name.split('-');
var type = result[0];
if (type == 'textarea') {
$("#rendered-form " + type + "[name = " + f_name + "]").text(f_value);
} else if (type == 'text') {
$("input[name = " + f_name + "]").val(f_value);
} else if (type == 'radio') {
$('#rendered-form input[name=' + f_name + '][value=' + f_value + ']').prop("checked", true);
} else if (type == 'select') {
$("#rendered-form " + type + "[name = " + f_name + "]").val(f_value);
} else {
$(":checkbox[value=" + f_value + "]").prop("checked","true");
}
}
}
function draft(){
var getAllHtmlCode = getHtml();
Android.fullCode(getAllHtmlCode);
}
function finalsave(){
var obj = $('form').serializeArray();
len = obj.length;
//$( ".fb-radio-group").hide();
for (i = 0; i < len; i++) {
var f_name = obj[i].name;
var f_value = obj[i].value;
var result = f_name.split('-');
var type = result[0];
if (type == 'textarea') {
//if( f_value == "") {
// $( ".field-textarea-"+result[1]).hide();
//}else{
var bodyText = f_value;
var body = $("<div class='ans'> </div>");
body.text(bodyText);
$("#rendered-form " + type + "[name = " + f_name + "]").replaceWith(body);
//}
} else if (type == 'text') {
//if( f_value == "") {
// $( ".field-text-"+result[1]).hide();
//}else{
var bodyText = f_value;
var body = $("<div class='ans'> </div>");
body.text(bodyText);
$("input[name = " + f_name + "]").replaceWith(body);
//}
} else if (type == 'radio') {
//$(".l_header").hide();
//$(".field-radio-group-"+result[2]).prev().show();
//$(".field-radio-group-"+result[2]).show();
var r_value = $('#rendered-form input[name=' + f_name + ']:checked').val();
$('#rendered-form input[name=' + f_name + ']').parent().hide();
$("label[for='"+f_name+"']").append('<div class="ans">'+r_value+'</div>');
} else if (type == 'select') {
if( f_value == "" || f_value == "0") {
//$( ".field-select-"+result[1]).hide();
}else{
var lbl = $("#rendered-form " + type + "[name = " + f_name + "]").find('option:selected').text();
var body = $("<div class='ans'> </div>");
body.text(lbl);
$("#rendered-form " + type + "[name = " + f_name + "]").replaceWith(body);
}
} else {
$(":checkbox[value=" + f_value + "]").prop("checked","true");
}
}
var allCode = document.getElementById("rendered-form").outerHTML;
Android.finalCode(allCode);
}
</script>
</html>

jQuery Button only works once cannot change fahrenheit to celsius [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
<!DOCTYPE html>
<html>
<head>
<title>Local Weather</title>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.10/css/weather-icons-wind.css">
<link rel="stylesheet" type="text/css" href="Local Weather.css">
</head>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
</html>
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function()
{
$.getJSON("https://freegeoip.net/json/", function(data)
{
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
$.getJSON(url, function(data2)
{
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src='+ data2.weather[0].icon + '/>');
btn = $("#corf");
btn.click(function ()
{
if(test)
{
temp = (temp * 1.8) + 32;
$("#degree").html(temp + '<button id="corf">℉</button>');
test = false;
}
else
{
temp = (temp * 0.5556) - 32;
$("#degree").html(temp + '<button id="corf">℃</button>');
test = true;
}
});
});
});
});
Cannot change Celsius to Fahrenheit multiple times, what's wrong?
You are trying to bind the click event to the element which doesn't exists in the DOM. To make sure your events binding is proper you can use Event Delegation. Just add event to the parent element and check for the event.target. If event.target is the button, the do the proper calculation.
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function() {
$.getJSON("https://freegeoip.net/json/", function(data) {
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude;
$.getJSON(url, function(data2) {
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src=' + data2.weather[0].icon + '/>');
$('#degree').click(function(e) {
if (e.target.id === 'corf') {
var newTemp = 0;
if (test) {
newTemp = (temp * 1.8) + 32;
$("#degree").html(newTemp + '<button id="corf">℉</button>');
test = false;
} else {
newTemp = temp;
$("#degree").html(newTemp + '<button id="corf">℃</button>');
test = true;
}
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
Try this:
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function()
{
$.getJSON("https://freegeoip.net/json/", function(data)
{
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
$.getJSON(url, function(data2)
{
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src='+ data2.weather[0].icon + '/>');
btn = $("#corf");
$(document).on('click',btn,function ()
{
if(test)
{
temp = (temp * 1.8) + 32;
$("#degree").html(temp + '<button id="corf">℉</button>');
test = false;
}
else
{
temp = (temp - 32) / 1.8;
$("#degree").html(temp + '<button id="corf">℃</button>');
test = true;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>

Weird JS Behavior With Bootstrap Sliders

So I recieved help from an internet saint to vastly improve my code to create a bootstrap slider per list item within a JS for loop, but now it is behaving erratically.
Sometimes it works perfectly, others it creates new items but not sliders (just a text input field), and others it only creates one item per list.
Any great minds see where I'm going wrong?
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
var conArray = [];
function addCon() {
var valCon = document.getElementById("conInput").value.trim();
document.getElementById("conForm").reset();
if (valCon.length == 0) {
return;
}
if (document.getElementById('conInput' + valCon) == null) {
conArray.push({id: valCon, slider: null});
} else {
return;
}
for (var i = 0; i < conArray.length; i++) {
var ele = document.getElementById('conInput' + conArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("conList").innerHTML += newItem;
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var valCon = conArray[i].slider.getValue();
conArray[i].slider.destroy();
document.getElementById('SIDconInput' + conArray[i].id).remove();
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
conArray[i].slider.setValue(valCon);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div> <!-- cons -->
Because you have two lists you can use two arrays:
var proArray = [];
var conArray = [];
The inline functions can be changed in order to pass the list prefix as parameter:
newAdd('pro')
newAdd('con')
And so you can adjust the addPro function to these changes.
From comment:
If I type in "#" or "?" as an item in your snippet above it shows the error. Not for you?
In order to solve such an issue you need to escape those chars when creating the slider:
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').....
The snippet:
var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
var val = document.getElementById(listIdPrefix + "Input").value.trim();
document.getElementById(listIdPrefix + "Form").reset();
if (val.length == 0) {
return;
}
var arr;
if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
if (listIdPrefix == 'pro') {
proArray.push({id: val, slider: null});
arr = proArray;
} else {
conArray.push({id: val, slider: null});
arr = conArray;
}
} else {
return;
}
for (var i = 0; i < arr.length; i++) {
var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
if (ele == null) {
var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById(listIdPrefix + "List").innerHTML += newItem;
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
} else {
(function (i, arr) {
setTimeout(function () {
var val = arr[i].slider.getValue();
arr[i].slider.destroy();
document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
arr[i].slider.setValue(val);
}, 100);
})(i, arr);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div>

http://www.engadget.com/rss.xml is not responding to my XMLHttpRequest. No error code in console

I am trying to do a RSS reader chrome extension based on an example from lifehacker (http://lifehacker.com/5857721/how-to-build-a-chrome-extension). I did my own based on that. It didn't work. I tried their source code and it worked perfectly fine(for lifehacker), but when I changed the xml source as http://www.engadget.com/rss.xml it only showed an empty square.If anyone can point any mistake or error, I would be truly thankful.My files are :
manifest.json
{
"name": "RSS Fetcher",
"version": "0.1",
"description": "engadget rss reader.",
"homepage_url": "http://www.engadget.com/",
"background_page": "background.html",
"permissions": [
"<all_urls>",
"http://www.engadget.com/*"
],
"browser_action": {
"default_title": "engadget reader",
"default_popup": "popup.html"
}
}
background.html
<html>
<head>
<script src='scripts/jquery-1.6.1.min.js'></script>
<script src="scripts/parse.js"></script>
<script>
function fetch_feed(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
callback(data);
} else {
callback(null);
}
}
}
// Note that any URL fetched here must be matched by a permission in
// the manifest.json file!
xhr.open('GET', url, true);
xhr.send();
}
function onRequest(request, sender, callback) {
if (request.action == 'fetch_feed') {
fetch_feed(request.url, callback);
}
}
// Wire up the listener.
chrome.extension.onRequest.addListener(onRequest);
</script>
</head>
<body>
</body>
</html>
popup.html
<html>
<head>
<script src='scripts/jquery-1.6.1.min.js'></script>
<script src="scripts/parse.js"></script>
<script>
function fetch_feed() {
chrome.extension.sendRequest({'action' : 'fetch_feed', 'url' : 'http://www.engadget.com/rss.xml'},
function(response) {
display_stories(response);
}
);
}
function display_stories(feed_data) {
var xml_doc = $.parseXML(feed_data);
$xml = $(xml_doc);
var items = $xml.find("item");
$('#popup').html('<img src="images/logo.png" id="logo" onclick="open_item(\'http://engadget.com/\'); window.close();" /><br clear="all" />');
items.each(function(index, element) {
var post = parse_post(element);
var item = '';
var class2 = '';
if (index >= localStorage['unread_count']) {
// // console.log('visited');
item += '<div class="post read">';
}
else {
item += '<div class="post">'
}
item += '<span class="tag">' + post.tag + '</span>\
<a href="' + post.url + '">\
<div id="' + post.id + '" class="item" onclick="open_item(\'' + post.url + '\');">\
<img src="' + post.img + '" width="107" height="60" />\
<h4>' + post.title + '</h4>\
<span class="description">' + post.description + '...</span>\
</div>\
</a>';
item += '</div>';
$('#popup').append(item);
});
}
</script>
<link rel="stylesheet" href="styles/post.css" type="text/css" />
</head>
<body>
<div id="popup">
</div>
<script>
$(document).ready(function() {
fetch_feed();
});
</script>
</body>
</html>
parse.js
function parse_post(element) {
// console.log(element);
var post = new Object();
post.title = $(element).find("title").text();
post.tag = post.title.split('[')[1].split(']')[0];
post.title = post.title.split('[')[0];
post.id = $(element).find("guid").text();
post.url = $(element).find('link').text();
post.description = $("<div/>").html($(element).find("description")).text();
post.img = $('img', post.description)[0].src; //107x60px
var shorten = 120;
if (post.title.length > 80) {
shorten = 70;
}
post.description = $.trim($(post.description).text());
post.description = post.description.substr(0, shorten);
// console.log(post);
return post;
}
function open_item(url) {
chrome.tabs.create({url: url});
chrome.browserAction.setBadgeText({text:''});
}
I also used jquery-1.6.1.min.js
Anything helps:) Thanks in advance!
not sure "all_urls" works in your manifest.json, remove that and give it a try

Categories