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
Related
I'm using the Unsplash API in order to input some keywords and then retrieve photos related to those keywords. In order to do that, I'm using the following Javascript:
var APIKey = '{mykey}';
$.getJSON('https://api.unsplash.com/search/photos?query=' + search + '&per_page=19&client_id=' + APIKey, function (data) {
console.log(data);
var imageList = data.results;
$.each(imageList, function (i, val) {
var image = val;
var imageURL = val.urls.regular;
var imageWidth = val.width;
var imageHeight = val.height;
if (imageWidth > imageHeight) {
$('#output').append('<div class="image"><img src="' + imageURL + '"></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container text-center">
<form class="form-inline" method="post">
<div class="form-group mx-auto my-5">
<input type="text" class="form-control" id="search" placeholder="Search..." name="search">
<button class="btn btn-primary" type="submit">Procurar</button>
</div>
</form>
</div>
<div id="output"></div>
What I'm trying to do is use this input text and this button in order to change the value of the variable search which is on the URL.
I'm new with javascript but I think that what I'm missing is some jQuery syntax.
You need to:
1) Prevent page reload/submitting the form when clicking the button. You can remove the form element as you don't need to refresh the page but get the input text input or keep the form and change the input type from submit to a button one.
2) Hook on the button click event and then execute your GET request to unsplash api.
3) Put this event handler in a document ready event handler so it can trigger when you click the button.
4) Do your magic :)
I hope it helps. Try the snippet below with your API key.
var APIKey = "{mykey}";
$(document).ready(function() {
$("#searchBtn").on("click", function() {
var searchQuery = $("#search").val();
getJson(searchQuery);
});
});
function getJson(search) {
$.getJSON(
"https://api.unsplash.com/search/photos?query=" +
search +
"&per_page=19&client_id=" +
APIKey,
function(data) {
console.log(data);
var imageList = data.results;
$.each(imageList, function(i, val) {
var image = val;
var imageURL = val.urls.regular;
var imageWidth = val.width;
var imageHeight = val.height;
if (imageWidth > imageHeight) {
$("#output").append(
'<div class="image"><img src="' + imageURL + '"></div>'
);
}
});
}
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container text-center">
<form class="form-inline" method="post">
<div class="form-group mx-auto my-5">
<input type="text" class="form-control" id="search" placeholder="Search..." name="search">
<button id="searchBtn" class="btn btn-primary" type="button">Procurar</button>
</div>
</form>
</div>
<div id="output"></div>
I am creating a form with two text boxes: Task and Description. What I want to do is be able to console.log in both boxes and save the input through a submit button.
i.e:
task: do laundry
Description: do a buttload of laundry(idk lol)
Alright, I got that down(I think). But what I want to do after is that once I backspace and clear it, I want to add another task and description, but I also want to add that AFTER the saved input.
ie:
task: do laundry, study
Description, do a buttload of laundry, study a lot
Can someone check my code and see what's wrong? It's just showing the console.log input, which is nice, but I want to be able to use the push method to add to the end of my arrays and SAVE it.
function submitForm() {
var FormData = {
task: myForm.task.value,
description: myForm.description.value
};
myJSON = JSON.stringify(FormData);
localStorage.setItem("formJSON", myJSON);
text = localStorage.getItem("formJSON");
obj = JSON.parse(text);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(task);
console.log(" " + descriptionArray.join(", "));
}
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit=" return submitForm()">
<label class="required">*Task and Description* </label>
<!first text box>
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!second comment box>
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script type="text/javascript " src="json.js "></script>
</div>
</p>
</form>
</body>
</html>
All tasks and description has to be in array form and packaged in JSON.
You just need to call your addTask and addDescription functions when the form submits. JSFiddle: http://jsfiddle.net/wcrg804z/
Some errors with your code:
You have two addTask functions when you only need one.
Your addDescription function is trying to push task (which is undefined) to descriptionArray.
There are extra closing </div> </p> </form> tags after your form which are unnecessary.
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit="return submitForm()">
<label class="required">*Task and Description* </label>
<!--first text box-->
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!--second comment box-->
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script>
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
//myJSON = JSON.stringify(FormData);
//localStorage.setItem("formJSON", myJSON);
//text = localStorage.getItem("formJSON");
//obj = JSON.parse(text);
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(" " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(description);
console.log(" " + descriptionArray.join(", "));
}
</script>
</body>
</html>
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);
});
});
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 have this particular jquery code to add/remove fields on a form and then send its values:
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#reglas div").length + 1;
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');
var fName = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fName2 = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fName2);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function() {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
In which you can add/remove fields on the Cache section but the form sends every value except those which were added dynamically.
How can I solve it? You can see the posted form data with Firebug.
Here is a JS Fiddle for you: http://jsfiddle.net/34rYv/121/
Also I realized that when I delete fields, its name doesn't rename.
Maybe you can help me with this too :)
Thanks in advance
Nicolas
Your Cache section stands outside the <form> tags as i see in the source code, so that could be why your fields are not submitted.
Put your form around the left/right div like this:
<div id="wrapper" align="center">
<div class="container" align="center">
<form id="formsite"> // your form starts here
<div id="left">
</div>
<div id="right">
</div>
</form>
</div>
</div>
Instead of this ( what you have right now ):
<div id="wrapper" align="center">
<div class="container" align="center">
<div id="left">
<form id="formsite"> // your form starts here
// the form will automatically be closed in this div
</div>
<div id="right">
</form> // this one will go away
</div>
</div>
</div>
Also, try to keep your code clean, For example:
var fieldWrapper = $('<div></div>',{
class: 'fieldwrapper',
id: 'field'+intId
});
This is way cleaner than:
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');