How to create a clone of Search field? - javascript

I have a search field in my app. I need to clone this search field with the same functions. One search field at the left side of the page and another, the same search field, at the right side of the page.
How I can make the clone using JS?
Below my JS code
document.querySelector('#city').addEventListener(click,'keyup', function(e) {
if (e.keyCode === 13) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>");
}
};
});
function show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
and part of HTML code
<body>
<div class="jumbotron" id="jumbo">
<h2 class="text-center" id="th2">Weather</h2>
</div>
<div class="container" id="cont">
<div class="row">
<h2 class="text-center text-primary">Your City</h2>
<span id="error"></span>
</div>
<div class="row form-group form-inline" id="rowDiv">
<input type="text" name="city" id="city" class="form-control" placeholder="City Name">
<button id="submitWeather" class="btn btn-primary">Search City</button>
</div>
<div id="show"></div>
</div>

As an option, I would suggest to create some function or class that creates input and description nodes and append to whatever container id (or class) you pass to it. In html you would only need element with rowDiv id. Obviously you can tailor it to your needs, but it's just an idea.
I thought something like this:
// rough example based of your code
class citySearch {
constructor(parentContainerId) {
this.searchField;
this.displayArea;
this.setStage(parentContainerId);
this.hookListener();
}
setStage(parentContainerId) {
this.searchField = document.createElement('input');
this.displayArea = document.createElement('div');
var parentContainer = document.getElementById(parentContainerId)
parentContainer.appendChild(this.searchField);
parentContainer.appendChild(this.displayArea);
}
show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
hookListener() {
this.searchField.addEventListener('keypress', this.onClick.bind(this));
}
onClick(e) {
if (e.keyCode === 13) {
var city = this.searchField.value;
if (city !== '') {
fetch('http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=bb037310921af67f24ba53f2bad48b1d")
.then( async(res) => {
const data = await res.json();
var widget = this.show(data);
this.displayArea.innerHTML = widget;
this.searchField.value = '';
})
} else {
this.displayArea.innerHTML = "<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>";
}
}
}
}
var firstSearch = new citySearch('rowDiv');
var secondSearch = new citySearch('rowDiv');
Html
<div class="row form-group form-inline" id="rowDiv"></div>

Here is some sample code that allows 1 code base, 2 search boxes and keeps the two search boxes in sync.
const searchBoxes = () => document.getElementsByClassName('searchbox');
document.addEventListener('DOMContentLoaded', function() {
Array.from(searchBoxes()).forEach(element => {
console.log(element.id);
element.addEventListener('keyup', function(event) {
let text = event.target.value;
// This is just a demo
document.getElementById("searchResult").innerHTML = text;
// Loop other search boxes
Array.from(searchBoxes()).forEach(e => {
if (e.id != event.target.id) e.value = text;
});
// ANY CODE HERE TO APPLY SEARCH
});
});
});
.searchbox {
border: 1px solid black;
background-color: wheat;
}
#searchResult {
height: 100px;
width: 100px;
background-color: yellow;
font-weight: bold;
}
<div>
<span>Some Text Here</span>
<input id="search1" class="searchbox" type="text" />
</div>
<div id="searchResult">ALL MY PAGE STUFF</div>
<div>
<span>Some Text Here</span>
<input id="search2" class="searchbox" type="text" />
</div>

Related

Im getting "JavaScript critical error at line 692" in internet explorer

