How to sort AJAX results using toggle button - javascript

I have made an AJAX request that fetches completed Ebay auction results using Ebay's API (Finding Service). It works, producing the desired results, but now I am a stuck on how best to filter those results (in my case, using a button) by price, date of sale, etc.
For example: I have the variable url which has the filter url += "&sortOrder=StartTimeNewest";. I would like a button to toggle between that filter and url += "&sortOrder=StartTimeOldest"; using a click event.
I am a student, and pretty inexperienced when it comes to JS/frameworks...and so far have not had much luck figuring out the best way to do this aside from duplicating my entire code from ebay.js and altering it slightly for each filter I would like to apply.
For example: I can create different variables like url1, url2 and so on that have the filters I want, calling them from a different ajax requests attached to the buttons...
...but I'm sure there is a better and simpler way to do this without being so repetitive and would appreciate any help pointing me in the right direction.
Ebay.js
$(window).load(function() {
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
var searchstring = $('input[type="text"]', this).val();
var url = "https://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=BrandonE-DigIt-PRD-5cd429718-3d6a116b";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&itemFilter(0).name=MinPrice";
url += "&itemFilter(0).value=7.00";
url += "&itemFilter(0).paramName=Currency";
url += "&itemFilter(0).paramValue=USD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=50";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
url += "&categoryId=176985";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button id="mainbtn" type="submit" class="btn btn-default">Search</button>
</form>
<div class="filters col-xs-12 col-md-10 col-offset-md-1">
<!-- TOGGLE BUTTONS WILL ALLOW RESULTS TO BE SORTED. -->
<button type="button" class="btn btn-info btn-sm date-btn">date</button>
<button type="button" class="btn btn-info btn-sm price-btn">price</button>
</div>
<br />
<div class="index col-xs-12 col-md-10 col-offset-md-1">
<p class="restitle">results:</p><br />
<div class="results"></div>
</div>

Per our comments, I created a simple class that will generate the url for you.
Go ahead and tweek it to get the correct values in there. Hopefully this helps!
I added comments in the code but lmk if you have any questions.
$(function() {
// invoke click event
$("[data-filter]").off();
$("[data-filter]").on("click", function() {
let $this = $(this);
let data = $this.data();
// toggle value
if (data.value == false) {
$(this).data("value", true);
} else {
$(this).data("value", false);
}
// create class
let url = new buildfindCompletedItemsUrl();
// get the sort order
url.getSortOrder();
// build the url
let ajaxUrl = url.build();
// get the results
GetFilteredResults(ajaxUrl, function(results) {
$("body").append($("<p />", {
text: results
}));
})
});
})
// class with contructor
function buildfindCompletedItemsUrl() {
this.url = "https://svcs.ebay.com/services/search/FindingService/v1";
this.defaultUrlParams = {
"OPERATION-NAME": "findCompletedItems",
"SERVICE-VERSION": "1.13.0",
"SERVICE-NAME": "FindingService",
"SECURITY-APPNAME": "BrandonE-DigIt-PRD-5cd429718-3d6a116b",
"GLOBAL-ID": "EBAY-US",
"RESPONSE-DATA-FORMAT": "JSON",
"REST-PAYLOAD": "",
"itemFilter(0).name": "MinPrice",
"itemFilter(0).value": "7.00",
"itemFilter(0).paramName": "Currency",
"itemFilter(0).paramValue": "USD",
"paginationInput.pageNumber": "1",
"sortOrder": "",
"paginationInput.entriesPerPage": "50",
"categoryId": "176985"
}
return this;
}
// looks at the dom and fills the sortOrderParam
buildfindCompletedItemsUrl.prototype.getSortOrder = function() {
var $filters = $("[data-filter]");
let param = this.defaultUrlParams["sortOrder"];
let _ = this;
$.each($filters, function(i, f) {
let $filter = $(f);
let data = $filter.data();
let val = data.value;
if (val == true) {
if (_.defaultUrlParams["sortOrder"] == "") {
_.defaultUrlParams["sortOrder"] += data.filter;
} else {
_.defaultUrlParams["sortOrder"] += "," + data.filter;
}
}
})
};
// builds the full url for the ajax call
buildfindCompletedItemsUrl.prototype.build = function() {
let _url = this.url;
let keys = Object.keys(this.defaultUrlParams);
let length = keys.length;
for (let i = 0; i < length; i++) {
let key = keys[i];
let val = this.defaultUrlParams[key];
if (i == 0) {
_url += `?${key}=${val}`;
} else {
_url += `&${key}=${val}`;
}
}
return _url;
}
// get your results and return them
function GetFilteredResults(url, callback) {
// do ajax here
return callback(url)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-filter="date" data-value="false">Sort By Date</button>
<button data-filter="price" data-value="false">Sort By Price</button>

Related

How to create a button to add URL links in the form

Does anyone know how to add like a link button into a form? For example, a user clicks a + button and they can add an URL. They can add another URL if they wish and remove any links if required. Would be good to have validation for links as well.
I know for validation of the URL I can use "Check if a JavaScript string is a URL", but will need something that will validate all links if multiple have been added.
The best way to explain what I am trying to do is by looking at "Can I insert a hyperlink in my form?" in the form builder.
I just want to add links, and I don't need to display text or anything like that.
Is this what are you looking for?
Your question is a bit unclear.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
let i = 0;
let ii = 0;
function isURL(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(s);
}
function removeLink(id, iid) {
console.log(id);
console.log(iid);
$(id).remove();
$(iid).remove();
return false;
}
function addLink(id) {
var input = prompt("Enter the link", "https://www.example.com");
var valid = isURL(input);
console.log(valid);
if(valid) {
var element = '<br><a id="_' + i + '" href="' + input + '">Link</a>';
console.log(element);
$(id).append(element);
let d = "'#_" + i + "'";
let dd = "'#__" + ii + "'";
let elment = ' <button type="button" id="__' + ii + '" onclick="removeLink(' + d + ', ' + dd + ')">Remove it!</button>';
$(id).append(elment);
console.log(elment);
i = i + 1;
ii = ii + 1;
}
else {
alert("The URL that you have entred is wrong.");
}
return false;
}
</script>
</head>
<body>
<form id="_form" method="POST">
<button type="button" onclick="addLink('#_form')">Add link</button>
</form>
</body>
</html>
Try it here: https://codepen.io/marchmello/pen/ZEGjMyR?editors=1000
What about DOM - not using longer form, so using URL as link text too.
function addUrl(e) {
var f = e.form;
var a = document.createElement("A");
a.href = e.value; // link URL
a.textContent = e.value; // link text
f.appendChild(a);
var x = document.createElement("INPUT");
x.type = "button";
x.value = "X";
x.onclick = remove;
f.appendChild(x);
f.appendChild(document.createElement("BR"));
}
function remove() {
var el = this, // button
parent = el.parentNode, // a must for remove
a = el.previousElementSibling; // anchor
if(el.nextSibling.tagName == 'BR') parent.removeChild(el.nextSibling);
parent.removeChild(el);
parent.removeChild(a);
}
<form>
<input name="url" size="50">
<input type="button" value="Add" onclick="addUrl(this.form.url)"><br>
</form>

how to set value element input using function in jquery

I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}

Not able to display all rows dynamically

i have 7 team member and im just able to display 1 of them in id demo, how can i display all my team members? PFB HTML code and javascript one what im using for the same:
<div class="col-lg-3 mb-0" style="display: flex;align-items: center;">
<div class="popup" onclick="myFunction()"><h6>My team</h6>
<span class="popuptext" id="myPopup">My team members:<br><h7 id="demo"></h7><br></span>
</div>
</div>
</div>
<ol class="breadcrumb"></ol>
<script>
// When the user clicks on <div>, open the popup
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
var data1 = "TEAMSEARCH";
//alert(data1);
$.ajax({
url : 'TeamAssignment',
type : 'POST',
data : {
data1 : data1
},
success : function(result) {
var memberList = $.parseJSON(result);
//alert ( "Returned rows " + memberList.length);
for (var i = 0; i < memberList.length; i++)
{
console.log(memberList[i].fullName );
document.getElementById("demo").innerHTML = memberList[i].fullName;
}
}
});
}
</script>
document.getElementById("demo").innerHTML = memberList[i].fullName
Each iteration of the loop rewrites the entire innerHTML of demo. You probably want something like document.getElementById("demo").innerHTML += '<li>' + memberList[i].fullName + '</li>'
the += is the actually important part.
You repeatedly overwrite the demo innerHTML. You should make the assignment right after the for loop.
try something like this:
var members = '';
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName );
members += memberList[i].fullName;
}
document.getElementById("demo").innerHTML = members;
You can also use below one:
var memberList = $.parseJSON(result);
$("#demo").html('') // here just make empty innetHTML
for(var member of memberList)
$("#demo").append('<li>' + member.fullName + '</li>') // here appending html string of each member

