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>
Related
I am working on implementing a web chat and have come up with an issue that I hope is easily solvable.
How do I change the color for the sender/receiver to differenciate them?
I have tried to saving the colors into my db but the issue is how I can identify that I am the sender and the receivers color needs to be different.
This is how I have implemented my chat:
Chat.js
connection.on("SessionNotification", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = user + " - " + moment(datetime).format("DD-MM-YYYY HH:mm:ss");
q.textContent = msg;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
});
Html
<script>
$(document).ready(function () {
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
var SessionId = document.getElementById("Id").value;
console.log(SessionId);
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
return false;
});
</script>
<div class="col-sm-12">
<h2>Session</h2>
<hr />
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div id="MessageListContainer">
<ul id="MessageList">
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CurrentUser)
<input class="form-control col-sm-12" id="Message" type="text" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input id="Send" type="button" value="Send" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<hr />
</div>
</div>
<script src="~/aspnet/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Your AJAX call that comes back as JSON appears to have a few fields like Name and CreatedOn. You can add an additional field server side for the SessionId, which you are injecting server-side anyway into your HTML. Then you can compare to see if the message's session matches yours. If so, then it is you and not the receiver. So you might have something like:
JS
// You set this earlier on
var SessionId = document.getElementById("Id").value;
// ........ OTHER CODE IN BETWEEN
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
// If session ID matches current session (i.e. you) then add different class
if (output[i].SessionId === SessionId) {
// It is you
p.setAttribute("class", "Sender");
} else {
// It is other person
p.setAttribute("class", "Receiver");
}
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
CSS
.Sender {
color: blue;
}
.Receiver {
color: green;
}
$("#backButton-1").click(function() {
$("#form-2").empty();
$("#form-1").show();
});
I'm having an issue getting this snippet to run. form-1 is hidden, backButton-1 is created after the end of form-2 and only after form-1 has been hidden. I want backButton-1 to empty out form-2 and unhide form-1 but the .click event isn't firing.
Here's the code:
$(document).ready(function() {
var playersName = '';
var gameName = '';
var playersNameArray = [];
$("#submit-1").click(function() {
playersName = $("#input_players").val();
gameName = $("#input_game").val();
$("#form-1").hide();
gameName = gameName.toLowerCase();
gameName = gameName.charAt(0).toUpperCase() + gameName.substr(1);
function makeArray(string) {
string = string.replace(/\s/g, '');
var array = string.split(",");
for (let i = 0; i < array.length; i++) {
array[i] = array[i].toLowerCase();
array[i] = array[i].charAt(0).toUpperCase() + array[i].substr(1);
}
playersNameArray = array;
}
makeArray(playersName);
function makeScores(array) {
$("#container-1").prepend("<p>Input " + gameName + " scores:</p>");
for (let i = 0; i < array.length; i++) {
var scoreDiv = document.createElement("div");
scoreDiv.className = "score";
scoreDiv.id = "score-" + (i + 1);
var scoreInput = document.createElement("input");
$(scoreInput).attr('type', 'text');
scoreInput.id = "scoreInput-" + (i + 1);
$("#form-2").append(scoreDiv);
$("#score-" + (i + 1)).append("<div class='scoreName'>" + array[i] + "</div>");
$("#score-" + (i + 1)).append(scoreInput);
}
$("#container-1").append(
$("<div class='submitButtonDiv' />").append(
$('<input type="submit" name="submit-2" value="Submit" id="submit-2" />')
),
$("<div class='backButtonDiv' />").append(
$('<input type="button" name="backButton-1" value="Back" id="backButton-1" />')
)
);
}
makeScores(playersNameArray);
});
$("#backButton-1").click(function() {
$("#form-2").empty();
$("#form-1").show();
});
$("#submit-2").click(function() {
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container-1">
<form action="/database.php" method="POST" id="form-1">
<div class="input">
<p>Enter player names, separated by commas:</p>
<input type="text" name="input_players" id="input_players">
</div>
<div class="input">
<p>Enter game name:</p>
<input type="text" name="input_game" placeholder="e.g. Smallworld" id="input_game">
</div>
<div class="submitButtonDiv">
<input type="submit" name="submit-1" value="Submit" id="submit-1">
</div>
</form>
<form action="/database.php" method="POST" id="form-2"></form>
</div>
You are saying the button is being created, which means that jQuery cannot add an event listener on load. Either create the listener together where you create the button, or use propagation.
// Create button, add to DOM
$("<div>New div</div>").appendTo("body")
.click(function() {
// Attach click event listener
alert("Works!");
});
// Or using propagation
$("body").on("click", "#test", function() {
alert("Works too!");
});
$("<div id='test'>New div</div>").appendTo("body");
Note that the second approach works irrespective of where you attach the event listener to body, be it before or after creating the new item.
In your case, I suggest:
$("#container-1").append(
$("<div class='submitButtonDiv' />").append(
$('<input type="submit" name="submit-2" value="Submit" id="submit-2" />')
),
$("<div class='backButtonDiv' />").append(
$('<input type="button" name="backButton-1" value="Back" id="backButton-1" />')
)
).on("click", "#backButton-1", function() {
$("#form-2").empty();
$("#form-1").show();
});
Try adding your links at the bottom
and add the following link in your head
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script> <!-- <<<< This ONE-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container-1">
<form action="/database.php" method="POST" id="form-1">
<div class="input">
<p>Enter player names, separated by commas:</p>
<input type="text" name="input**strong text**_players" id="input_players">
</div>
<div class="input">
<p>Enter game name:</p>
<input type="text" name="input_game" placeholder="e.g. Smallworld" id="input_game">
</div>
<div class="submitButtonDiv">
<input type="submit" name="submit-1" value="Submit" id="submit-1">
</div>
</form>
<form action="/database.php" method="POST" id="form-2"></form>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
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 have modified the answer in the post dicussed here.
In my application I have two buttons - edit and save. When clicked on edit, the labels get converted into input fields, where the user can edit the content and save.
Everything is working fine, but the problem is that when the user clicks on the edit button twice, the content in the input fields becomes blank, i.e. the <input> value becomes blank.
Please suggest me a fix for this. Where am I going wrong?
<div id="companyName">
<label class="text-cname"><b>#Html.DisplayFor(m => m.Company)</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" />
</div>
<script>
$(document).ready(function () {
$('#edit').click(function () {
// for company name
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
</script>
You can use replaceWith() method to convert label to textarea.
$("#edit").click(function(){
var text = $("label").text();
$("label").replaceWith("<input value='"+text+"' />");
});
$("#save").click(function(){
var text = $("input ").val();
$("input ").replaceWith("<label>"+text+"</label>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="edit">Edit</button>
<button id="save">Save</button>
<br/><br/>
<label>Text</label>
The most simple fix would be to disable the edit button once you've clicked it, and enable it again after saving:
$(document).ready(function () {
$('#edit').click(function () {
$(this).prop('disabled', true);
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
$('#edit').prop('disabled', false);
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
When you click the second time the value of companyName is empty, that's why the <input> value becomes blank. This is a very simple solution, but you lose the focus on edit box which is easy to fix.
$('#edit').click(function () {
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if(companyName != "")
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
Try This one
function EditContent(){
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if (companyName != "") {
$('.text-cname').text('').append(lblCName);
}
lblCName.select();
}
function SaveContent(){
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="companyName">
<label class="text-cname"><b>Company</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" onclick="SaveContent()" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" onclick="EditContent()" />
</div>
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 + '"/>');