I have a problem in IE with my forEach, it is working in Google Chrome and Microsoft Edge but IE is giving me this error.
Code :
function jsFiltreleme(GelenDeger) {
$('#myDiv').html('');
var cnt = 1;
$.ajax({
type: 'GET',
url: '/Ajax/ContractedServiceAdd2?serviceName=' + GelenDeger.serviceName + '&&cityCode=' + GelenDeger.cityCode + '&&countryCode=' + GelenDeger.countryCode + '&&markCode=' + GelenDeger.markCode + '',
dataType: "json",
success: function (response) {
response.forEach(acente => { //Problem is Here line 692
const $div = $('<div></div>').addClass("well well-sm").attr('style', 'border-style:ridge;');
$div.html(`
<div class = "numberCircle"> ` + cnt++ + ` </div> <strong>Acente Adı : </strong> ` + acente.name + `<br>
<strong>Yetki :</strong> ` + acente.category + `<br>
<strong>Adresi : </strong> ` + acente.address + `<br>
<strong>Telefon :</strong> ` + acente.phone + `<br>
<a href=\"mailto:`+ acente.email + `\"><strong> >E-Mail Gönder</strong><br>
<a href=\"https://maps.google.com/maps?q= `+ acente.lat + "," + acente.lng + `\"><strong> >Yol tarifi al</strong>
`);
$("#myDiv").append($div);
});
if (response.length == 0) {
alert("Kayıt Bulunamadı");
}
},
});
}
The arrow function expression doesn't support IE browser, you could change your code as below:
response.forEach(function (acente) { //Problem is Here line 692
});
if (response.length == 0) {
alert("Kayıt Bulunamadı");
}
Edit:
not change this time is say javascript critical error at line 693
This issue is related to the code about the dynamically add html elements. You could build the DOMString first, then insert the string into a div container using the append method. Code like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>
<script>
var response= [your response array];
var cnt = 1;
response.forEach(function (acente) {
var textnode = document.createTextNode(acente);
document.getElementById("output").appendChild(textnode);
var newdiv = "<div class = 'well well-sm' style='border-style:ridge;'><div class = 'numberCircle'> " + cnt++ + " </div> <strong>Acente Adı : </strong> " + acente.name + "<br />" +
"<strong>Yetki :</strong> " + acente.category + "<br>" +
"<strong>Adresi : </strong> " + acente.address + "<br>" +
"<strong>Telefon :</strong> " + acente.phone + "<br>" +
"<a href='mailto:" + acente.email + "'><strong> >E-Mail Gönder</strong>" + "<br/>" +
"<a href='https://maps.google.com/maps?q= " + acente.lat + "," + acente.lng + "'><strong> >Yol tarifi al</strong>" +
"</div>"
$("#output").append(newdiv);
});
</script>

Get request doesn't display value in HTML document

I think this is my stupidity and the problem is really slight but it just doesn't display anything after get request. I have no errors and I am getting return call 200. So everything in request seems to be fine.
if('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(function(position){
loadWeather(position.coords.latitude + ',' + position.coords.longitude);
});
} else {
loadWeather('Berlin, DE', '');
}
function loadWeather(location, woeid) {
$.simpleWeather ({
location: location,
woeid: woeid,
unit: 'c',
succes: function(weather) {
city = weather.city;
temp = weather.temp + '°';
wcode = '<img class="weathericon" src="assets/weatherimg' + weather.code + '.svg">';
wind = '<p>' + weather.wind.speed + '</p><p>' + weather.units.speed + '<p>';
humidity = weather.humidity + ' %';
$('.location').text(city);
$('.temperature').html(temp);
$('.climate_bg').html(wcode);
$('.windspeed').html(wind);
$('.humidity').text(humidity);
},
error: function(error) {
$('.error').html('<p>' + error + '</p>');
}
});
};
$(document).ready(function() {
loadWeather();
});
This is my html code.
<section>
<div class='mainContentHeader'>
<h2> Weather App </h2>
</div>
<div class='mainContent'>
<div class='container'>
<p class='location'></p>
<p class='temperature'></p>
<div class='climate_bg'>
</div>
<div class='info_bg'>
<img class='dropicon' src='/assets/Droplet.svg'>
<p class='humidity'></p>
<img class='windicon' src='/assets/Wind.svg'>
<div class='windspeed'></div>
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js'> </script>

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

jQuery don't work on phonegap