JavaScript function to generate dropdowns / remove dropdown menus

I am trying to add and remove dropdown <select>s to a form on a button click. This is the code I have currently. I could have sworn I had this working last night, but when I went to work some more on my project this morning, the dropdowns wouldn't add / remove correctly.
function DropDowns(){
this.counter = 0;
this.addDropdown = function (divname) {
var newDiv = document.createElement('div');
var html = '<select name="cookie' + this.counter + '">', i;
for (i = 0; i < cookies_drop.length; i++) {
html += "<option value='" + cookies_drop[i] + "'>" + cookies_drop[i] + "</option>"
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
this.counter++;
}
this.remDropdown = function() {
$('#dropdowns-container').find('div:last').remove();
this.counter--;
}
}
var dropsTest = new DropDowns();
HTML:
<form action='' method=post id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I can only figure out the main problem may be on the server side when you create the cookies_drop variable using json_encode.
Other problems may reside in:
A test on the parameter of addDropdown function is suggested to check if it's valid
In the function remDropdown the decrement of the counter variable must be done only if the element is actually removed
You mixed jQuery and javaScript
Instead of using directly the createElement, making the code more simple and readable, you used the innerHTML property.
So, my snippet is:
// I assume you used something like:
// var cookies_drop = JSON.parse( '<?php echo json_encode($data) ?>' );
var cookies_drop = [{text: "Text1", val: "Value1"},
{text: "Text2", val: "Value2"},
{text: "Text3", val: "Value3"}];
function DropDowns() {
this.counter = 0;
this.addDropdown = function (divname) {
var divEle = document.querySelectorAll('form[id=' + divname + ']');
if (divEle.length != 1) {
return; // error
}
var newDiv = document.createElement('div');
var newSelect = document.createElement('select');
newSelect.name = 'cookie' + this.counter;
newDiv.appendChild(newSelect);
for (var i = 0; i < cookies_drop.length; i++) {
var newOption = document.createElement('option');
newOption.value = cookies_drop[i].val;
newOption.text = cookies_drop[i].text;
newSelect.appendChild(newOption);
}
divEle[0].appendChild(newDiv);
this.counter++;
}
this.remDropdown = function () {
var lastDiv = document.querySelectorAll('#dropdowns-container div:last-child');
if (lastDiv.length == 1) {
lastDiv[0].parentNode.removeChild(lastDiv[0]);
this.counter--;
}
}
}
var dropsTest = new DropDowns();
<form action="" method="post" id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>

Parsing JSON data using JavaScript push - want to prevent automatically closing divs

I'm working on parsing JSON data and converting it to html form.
I'm using the javascript push function, which I thought would push the data into the array I've designated it to in the order I push it. However, whenever I push a new div element, it is automatically closed after being pushed making the html come out in a different order I want. Is there a way I can prevent this?
JavaScript:
$(function(){
var container = $('.panel-body');
var jsonObj = $.parseJSON('{"fields":[{"label":"Nafn form / Form name","field_type":"sFormName","required":false,"field_options":{"size":"small"},"cid":"c2"},{"label":"Spurning 1 ","field_type":"QuestionText","required":false,"field_options":{"size":"small"},"cid":"c5"},{"label":"Spurning 2","field_type":"QuestionCheckbox","required":false,"field_options":{"options":[{"label":"","checked":false},{"label":"","checked":false}]},"cid":"c9"},{"label":"Spunring 4","field_type":"QuestionRadio","required":false,"field_options":{"options":[{"label":"Val","checked":false},{"label":"VAl ","checked":false},{"label":"Val","checked":false}],"include_other_option":false},"cid":"c13"},{"label":"Spurning með multi","field_type":"QuestionMultiBegin","required":false,"field_options":{"options":[{"label":"","checked":false},{"label":"","checked":false}]},"cid":"c17"},{"label":"Spurning","field_type":"QuestionDropdown","required":false,"field_options":{"options":[{"label":"Val","checked":false},{"label":"Val","checked":false},{"label":"Val","checked":false}],"include_blank_option":false},"cid":"c21"},{"label":"Skráning","field_type":"Registration","required":false,"field_options":{"options":[{"label":"Notendanafn / Username"},{"label":"Lykilorð / Password"}],"include_blank_option":false},"cid":"c25"}]}');
var body = [];
var headerData = jsonObj.fields;
console.log(headerData);
for (var i = 0; i < headerData.length; i++) {
if(jsonObj.fields[i].field_type == "sFormName") {
body.unshift("<div class='panel panel-default panel-element'><div class='panel-heading'>" + jsonObj.fields[i].label)
} else {
body.push("<div class='panel panel-default panel-element'><div class='panel-heading'>" + jsonObj.fields[i].label);
}
if (jsonObj.fields[i].field_type == "QuestionText") {
body.push("<div class='panel-body'><textarea class='large-text form-control'></textarea></div>");
} else if (jsonObj.fields[i].field_type == "QuestionParagraph") {
body.push(jsonObj.fields[i].field_options.description);
} else if (jsonObj.fields[i].field_type == "QuestionDropdown") {
var data = jsonObj.fields[i].field_options.options;
body.push("<div class='panel-body'><div class='dropdown'><button class='btn btn-default dropdown-toggle' type='button' data-toggle='dropdown' id='dropdownMenu1' aria-haspopup='true' aria-expanded='true'>" + jsonObj.fields[i].field_options.options[0].label + "<span class='caret'></span></button>");
body.push("<ul class='dropdown-menu' aria-labelledby=dropdownMenu1'>");
for(var j = 0; j < data.length; j++) {
body.push("<li><a href='#'>" + jsonObj.fields[i].field_options.options[j].label + "</a></li>");
}
body.push("</ul></div></div>");
} else if (jsonObj.fields[i].field_type == "QuestionRadio") {
var data = jsonObj.fields[i].field_options.options;
body.push("<div class='panel-body'>");
for(var j = 0; j < data.length; j++) {
body.push("<div class='radio'><div class='controls'><input type='radio' name='radio'></input>" + jsonObj.fields[i].field_options.options[j].label);
}
body.push("</div></div></div></div>");
} else if (jsonObj.fields[i].field_type == "Registration") {
body.push("<div class='panel-body'>");
body.push("<div class='form-group'><form class='reg-form' role='form'><div class='form-group'><label for='email'>" + jsonObj.fields[i].field_options.options[0].label + "</label>");
body.push("<input type'email' class='form-control' id='email'></div>");
body.push("<div class='form-group'><form class='reg-form' role='form'><div class='form-group'><label for='pwd'>" + jsonObj.fields[i].field_options.options[1].label + "</label>");
body.push("<input type'password' class='form-control' id='pwd'></div>");
body.push("<div class='checkbox'><label><input type='checkbox'> Muna mig / Remember me</label></div></form></div>");
}
$(container).html(body);
}});
As you can see, I wrote the code assuming that I would have to push an ending div to each element that I'd opened, however that seems to be ignored.
The problem here is that you're trying to pass the body array to the html method, however you should instead concatenate all strings inside of it, the pass it.
Like so:
var htmlMarkup = body.reduce(function(){
return prev + current;
}, '');
or use 'join' as suggested by Hacketo, since it's less verbose:
var htmlMarkup = body.join('');
$(container).html(htmlMarkup);

Categories