I'm trying to build a wikipedia viewer using Wikipedia's API, but I have a minor problem. If I manually press the search button, everything works fine, but if I press enter, nothing happens. Here's the js code:
$(document).ready(function () {
$("#input").keyup(function (event) {
if (event.keyCode == 13) {
$("#submit-button").click();
}
});
});
function wikiSearch() {
var query = document.getElementById("input").value;
var wiki_api = 'https://en.wikipedia.org/w/api.php';
var api = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&exintro=&explaintext=&generator=search&gsrlimit=10&gsrsearch=";
var wikilink = 'http://en.wikipedia.org/?curid=';
var link = api + query;
var html = "";
$.ajax({
url: link,
type: "get",
dataType: "JSONP",
success: function (data) {
var results = data.query.pages;
var pgs = Object.keys(results);
pgs.forEach(function (page) {
var title = results[page].title;
var text = results[page].extract;
var pagelink = wikilink + results[page].pageid;
html += '' + '<div class="item">' + title + '<br>' + '<p class="description-text" >' + text + '</p>' + '</div> <br> ';
});
$('#display').html(html);
}
});
}
And here's the html code:
<div class="container" id="content">
<h1>Wikipedia Viewer</h1>
<form>
<input type="text" name="search" placeholder="Search Wikipedia" id="input">
</form>
Random page
<input id="submit-button" type="button" value="Search" onclick="wikiSearch()" class="btn btn-success">
<div id="display"></div>
</div>
Here's a jsfiddle: https://jsfiddle.net/tbgoy836/
Replace input type="button" to submit. Also the input type="submit" should be inside the form. In that case you don't need to check the keycode & preventDefault will prevent the default behaviour of the form submit, since form is getting submitted using ajax. On pressing enter/return it will find the first submit button by itself and will trigger a click action
$(document).ready(function() {
$("#searchForm").submit(function(e) {
e.preventDefault();
wikiSearch()
})
});
function wikiSearch() {
console.log('wikiSearch')
var query = document.getElementById("input").value;
var wiki_api = 'https://en.wikipedia.org/w/api.php';
var api = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&exintro=&explaintext=&generator=search&gsrlimit=10&gsrsearch=";
var wikilink = 'http://en.wikipedia.org/?curid=';
var link = api + query;
var html = "";
$.ajax({
url: link,
type: "get",
dataType: "JSONP",
success: function(data) {
var results = data.query.pages;
var pgs = Object.keys(results);
pgs.forEach(function(page) {
var title = results[page].title;
var text = results[page].extract;
var pagelink = wikilink + results[page].pageid;
html += '' + '<div class="item">' + title + '<br>' + '<p class="description-text" >' + text + '</p>' + '</div> <br> ';
});
$('#display').append(html);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="content">
<h1>Wikipedia Viewer</h1>
<form id="searchForm">
<input type="text" name="search" placeholder="Search Wikipedia" id="input">
<div>
Random page
<input id="submit-button" type="submit" value="Search" onclick="wikiSearch()" class="btn btn-success">
</div>
</form>
<div id="display"></div>
</div>
Why you don't call function in javascript?
$("#submit-button").click(function(){
wikiSearch();
})
And remove onclick parameter of input.
Try $("#submit-button").trigger("click");
Or
you can simply call the function wikiSearch() instead of trigger the click event of submit button
Related
I have an application using Flask and JavaScript. I have a function in JavaScript when the user click the button and the data are send to Flask. This function create a marker on the map and set the data from function in Flask to marker popup. I use form in popup because I want to get the name form this popup. I want to submit this form from popup and get the name but when I do it print("Name :",nazwa_event) it return me None. I create a input with hidden tag in html and I set input value to the name from form $('input[id=nameOF]').val(nazwa.value);. It is possible to do that or I can't submit form from Ajax ?
HTML code:
<input type="text" id="name_of_event" class="form-control mb-2" name="name_event" placeholder="Nazwa wydarzenia">
<input name="nameOfEvent" type="hidden" value="" id="nameOF">
<br>
<button id="search-button_event" type='submit' name="event_form" class="btn btn-primary">Szukaj</button>
JS code:
$("#search-button_event").click(function () { // make ajax request on btn click
$.ajax({
type: "POST",
url: "/mapaa", // url to the function
data: {
nameevent: $("#name_of_event").val(), // value of the form
},
success: function (response) {
nazwa = (response['name']);
let marker_event = L.marker(array[0]).bindPopup()
marker_event._popup.setContent(
'<form method="POST" action="/mapaa"'+
'<p>Nazwa: '+nazwa+'</p>'+
'<button type="submit" id="form-submit" name="form-submit" class="btn btn-warning btn-block">Dołącz do wydarzenia</button>'+
'</form>')
marker_event.addTo(mymap)
polyline_event = L.polyline(array,{color: 'red'})
marker_event.on('click',function(){
polyline_event.addTo(mymap)
})
marker_event.getPopup().on('remove', function() {
polyline_event.remove()
})
$('input[id=nameOF]').val(nazwa.value);
mymap.setView(array[0],14)
},
});
});
FLASK code:
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
user_id = current_user.get_id()
slownik = {}
if request.method == "POST":
if request.is_json:
req = request.get_json()
nazwa = req['name']
data_pocz = req['data_start']
data_kon = req['data_end']
typ = req['type']
dlugosc = req['len_route']
coord = req['coordinates']
event_database = Event(date_start=data_pocz, date_end=data_kon, type=typ, name=nazwa, len_route=dlugosc,admin=user_id, route=coord)
db.session.add(event_database)
db.session.commit()
print('Dodano wydarzenie')
if 'form-submit' in request.form:
nazwa_event = request.form.get('nameOfEvent')
print("Id ev:",nazwa_event)
else:
name_ev = request.form.get('nameevent')
all_data = Event.query.filter_by(name=name_ev).all()
for row in all_data:
date_st_string = str(row.date_start)
date_end_string = str(row.date_end)
slownik = {'id':row.id,'date_st':date_st_string,'date_end':date_end_string,'type':row.type,'name':row.name,'len_route':row.len_route,'route':row.route}
return jsonify(slownik)
return render_template('mapaa.html', title='Mapa')
I can't test it but as for me you have hidden <input> in wrong place - it has to be inside form inside popup. And you can set value directly in HTML without using jQuery
marker_event._popup.setContent(
'<form method="POST" action="/mapaa"' +
'<input name="nameOfEvent" type="hidden" value="' + nazwa.value + '" id="nameOF">' +
'<p>Nazwa: ' + nazwa + '</p>' +
'<button type="submit" id="form-submit" name="form-submit" class="btn btn-warning btn-block">Dołącz do wydarzenia</button>' +
'</form>'
)
I'm not sure if it should be nazwa.value or only nazwa like in '<p>Nazwa: ' + nazwa + '</p>'
So I want to have a form (like a textarea with a submit button or something simple) that can change part of the link of another button (shown below).
This form would only change the 'receiveAddr' part of the href link (would change "1313mainstreetlosangeles" to the address the user submits) but keep everything else the same.
So changing only part of an href link in a button based on the text a user submits.
Is there any way to do this?
<a class="button" id="btn" href="https://url.com/v1/?type=buy&mode=popup&receiveAddr=1313mainstreetlosangelesca&receiveType=USD&callback=url.com" target="_blank">Buy now</a>
Have a look at URLSearchParams
You will need a polyfill for IE
let url = new URL("https://url.com/v1/?type=buy&mode=popup&receiveAddr=1313mainstreetlosangelesca&receiveType=USD&callback=url.com");
let params = new URLSearchParams(url.search);
document.getElementById("btn").addEventListener("click", function(e) {
var addr = document.getElementById("addr").value.trim();
if (addr) {
params.set('receiveAddr', addr);
url.search = params.toString();
this.href=url;
console.log(url);
} else {
e.preventDefault();
document.getElementById("addr").focus();
alert("Please fill in an address");
}
});
<input type="text" id="addr" />
<a class="button" id="btn" target="_blank">Buy now</a>
Alternative - NOTE the encodeURIComponent
document.getElementById("btn").addEventListener("click", function(e) {
var addr = document.getElementById("addr").value.trim();
if (addr) {
addr = encodeURIComponent(addr);
var url = `https://url.com/v1/?type=buy&mode=popup&receiveAddr=${addr}&receiveType=USD&callback=url.com`
this.href=url;
console.log(url);
} else {
e.preventDefault();
document.getElementById("addr").focus();
alert("Please fill in an address");
}
});
<input type="text" id="addr" />
<a class="button" id="btn" target="_blank">Buy now</a>
Sensible solution:
var changeForm = document.forms['changeBtn'],
regex = /receiveAddr=(.*?)&/;
changeForm.addEventListener('submit', function(e) {
e.preventDefault(); // Don't submit function
var form = e.target,
btn = document.getElementById('btn'),
href = btn.href,
textareaVal = encodeURIComponent(form.receiveAddr.value.trim());
btn.href = href.replace(regex, 'receiveAddr=' + textareaVal + '&');
});
<form id="changeBtn">
<textarea name="receiveAddr"></textarea><br>
<input type="submit">
</form>
<a class="button" id="btn" href="https://url.com/v1/?type=buy&mode=popup&receiveAddr=1313mainstreetlosangelesca&receiveType=USD&callback=url.com" target="_blank">Buy now</a>
Solution Overkill:
var changeForm = document.forms['changeBtn'],
regexFirstPart = /(.*)\?/;
changeForm.addEventListener('submit', function(e) {
e.preventDefault(); // Don't submit function
var form = e.target,
href = document.getElementById('btn').href,
firstPart = regexFirstPart.exec(href)[0],
urlParts = processQuery(href); // ends with ?
urlParts.receiveAddr = changeForm.receiveAddr.value;
btn.href = firstPart + objectToUrlParams(urlParts);
});
function processQuery(url) {
var regex = /[?&]([^=#]+)=([^&#]*)/g,
params = {},
match;
while (match = regex.exec(url)) {
params[match[1]] = match[2];
}
return params;
}
function objectToUrlParams(obj) {
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
}
<form id="changeBtn">
<textarea name="receiveAddr"></textarea><br>
<input type="submit">
</form>
<a class="button" id="btn" href="https://url.com/v1/?type=buy&mode=popup&receiveAddr=1313mainstreetlosangelesca&receiveType=USD&callback=url.com" target="_blank">Buy now</a>
Tricky solution:
textarea=//your textarea
var value="";
if(textarea.value==null){
value="1313mainstreetlosangelesca";
}else{
value=textarea.value;
}
Then add link to document:
link='<a class="button" id="btn" href="https://url.com/v1/?type=buy&mode=popup&receiveAddr='+value+'&receiveType=USD&callback=url.com" target="_blank">Buy now</a>';
Use String interpolation of a variable that would be set with the new address upon submission of the form
I am dynamically generating checkboxes from my database using jquery ajax to call my web api. The problem is that I am trying to get the length of the checkbox array but constantly receiving an array length of zero when i debug. Please what might be wrong with my code.
HTML CODE
<div class="panel-body">
<form method="post">
<div class="form-group">
<label>Add Role Name</label>
<input type="text" class="form-control" placeholder="Role Name" />
</div>
<div class="col-md-6">
<div class="well">
<fieldset id="appName">
</fieldset>
</div>
<input id="saveUrl" type="button" value="Add Role" class="btn btn-success pull-right" />
</div>
</form>
</div>
JQUERY CODE
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
method: 'GET',
url: 'http://localhost:61768/api/users/GetUrls',
headers: {
'Authorization': 'Basic ' + btoa(localStorage.getItem('ApplicationId') + ":" + localStorage.getItem('ApiKey'))
},
success: function (data) {
if (Object.keys(data).length == 0) {
alert("Ewoo");
} else {
$.each(data, function (index, value) {
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
$('#appName').append(input); //Where I generate the checkboxes
});
}
},
error: function () {
alert("DonDy");
}
});
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
$('#saveUrl').click(function () {
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
});
</script>
The result of click the save button is alerting bad
In this code checkbox is getting appended but you are not checking the checkbox
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
Here you are checking length of checked checkbox..hence alerting to bad :
var $checkboxes = $('input[name="chk[]"]:checked');
Try this and that to inside save url click fucntion:
$('#saveUrl').click(function () {
var $checkboxes = $('input[name="chk[]"]');
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
Since you are populating/creating checkbox inside an AJAX call, you should have $checkboxes inside the #saveUrl function, because before that, it would be empty when the JS is loaded. You need this variable when the #saveUrl is clicked, hence it should check for the checked inputs when the #saveUrl is triggered:
$('#saveUrl').click(function() {
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
can anyone tell how to add tooltip for dynamically created button.In my page i have one submit button,and it will create dynamic buttons with respect to the xml data.i want to create tooltip for this buttons.here is my code
<script>
$(document).ready(function () {
$("#Submit").click(function () {
$.ajax({
type: "GET",
url: "mars.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('student').each(function () {
var Name = $(this).find('name').text();
var Mark = $(this).find('marks').text();
var Sid = $(this).find('id').text();
var student_id = "#"+$(this).attr("id");
$("#content").append("<li><input type='button' class='dyna_btn' id = '"+$(this).attr("id")+"' value='"+Name+"'/></li>");
var hue = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
$(student_id).css('color', hue);
$("#content").append('<li>' + Sid + '<li>');
});
}
});
});
});
$(document).on("click", ".dyna_btn", function() {
alert("button"+$(this).attr("id"));
console.log("button clicked");
});
</script>
<body>
<form id="From1" method="post">
<input type="button" value="submit" name="Submit" id="Submit" />
<div id="content">
</div>
</form>
</body>
Just add title="" attribute in same way like this:
<input type='button' class='dyna_btn' id = '"+$(this).attr("id")+"' value='"+Name+"' title='"+Name+"' />
Created this website. Works fine if characters in the search box are entered slowly(5 results get displayed) but when typed fast, multiple of 5 results get displayed, indicating that .empty() does not work. Please guide.
Document Ready,
<script type="text/javascript">
$(document).ready(function () {
$("#search").keyup(function(e){
$("#status").empty();
/*
var keyCode = e.keyCode || e.which;
if(keyCode == 13) {*/
myFunction();
//}
});
$("#status").hide();
$("#more").hide();
});
</script>
Some more JS added,
var nexturl ="";
var lastid ="";
var param;
function myFunction() {
param = $('#search').val();
//alert("I am an alert box!");
if (param != "") {
$("#status").show();
//alert("Show ");
var u = 'https://graph.facebook.com/search/?callback=&limit=5&q='+param;
$("#data").empty(); //empty the data div
//alert("emptied?");
getResults(u);
$("#more").show();
}
$("#more").click(function () {
$("#status").show();
//alert("Show ");
$("#more").hide();
pageTracker._trackPageview('/?q=/more');
var u = nexturl;
getResults(u);
});
}
</script>
The HTML involved,
<div style="margin-bottom:10px;float:right;">
<form action="" method="get" id="searchform" onsubmit="return false;">
<input name="q" type="text" id="search" onClick="this.select();" size="32" maxlength="128" class="txt" style="padding: 0 5px;" >
<input type="button" id="hit" value="Search" onclick="myFunction();return false" class="btn">
</form>
</div>
</div>
<div id="data_container">
<div id="data">
<div id="status_container">
<div id="status"><img src="loader.gif" alt="loading facebook status search"/></div>
</div>
</div>
</div>
The getResults() function,
function getResults(u) {
//$("#status").show();
$("#data").empty(); // print that we are in
$.ajax({
dataType: "jsonp",
url: u,
success: function(res) { // take an object res
$("#data").empty();
$("#status").show(); // show status
$("#more").show();
if (res.data.length) { // check length of res
// print if >0
nexturl = res.paging.next; // calculate next url
$.each(res.data, function(i,item){
if (item.id != lastid) {
lastid = item.id;
var html ="<div class=\"post\">";
html += "<div class=\"message\">"+item.from.name+" ";
if (item.message) {
html += item.message+"<\/div>";
} else {
html += "<\/div>";
}
if (item.picture) {
html += "<div class=\"image\"><img src=\""+item.picture+"\"></div>";
} else {
html += "<div class=\"image\"><\/div>";
};
if (item.link) {
html += "<div class=\"link\">"+item.name+"</div>";
if (item.caption) {
html += "<div class=\"caption\">"+item.caption+"</div>";
};
if (item.description) {
html += "<div class=\"description\">"+item.description+"</div>";
};
};
html += "<div class=\"meta\">";
if (item.icon) {
html += "<span class=\"icon\"><img src=\""+item.icon+"\"></span> ";
};
var t = item.created_time;
var time = t.substring(0,19)+"\+00:00";
html += "<span class=\"time\">"+$.cuteTime({},time)+"<\/span> ";
html += " <\/div>";
html +="</div>";
$("#data").append(html) ;
}
});
$("#more").appendTo("#data");
$("#more").show();
$("#status").appendTo("#data");
} else {
$("#data").append("<h3 class=\"none\">No entries found. Please try another search.</h3>");
};
}
});
}
In Chrome and FireFox it does work for me. It just continues changing with every character and catches up - which is typical. It might be a good idea to add a short delay in between result changing, though, so that you can better track and watch the changes for testing purposes or report out to the console when the .empty() fires and what that selector's contents are after to ensure it does work the way you expect it.