This code works perfectly in different browser (Chrome, Firefox, Safari), but in PhoneGap, when I click the button 'login' the logme function does not work.
I have tried to replace click by vclick,
or //ajax.gooogleapis.com/.... by file://ajax.goo.... but it does not work.
Do you have an idea of the problem?
thanks
<!DOCTYPE html>
<html>
<head>
<style>
* { font-family: Verdana, Geneva, sans-serif; line-height: 30px }
.title { background:#333; color: white; }
.success { color: #060; font-weight: bold; }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var apiURL = "localhost/wordpress/api/";
var noncestring = "get_nonce/?";
var authstring = "user/generate_auth_cookie/?";
var poststring = "posts_auth/create_post/?";
var username, password;
var nonce, cookie;
$('document').ready(function(){
$('#logme').click(function() {
jQuery(function($) {
username = document.forms["logme"].elements["username"].value;
password = document.forms["logme"].elements["password"].value;
});
getNonce("user", "generate_auth_cookie");
function getNonce(controller, method) {
$.getJSON(apiURL + noncestring + "controller=" + controller + "&method=" + method, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "nonce") {
nonce = val;
$('.status').append("<br>Nonce acquired for controller '" + controller + "', method '" + method + "': " + val);
// Add additional methods here. Could make this a switch statement.
if (method == "generate_auth_cookie")
createAuthCookie();
if (method == "create_post")
createPost();
getid();
}
});
});
}
function createAuthCookie() {
$('.status').append("<br>creating -> auth cookie with nonce " + nonce);
var authCookieURL = apiURL + authstring + "nonce=" + nonce + "&username=" + username + "&password=" + password;
$.getJSON(authCookieURL, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "cookie") {
cookie = val;
$('.status').append("<br>Auth cookie -> acquired! value: " + val);
// Get a new nonce to create the post:
getNonce("posts_auth", "create_post");
}
});
});
}
function getid() {
$('.status').append("<br>Get -> id");
var authCookieURL = apiURL + authstring + "nonce=" + nonce + "&username=" + username + "&password=" + password;
$.getJSON(authCookieURL, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "user") {
user = val;
$('.status').append("<br>id -> acquired! value: " + user.id + "<br>username -> acquired! value: " + user.username + "<br>nicename -> acquired! value: " + user.nicename + "<br>email -> acquired! value: " + user.email + "<br>avatar url -> acquired! value: " + user.avatar);
// Get a new nonce to create the post:
getNonce("posts_auth", "create_post");
}
});
});
}
function createPost() {
$('.status').append("<br>creating -> post with nonce: " + nonce);
var cookiepart = "&cookie=" + cookie;
var postContent = "&status=publish&title=NonceTest&content=test+test&author=Alex&categories=Demos&tags=test,api,json";
$.getJSON(apiURL + poststring + "nonce=" + nonce + cookiepart + postContent, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "status") {
console.log("status value: " + val);
if (val == "ok") {
$('.status').append("<br><span class='success'> -> A new post was successfully created.</span>");
}
}
});
});
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="title">Json Test 3</div>
<form id="loginForm" method="get" accept-charset="utf-8" name="logme">
<fieldset>
<div data-role="fieldcontain">
<label for="email"> Username </label>
<input type="text" name="username" id="email" value="">
</div>
<div data-role="fieldcontain">
<label for="password"> Password </label>
<input type="password" name="password" id="password" value="">
</div>
<input type="button" data-theme="g" name="submit" id="logme" value=" Login ">
</fieldset>
</form>
<div class="status">Getting nonce for auth cookie...</div>
</div>
</body>
</html>
Load jquery as 'http://'. I had this problem too when trying to load remote files with Phonegap (or Ionicframework), just '//' does not seem to work.
Your jquery works 100%. The problem is your apiURL is not from external server, its just from localhost. try test on external server. don't use localhost.

single and multiple File upload using jquery ajax in Struts 2

