I'm working on the wikipedia viewer for free code camp and I'm trying to make the search bar work.
Ideally I would just like to have the user type in some text, then have that become a string in my code when the user hits submit. This is the html for the search bar so far
<form method="get">
<input type="text" placeholder="Search articles" class="srchbox" name="Search" id="searchbar">
<button type="submit" class="btn">Search</button>
</form>
and the api setup I have to make the search
var apiURL = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&generator=search&search=" + textInput;
$(document).ready(function() {
$.ajax({
url: apiURL,
dataType: "jsonp",
success: function(data) {
var wikiAPI = JSON.stringify(data, null, 3);
console.log(wikiAPI);
var wikiHTML = "";
for (i=0; i < data[1].length; i++)
{
wikiHTML += ("<a href =\"" + data[3][i] + "\" target=\"_blank\">")
wikiHTML += "<div class = \"wikicontent container-fluid\" style = \"color:black;\">";
wikiHTML += ("<h2>" + data[1][i] + "</h2>");
wikiHTML += ("<h3>" + data[2][i] + "</h3>");
wikiHTML += "</div></a>"
}
$("#articles").html(wikiHTML);
I'm a bit lost on how to pull this off so any help would be great. Thank you!
You can use submit event, set query to #searchbar .value
$("form").on("submit", function(e) {
e.preventDefault();
if (this.searchbar.value.length) {
var url = "https://en.wikipedia.org/w/api.php?format=json"
+ "&action=opensearch&generator=search&search="
+ this.searchbar.value;
$.ajax({url:url, /* settings */});
}
});
Related
I am trying to get my search box to work and do a getJSON on text search and title. but in the console log, I get text=undefined?title=undefined. so it is not displaying any JSON. Not sure if my click is working correctly or if I have to make my JSON objects?
Script
<script>
var searchstring = $('input[type="text"]', this).val();
var url = "https://data.edu/api/v1/metadata";
url += "?text=" + searchstring;
url += "?title=" + searchstring;
$(document).ready(function() {
$('button[type="button"]').click(function(event){
$.ajax({
type: "GET",
url: url,
success: function(res){
console.log(res);
var items = res.data.metadata;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "</div><br />";
};
$('#results').html(ins);
}
});
});
});
</script>
html
<form class="destinations-form" role="search" >
<div class="input-line">
<input id="searchForm" type="text" class="form-input check-value" placeholder="Search Documents" />
<button type="button" class="form-submit btn btn-special" "</button>
</div>
</form>
<div class="container">
<div class="hero-text align-center">
<div id="results"></div>
</div>
</div>
json
data: [
{
collection_id: "ADGM-1552427432270-483",
metadata:{
year: "2019",
files: text ,
title: text,
},
The problem is because you only read the values from the field when the page first loads and it is empty. To fix this, move that logic inside the click handler.
The next issue is that you should remove this from $('input[type="text"]', this). You don't need a contextual selector here, and this one is incorrect regardless.
Also note that a valid querystring starts with ? and separates each value with &, so your url concatenation needs to be amended slightly. In addition you shouldn't update the url value on every click. If you do it this way your AJAX request will only work once.
Lastly the metadata in your response is an object, not an array. data is the array so you need to loop over that instead. The loop can also be simplified by using map(). Try this:
$(document).ready(function() {
const url = "https://data.edu/api/v1/metadata";
$('button[type="button"]').on('click', function(e) {
let searchstring = $('input[type="text"]').val();
let requestUrl = url + `?text=${searchstring}&title=${searchstring}`;
$.ajax({
type: 'GET',
url: requestUrl,
success: function(res) {
let html = res.data.map(item => `<div>Title ${item.metadata.title}</div><br />`);
$('#results').html(html);
}
});
});
});
Greetings to the experts on WEB development, I myself am a beginner in this field, I am doing a training project, so the question arose. There is a form:
...
<form name="date">
<p>
<label for="date">Choose date</label>
<input type="date" name="calendar" id="calendar" onchange="handlerDate(event)">
</p>
</form>
...
Which I then process in this way:
function handlerDate(e) {
e.preventDefault();
let dateForm = document.forms["date"];
let dateChosen = dateForm.elements["calendar"].value;
let dateNow = new Date();
dateChosen = new Date(dateChosen);
if ($('#uncorrectDate').length)
$('#uncorrectDate').remove();
if ((dateChosen.getFullYear() !== dateNow.getFullYear() || dateChosen.getMonth() !== dateNow.getMonth()) ||
((dateChosen.getFullYear() === dateNow.getFullYear() || dateChosen.getMonth() === dateNow.getMonth()) &&
(dateChosen.getDate() < dateNow.getDate()))
) {
$('<p id="uncorrectDate">Incorrect date</p>').appendTo('.mainbody');
$("#userInfo").remove();
} else {
if($('#userInfo').length)
$('#userInfo').remove();
var timesGet = GetOrders(dateChosen.toLocaleDateString());
times = timesGet.booked;
let selectTimes = '</p><p><label>Choose time: </label><select name="text">';
for (let k = 0; k < times.length; k++) {
let time = `${times[k]}:00`;
selectTimes += '\n<option value="' + time + '">' + time + '</option>';
}
selectTimes += "</select><\p>";
$('<form id="userInfo">' +
'<p> ' +
'<label for="email">Email:</label>' +
'<input type="email" placeholder="user#gmail.com" name="email"/></p>' +
'<p>' +
'<label for="phone">Телефон: </label>' +
'<input type="tel" placeholder="(XXX)-XXX-XXXX" name="phone"/>' +
'</p>' +
'<p>' +
selectTimes +
'</p>' +
'<p>' +
'<button type="submit">Send</button>' +
'</p>' + '</form>'
).appendTo('.mainbody');
}
}
function GetOrders(date) {
var result = "";
$.ajax({
url: "/api/records/" + date,
type: "GET",
async: false,
contentType: "application/json",
success: function (record) {
result = record;
}
});
return result;
}
function CreateOrder(userName, userMail, userPhone, userDate, userTime) {
$.ajax({
url: "api/users",
contentType: "application/json",
method: "POST",
data: JSON.stringify({
name: userName,
email: userAge,
phone: userPhone,
date: userDate,
time: userTime
}),
success: function (user) {
$(".mainbody").append('<p>Заказ был сделан!</p>');
}
})
}
The logic that was unnecessary for understanding the issue is removed. First question: is it normal practice to dynamically change the page in this way through jQuery? Since I am doing that purely for practical purposes: to make a task, I’m not entirely guided by how it is customary to do, how it is not customary. The second and main question: how can I now receive and correctly send data from the form? Is there an example syntax in this case (without php). There is an onsubmit attribute in the form, you can specify the function handler there, but is there an example of how this is done? And is it necessary in this case to put an additional handler function onclick on the submit button? I need to get data from the form, validate it, and call the CreateOrder method with this data. On the server, all this will be processed correctly, I configured it, but did not find normal examples of how to write correctly onsubmit or onclick, into which I need to pass 1 parameter: the date received earlier.
I make a server request to get streetnames and they should show up as datalist options....but in google chrome they didn't.
In Firefox and IE it pops up with the correct requested street names. Here is some Code:
the HTML:
<li>
<label>Straße <span class="required">*</span></label>
<input id="input_strasse" type="text" value ="Strasse" autocomplete="off" list="input_strasse_datalist" class="field-long" placeholder="Straße" />
<datalist id="input_strasse_datalist" ></datalist>
</li>
JS:
$(document).on("keyup", "#input_strasse", function () {
var inputStr = $('#input_strasse').val();
var charStr = inputStr.charAt(0).toUpperCase() + inputStr.substr(1);
var UrlToWebservice = window.localStorage.getItem("url_to_webservice");
console.log("buchstabensuppe: ", charStr)
$.ajax({
type: 'POST',
url: UrlToWebservice + 'SP_SELECT_Strassen',
data: { 'charStr': charStr },
crossDomain: true,
dataType: 'xml',
success: function (response) {
// var strassen = new Array;
$(response).find('STRASSE').each(function () {
var strasse = $(this).find('NAME').text();
var plz = $(this).find('PLZ').find('plz').text();
var ort = $(this).find('PLZ').find('ORT').text();
var arstrasse = $(this).find('AR').first().text();
console.log("arstrasse ", arstrasse)
$("#input_strasse_datalist").append('<option data-ar = ' + arstrasse + ' value = "' + strasse + ' (' + plz + ', ' + ort + ')">' + strasse + ' (' + plz + ', ' + ort + ')</option>')
$("#input_plz").val(plz)
$("#input_ort").val(ort)
})
},
error: function () {
window.location.hash = "httperror";
}
})
})
I recognized that user-agent gives datalist display: none; if I gave the datalist display: block; but it looks like this:
So it is not inside the Dropdown and no option is selectable. It should look like this:
The really strange thing is, that it works perfectly on the local version of the app. Only when I run it at the server in the local chrome the strange behaviour appears. I'm really clueless. Please help. Thanks!
Seems to work after updating chrome.
No problem anymore with Version 63.0.3239.84.
I want to fetch the values from dynamically created html textboxes in my aspx page. Now first I want to check if the textbox exists or not. If exists then I want to fetch values from these texboxes. Here is the code which I am using for creating textboxes dynamically
<script type="text/javascript">
var counter = 2;
$(document).ready(function () {
$("#addButton").click(function () {
if (counter > 3) {
alert("Limit Exceeds");
return false;
}
var $wrap = $('#TextBoxesGroup');
var dynamichtml = '<div id="div' + counter + '"><div class="mcity"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="mcity"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div><div class="mcity"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 11 + '" class="auto"/> </div>';
$wrap.append(dynamichtml);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxesGroup").find("#div"+ counter).remove();
// $("#TextBoxesGroup").find("#textbox" + counter+1).remove();
});
$(".auto").live("focus", function () {
$(this).autocomplete({
source: function (request, response) {
var textval = request.term; // $(this).val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + textval + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
});
});
</script>
This code is generating textboxes generating and I am fetching data from my database using json autocomplete process.After this I am trying to send the information to another page using javascript the code that I write for this is below
<script type="text/javascript">
$(function () {
$("#btnPost").bind("click", function () {
//Create a Form
var $form = $("<form/>").attr("id", "data_form")
.attr("action", "Complete.aspx")
.attr("method", "post");
$("body").append($form);
//Append the values to be send
AddParameter($form, "txtleft", $("#txtSearchleft").val());
AddParameter($form, "txtright", $("#txtSearchright").val());
//Send the Form
$form[0].submit();
});
});
function AddParameter(form, name, value) {
var $input = $("<input />").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
form.append($input);
}
</script>
This work fine for textboxes which placed default in my page. But for the textboxes that generate dynamically after these textboxes I dnt know how to send values of those textboxes to my next page
Javascript and asp.net experts please help me to resolve this
Thanks
You can get the controls values using FormCollection. Note that it works on name rather than Id.
You need to keep the count and follow some naming convention for name of your controls.
Create a asp.net hidden field and keep the control count in that. And get according the values of the hidden field.
Msdn link
well if you were to assign your form an id
you could just serialize your form and post it using ajax if you wanted
$.post("complete.aspx",$("#data_form").serialize(),function(response){
//react to the post here
});
I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}