While building a weather app I faced a problem. It has to automatically detect where we based and provide with appropriate temperature and location e.g city name. I'm trying to replace p with a data from JSON. In particular I'm trying to replace paragraph with a city name. For some reason it doesn't work.
http://codepen.io/ekilja01/full/KaMXjp/
Here is my HTML:
<body>
<div class="container-fluid">
<i class="fa fa-thermometer-empty fa-2x" aria-hidden="true"></i>
<br><br><br>
<form>
<input type="radio" name="celsiusOrFahrenheit" value="fahrenheit"> Fahrenheit °F;<br>
<input type="radio" name="celsiusOrFahrenheit" value="celsius" checked> Celsius °C<br>
</form>
<div class="yourlocation">
<h1>Your location is: </h1>
<p class="yourLocationGoesHere">
</p>
</div>
<h1>Your current weather is: </h1>
<div class="showTemperature">
<p class="showDegree">32</p>
</div>
</div>
</body>
Here is my jQuery:
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather? q=London,uk&appid=7f5806c8f3fd28b03e2d6580a50732d6", function (data){
var len = data.length;
var html = "";
html += "<p>'" + len.name + "'</p>";
$(".yourLocationGoesHere").html(html);
});
});
Here is my JSON:
{"coord":
{"lon":145.77,"lat":-16.92},
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],
"base":"cmc stations",
"main":{"temp":293.25,"pressure":1019,"humidity":83,"temp_min":289.82,"temp_max":295.37},
"wind":{"speed":5.1,"deg":150},
"clouds":{"all":75},
"rain":{"3h":3},
"dt":1435658272,
"sys":{"type":1,"id":8166,"message":0.0166,"country":"AU","sunrise":1435610796,"sunset":1435650870},
"id":2172797,
"name":"Cairns",
"cod":200}
Please help.
data is refering to your json document, so it should be:
html += "<p>'" + data.name + "'</p>";
The len variable just holds the length ;)
You were trying to get the city name of the length of the JSON which is wrong. Simply do :
data.name
Here's working solution. Hope it helps!
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather? q=London,uk&appid=7f5806c8f3fd28b03e2d6580a50732d6", function (data){
var len = data.length;
var html = "";
html += "<p>'" + data.name + "'</p>";
$(".yourLocationGoesHere").html(html);
});
});
Related
enter image description herethis is simple text boxes i give the value and add them ![enter image description here][2]
when I add more text boxes with append query now the sum is not calculating
[enter image description here][3]
THis is jquery code of iam apending two divs with Two ids and text boxes are also have there ids
Use jquery features for implement complex thing in a very easier way...
It provides Huge Library with number of functions and Flexibility for executing your code in cross browsers
HTML
<div class="row">
<button type="button" class="btn btn-success add-more">ADD MORE</button>
</div>
<div class="form-group" id="ele">
<div class="row" id="item1">
<div class="row">
<input type="number" class="num1">
<label>+</label>
<input type="number" class="num2">
<label>SUM</label>
<input type="number" class="sum" readonly="true">
<button type="button" class="btn btn-success remove">x</button>
</div>
</div>
</div>
JQUERY Script
var item = $('#item1').html();
var cnt = 0;
$('.add-more').click(function() {
cnt++;
$('#ele').append("<div class='row' id='item" + cnt + "'>" + item + "</div>");
});
$(document).on('click', '.remove', function() {
$(this).closest('.row').remove();
});
$(document).on('keyup', '.num1,.num2', function() {
if ($(this).hasClass('num1')) {
var num1 = parseInt($(this).val());
var num2 = parseInt($(this).siblings('.num2').val());
$(this).siblings('.sum').val(num1 + num2);
} else if ($(this).hasClass('num2')) {
var num2 = parseInt($(this).val());
var num1 = parseInt($(this).siblings('.num1').val());
$(this).siblings('.sum').val(num1 + num2);
}
});
Check Demo Here
I am trying to submit a search request to the Wikipedia API using a form that is fulled out by the user. When the form is submitted, however, the page refreshes and nothing is done. I have tried to "preventDefault", and that did not get the job done. I will post my html and javascript code below (if my css is somehow helpful, I can of course supply that as well).
HTML:
<body>
<div class="random text-center">
<a target="_blank" href ="http://en.wikipedia.org/wiki/Special:Random">Get a Random Entry</a>
</div>
<br/>
<div class="text-center">
<form>
<input type="text" placeholder="search" id="search">
<input type="submit">
</form>
</div>
<div class="results">
</div>
</body>
Javascript:
$(document).ready(function(){
$('#search').submit(search());
function search(){
var value = ("#search").val();
//var value = "eggs";
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + value + "&utf8=&format=json&callback=?", function(json) {
json.query.search.forEach( function(val) {
var title = val.title;
var snippet = val.snippet;
titleURL = title.replace(/ /g, "_");
$(".results").append("<a target='_blank' href='https://en.wikipedia.org/wiki/" + titleURL +"'><div class='result'><div class='title'>" + title + "</div><br/><div class='snippet'>" + snippet + "</div></div></a><br/>")
});
var title = json.query.search[0].title;
var snippet = json.query.search[0].snippet;
});
};
});
codepen:
http://codepen.io/blarmon/pen/rrZzyB
I am using Javascript to get the credit card information from Magentic Strip Reader device. (I am using USB attached device)
I have written a code in HTML Javascript but it failed to run. I mean my page is on HTTPS when I connected the device after opening this page. The device lights turns to green which means this page is security proof.
But when I swipe the card it did not show nothing in the field. I also have a function to focus on the field. But I don't know whats wrong it, Please see my code below and give me any suggestions.
HTML:
<span style='required'>*</span> - Indicates required field.
<div class='fields'>Swiped Information</div>
<input type=text name='swiped' id='swiped'>
<div class='fields'>First Name</div>
<input type=text name='first_name' id='first_name'><span style='required'>*</span>
</div>
<div class='fields'>Last Name</div>
<input type=text name='last_name' id='last_name'><span style='required'>*</span>
</div>
<div class='fields'>Expiration</div>
<input type=text size=8 name='expiration' id='expiration'><span style='required'>*</span>(MMYY)
</div>
<div class='fields'>CVV Code</div>
<input type=text size=8 name='cvv' id='cvv'><span style='required'>*</span>
</div>
<div class='fields'>Credit Card Number</div>
<input type=text name='card' id='card'><span style='required'>*</span>
</div>
<hr>
<div class='buttons'></div>
<a onclick="readCard();" style="cursor:pointer; color:red;">Swipe Credit Card</a>
</div>
Javascript code:
<script type="text/javascript">
function readCard () {
document.getElementById('swiped').focus();
var card_data = document.getElementById('swiped').value;
if(card_data != ''){
var details1 = card_data.split("^");
var card_number = details1[0];
card_number = card_number.substring(2);
var names = details1[1].split("/");
var first_name = names[1];
var last_name = names[0];
var details2 = details1[2].split(";");
details2 = details2[1].split("=");
var exp_date = details2[1];
exp_date = exp_date.substring(0, exp_date.length - 1);
exp_date = exp_date.substring(2, 3) + "/" + exp_date.substring(0,2);
document.getElementById('card').value = card_number;
document.getElementById('first_name').value = first_name;
document.getElementById('last_name').value = last_name;
document.getElementById('expiration').value = exp_date;
}
}
</script>
If the swiper model is IDMB, then it is not encrypted but may be set to HID and not KBE (keyboard emulated). Are you able to swipe into a text editor, notepad? If not, you may be able to switch it from HID to KBE with MagTek's demo application.
http://www.magtek.com/support/software/demo_programs/usb_swipe_insert.asp
I'm working on a small, temporary site that will be used for collecting some names.
The idea is that people fill in the number of their class and their name and once they press a button, these two values are added to the page and can be viewed by everyone who visits the site.
I've already made a concept of this using javascript: www.googledrive.com/host/0B_eZKT0Ni3-tOXF5OVVQeWZRRjQ
The only problem is that the items aren't really stored on the site. As far as I know, you can only accomplish this using a database, but I have no experience with linking a database to a webpage.
Can someone help me with this or does someone know a source where I can find a solution for this? My searches turned up nothing.
I'm sorry if I'm sounding like a "help vampire". I only turned to you guys for a solution because I can't find it anywhere else.
HTML:
<body>
<div id="wrapper">
<div id="header">
<h2 id="title">Italiëreis 2015: opdiening tijdens quiz</h2>
</div>
<div id="content">
<!-- eerste ploeg -->
<div class="L">
<p id="kop">Ploeg 1</p>
<p class="klas"><input type="text" id="klas1" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam1" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText1()" value="Schrijf in" class="button" />
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst1"></ol>
</div>
</div>
<!-- tweede ploeg -->
<div class="L">
<p id="kop">Ploeg 2</p>
<p class="klas"><input type="text" id="klas2" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam2" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText2()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst2"></ol>
</div>
</div>
<!-- derde ploeg -->
<div class="L">
<p id="kop">Ploeg 3</p>
<p class="klas"><input type="text" id="klas3" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam3" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText3()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst3"></ol>
</div>
</div>
<!-- vierde ploeg -->
<div class="L">
<p id="kop">Ploeg 4</p>
<p class="klas"><input type="text" id="klas4" class="text" maxlength="2" placeholder="Klas"/></p>
<p class="naam"><input type="text" id="naam4" class="text" placeholder="Naam"/></p>
<input type="button" onclick="changeText4()" value="Schrijf in" class="button"/>
<br>
<p>Reeds ingeschreven mensen:</p>
<div class="overflow">
<ol id="lijst4"></ol>
</div>
</div>
</div>
<div id="footer">
<div id="credits">Code geschreven door Bert-Jan van Dronkelaar - 6E</div>
</div>
</div>
CSS is irrelevant.
Javascript:
//eerste ploeg
function changeText1() {
var klas1 = document.getElementById('klas1').value;
var naam1 = document.getElementById('naam1').value;
if (document.getElementById('klas1').value != "" && document.getElementById('naam1').value != "") {
var node = document.createElement("LI");
var textnode1 = document.createTextNode(klas1 + " " + naam1);
node.appendChild(textnode1);
document.getElementById("lijst1").appendChild(node);
}
}
//tweede ploeg
function changeText2() {
var klas2 = document.getElementById('klas2').value;
var naam2 = document.getElementById('naam2').value;
if (document.getElementById('klas2').value != "" && document.getElementById('naam2').value != "") {
var node = document.createElement("LI");
var textnode2 = document.createTextNode(klas2 + " " + naam2);
node.appendChild(textnode2);
document.getElementById("lijst2").appendChild(node);
}
}
//derde ploeg
function changeText3() {
var klas3 = document.getElementById('klas3').value;
var naam3 = document.getElementById('naam3').value;
if (document.getElementById('klas3').value != "" && document.getElementById('naam3').value != "") {
var node = document.createElement("LI");
var textnode3 = document.createTextNode(klas3 + " " + naam3);
node.appendChild(textnode3);
document.getElementById("lijst3").appendChild(node);
}
}
//vierde ploeg
function changeText4() {
var klas4 = document.getElementById('klas4').value;
var naam4 = document.getElementById('naam4').value;
if (document.getElementById('klas4').value != "" && document.getElementById('naam4').value != "") {
var node = document.createElement("LI");
var textnode4 = document.createTextNode(klas4 + " " + naam4);
node.appendChild(textnode4);
document.getElementById("lijst4").appendChild(node);
}
}
#SpencerWieczorek is not wrong, PHP and MySql will work for what you need. However, there is a bit of a learning curve there.
For a beginner, I'd recommend using Parse. It's free and it makes saving and retrieving data trivial. Below is simple app that lets the user input a class year and their name and saves them so others can see them on the same page.
The snippet here wont work due to SO restrictions...
...but here is a working jsfiddle
This is accomplished with plain ole javascript BTW
To get this going on your own you'll need to:
You'll need to go to https://www.parse.com/#signup and create an account with them
Go to https://www.parse.com/apps/new and create an app
add this in your html's head tag <script type="text/javascript" src="https://www.parsecdn.com/js/parse-1.3.0.min.js"></script>
Go to https://www.parse.com/apps/quickstart#parse_data/web/new, select your app from the dropdow (top-ish right) the Parse.initialize() function will be shown here with your app's Application ID and JavaScript key, copy this line for later
Replace the Parse.initialize() function in my example with the one you copied in step 4
Read up on the their javascript guide here to see what all you can do with parse
for a more indepth look, check out the Parse JavaScript SDK & Cloud Code Reference
You can also interact with parse with other scripting languages if you'd like.
Parse is free up to a certain amount of usage. I have one app that's used daily by 100+ users and doesn't come anywhere near having to pay anything.
Parse.initialize("Application ID", "JavaScript key");
function saveInput(){
//get our new values
var klassYear = document.getElementById('klassYear').value.trim();
var studentName = document.getElementById('studentName').value.trim();
// dont continue if either value is blank
if(klassYear=="" ||studentName=="" ){
alert ('Please fill in both fields.') ;
return;
}
// create the `Parse` object
var Klass = Parse.Object.extend("Klass");
var _klass = new Klass();
// set the object's values to our input values
_klass.set("klassYear", klassYear);
_klass.set("studentName", studentName);
// save the object
_klass.save(null, {
success: function(_klass) {
// if the save succeeded, add the new info to our page
retrieveSavedInputs()
},
error: function(_klass, error) {
// save failed, do error handeling here
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}
function retrieveSavedInputs(){
// create a query to search for our `Klass` items
var Klass = Parse.Object.extend("Klass");
var query = new Parse.Query(Klass);
query.find({
success: function(results) {
// get our table's `tbody` and clear it
var myTbl = document.getElementById('mytbl');
myTbl.innerHTML='';
// `results` is an array of all the matches
// loop through each
for(var i =0; i < results.length; i++){
// get the values from the saved object
// note that `klassYear` and `studentName`
// are not available within the scope of the `success` function
var k = results[i].get("klassYear")
var s = results[i].get("studentName")
// create a table row with the info and add it at the top of `contents`
myTbl.innerHTML = '<tr><td>'+k+'</td><td>'+s+'</td></tr>' + myTbl.innerHTML;
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
// load all previously saved items
window.onload = retrieveSavedInputs();
//clcik handeler for the btn
document.getElementById("myBtn").addEventListener('click', saveInput , false);
table{
margin-top:50px;
}
Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table> Class Year: <input type="text" id="klassYear" value=""/> <br>
Name: <input type="text" id="studentName" value=""/> <br>
<input type="button" id="myBtn" value="Submit" class="button" />
<br> Add a ame and year above and see it added to the list below
<div id="myDiv"></div>
<table width="400" border="1">
<thead>
<tr>
<th scope="col">Class Year</th>
<th scope="col">Student Name</th>
</tr>
</thead>
<tbody id="mytbl">
</tbody>
</table>
I have two div called "answerdiv 1" & "answerdiv 2" in html.
now i want to give/create div id uniquely like "answerdiv 3" "answerdiv 4" "answerdiv 5" and so on.
Using javascript/jquery how can i append stuff in these dynamically created divs which id should be unique?
in my project user can add "n" numbers of div, there is no strict limit to it.
Help me out.
Thanks in Adv
================================================================================
My HTML code is:
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
My JS code:
function exchangeLabelsanswertxt(element)
{
var result = $(element).val();
if(result!="")
{
$(element).remove();
$("#answertextdiv").append("<label id='answertext' onClick='exchangeFieldanswertxt(this);'>"+result+"</label>");
}
}
function exchangeFieldanswertxt(element)
{
var result = element.innerHTML;
$(element).remove();
$("#answertextdiv").append("<textarea id='answertext' name='answertext' placeholder='Type answer here' rows='2' cols='40' tabindex='6' onBlur='exchangeLabelsanswertxt(this);'>"+result+"</textarea>");
}
Now from above code I want to append all stuff in unique "answertextdiv" id.
If your divs are in a container like:
<div id="container">
<div id="answerdiv 1"></div>
<div id="answerdiv 2"></div>
</div>
you could do something like:
//Call this whenever you need a new answerdiv added
var $container = $("container");
$container.append('<div id="answerdiv ' + $container.children().length + 1 + '"></div>');
If possible, try not to use global variables...they'll eventually come back to bite you and you don't really need a global variable in this case.
You can try something like this to create divs with unique ids.
HTML
<input type="button" value="Insert Div" onClick="insertDiv()" />
<div class="container">
<div id="answerdiv-1">This is div with id 1</div>
<div id="answerdiv-2">This is div with id 2</div>
</div>
JavaScript
var i=2;
function insertDiv(){
for(i;i<10;i++)
{
var d_id = i+1;
$( "<div id='answerdiv-"+d_id+"'>This is div with id "+d_id+"</div>" ).insertAfter( "#answerdiv-"+i );
}
}
Here is the DEMO
You should keep a "global" variable in Javascript, with the number of divs created, and each time you create divs you will increment that.
Example code:
<script type="text/javascript">
var divCount = 0;
function addDiv(parentElement, numberOfDivs) {
for(var i = 0; i < numberOfDivs; i++) {
var d = document.createElement("div");
d.setAttribute("id", "answerdiv"+divCount);
parentElement.appendChild(d);
divCount++;
}
}
</script>
And please keep in mind that jQuery is not necessary to do a lot of things in Javascript. It is just a library to help you "write less and do more".
I used below JQuery code for the same
$("#qnty1").on("input",function(e)
{
var qnt = $(this).val();
for (var i = 0; i < qnt; i++) {
var html = $('<div class="col-lg-6 p0 aemail1"style="margin-bottom:15px;"><input type="text" onkeyup= anyfun(this) class="" name="email1'+i+'" id="mail'+i+'" > </div><div id=" mail'+i+'" class="lft-pa img'+i+' mail'+i+'" > <img class="" src="img/btn.jpg" alt="Logo" > </div> <div id="emailer1'+i+'" class=" mailid "></div>');
var $html=$(html);
$html.attr('name', 'email'+i);
$('.email1').append($html);
}
}
my HTML contain text box like below.
<input type="text" name="qnty1" id="qnty1" class="" >
and
<div class="email1">
</div>
you need a global counter (more generally: a unique id generator) to produce the ids, either explicitly or implicitly (the latter eg. by selecting the last of the generated divs, identified by a class or their id prefix).
then try
var newdiv = null; // replace by div-generating code
$(newdiv).attr('id', 'answerdiv' + global_counter++);
$("#parent").append(newdiv); // or wherever
var newdivcount=0;
function insertDivs(){
newdivcount=newdivcount+1;
var id="answerdiv-"+(newdivcount);
var div=document.createElement("DIV");
div.setAttribute("ID",id);
var input=document.createElement("TEXTAREA");
div.appendChild(input);
document.getElementById('container').appendChild(input);
}
<button onclick="insertDivs">InsertDivs</button>
<br>
<div id="container">
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
</div>
Here is the another way you can try
// you can use dynamic Content
var dynamicContent = "Div NO ";
// no of div you want
var noOfdiv = 20;
for(var i = 1; i<=noOfdiv; i++){
$('.parent').append("<div class='newdiv"+i+"'>"+dynamicContent+i+"</div>" )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
</div>