how to upload a file using ajax jquery with showing progress bar while uploading in struts2 i searched every where no luck can any one give me idea or some code snipplet thank you.for now i am using normal upload in html like this.
<a id="addFile-link" href="#" title="add file"><img src="htdocs/images/add_file.png" style="width: 20px; height: 20px; border: 0"></a>
<form id="form" name="form" target="viewFileUpload" method="post"
action="fileUpload.do" enctype="multipart/form-data">
<input type="file" name="upload" id="file" class="fileUpload" multiple>
</form>
$("#addFile-link").click(function() {
var initialFolderId = document.getElementById('currentFolder').value;
//Added for converting first time page load null or empty value validation in Servelet engine
if (initialFolderId == null || initialFolderId == "") {
initialFolderId = 0;
}
document.getElementById('selectedFolder').value = initialFolderId;
$("#file").click();
var uploadElement = document.getElementById("file");
$('#file').change(function() {
uploadElement.form.submit();
//sleep(100)
setTimeout(function() {openFolder(document.getElementById('currentFolder').value);getRecentActivity(0);}, 3000);
$('#Activites').html("");
});
});
$('#addFile-link').bind("click",function(){
var FolderId
FolderId=document.getElementById('currentFolder').value;
document.getElementById('selectedFolder').value = FolderId;
if( FolderId==" " || FolderId==0){
$('#input').prop('disabled', true);
showFileMSg();
//alert("kindly select a folder to upload files");
}
else{
$('#input').prop('disabled', false);
$('#fileupload').fileupload({
xhrFields: {withCredentials: true},
url: "fileUpload.do?",
type:"POST",
dataType : "JSON",
autoUpload: true,
formdata:{name:'FolderId',value:FolderId},
disableImagePreview:true,
filesContainer: $('table.files'),
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-upload fade">' +
'<td><span class="preview"></span></td>' +
'<td><p class="name"></p>' +
'<div class="error"></div>' +
'</td>' +
'<td><p class="size"></p>' +
'<div class="progress"></div>' +
'</td>' +
'<td>' +
(!index && !o.options.autoUpload ?
'<button class="start" disabled>Start</button>' : '') +
(!index ? '<button class="cancel">Cancel</button>' : '') +
'</td>' +
'</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-download fade">' +
'<td><span class="preview"></span></td>' +
'<td><p class="name"></p>' +
(file.error ? '<div class="error"></div>' : '') +
'</td>' +
'<td><span class="size"></span></td>' +
'<td><button class="delete">Delete</button></td>' +
'</tr>');
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.name').text(file.name);
row.find('.error').text(file.error);
} else {
row.find('.name').append($('<a></a>').text(file.name));
if (file.thumbnailUrl) {
row.find('.preview').append(
$('<a></a>').append(
$('<img>').prop('src', file.thumbnailUrl)
)
);
}
row.find('a')
.attr('data-gallery', '')
.prop('href', file.url);
row.find('button.delete')
.attr('data-type', file.delete_type)
.attr('data-url', file.delete_url);
}
rows = rows.add(row);
});
return rows;
},
always:function (e, data) {
$.each( function () {
$(this).removeClass('fileupload-processing');
});
},
done: function (e, data) {
$('.template-upload').remove();
$.each(data.files, function (index, file) {
openFolder(FolderId);
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
/*add: function (e, data) {
$('body').append('<p class="upl">Uploading...</p>')
data.submit();
},*/
})
}
});
<form id="fileupload" on action="fileUpload.do" method="POST" enctype="multipart/form-data">
<input id="input" type="file" name="upload" multiple style="cursor: pointer; display: none">
<im:hidden name="selectedFolder" id="selectedFolder" value="1" />
<span class="fileupload-process"></span>
<div class="col-lg-5 fileupload-progress fade">
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-info" style="width:0%;"></div>
</div>
<div class="progress-extended"> </div>
</div>
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
</form>

Categories