Change button using CSS or by using scripts - javascript

I am using data tables to show data and a button is present opposite to each entry of my data table.
That button has onclick which captures the parameter present in a row and save in array.
I want to change color when certain entry is selected and reset on deselect.
Here is what I am doing,
function select(name){
var property = document.getElementById('checkRule');
if( rArray.includes(name) ){
property.style.backgroundColor = "#FFFFFF"
const index = rArray.indexOf(name);
if (index > -1) {
rArray.splice(index, 1);
}
}else{
rArray.push(name);
property.style.backgroundColor = "#28a0ff"
}
console.log('ARRAY >> ', rArray);
}
This code is only changing color of very first element of of data table.
How shall I make it work?

Assuming that you want to send the ajax request after you select a radio button and you click on go.
You do not need to change the html, but you will have to change the javascript file.
$("#go").click(() => {
var result = $("input:radio[name='doamin']:checked").val();
console.log("result > ", result);
var Data = {
result1: result,
};
console.log("postData > ", Data);
$.ajax({
url: "import",
headers: {
Accept: "text/plain",
"Content-Type": "application/json",
},
type: "POST",
dataType: "html",
data: JSON.stringify(Data),
success: function (data) {
console.log(data);
},
error: function (err) {
console.log(err);
},
});
});
Ideally, you want to send a POST request, as there is a body attached.

Related

wrong value due to client side and server side integration

I have a text area with id "text" and I am toggling the text area to appear on the screen with a click event on some div and I have 30 such divs. Initially , I'm assigning the textarea.value with result of ajax call to my fetch api which fetches the data from the mongo on the server side based on an unique id.
Sometimes , when I'm making the ajax call to my update api in my backend , the textarea.value I'm sending as data to this ajax call is not the same as the updated text of the text area.
//client side
// called when any of the divs is clicked
$(".radius").on("click", function(event) {
//extracting the id from the class and using this id as the id of my data for my mongo
var st=event.target.classList[1].substring(0,7);
var num=parseInt(event.target.classList[1].substring(7));
var toadd="close-button"+num;
//console.log(num+"modal")
closeButton.classList.add(toadd);
$.ajax({type: "POST",
url: "/fetch",
async: true,
data: JSON.stringify({
id: num,
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
input.value=result.text;
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
});
// called when textarea is closed
function toggleModal1(event) {
var s1=closeButton.classList[closeButton.classList.length-1];
var st=s1.substring(12);
closeButton.classList.remove(s1);
var num=parseInt(st);
// event.preventDefault();
console.log(input.value)
$.ajax({type: "POST",
url: "/update",
data: JSON.stringify({
id:num,
text:input.value,
//input is my textarea
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
}
//server side
app.post("/fetch",function(req,res)
{
//console.log(req.body);
// var id1=req.body.id;
const findInDB= Fruit.findOne({id:req.body.id},function (err, docs) {
console.log(docs);
res.send({text:docs.text});
});
});
app.post("/update",function(req,res)
{
Fruit.updateOne({id:req.body.id},
{text:req.body.text}, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated Docs : ", docs);
}
});
I tried debugging my code but couldn't reason out the contents of my console.
You are referencing input in your client side code, but I don't see it anywhere in the code. Can you check?
Update:
the textarea.value I'm sending as data to this ajax call is not the
same as the updated text of the text area.
I assume that you have an error in the code related to input. If you can add it to your answer, it will be easier to help you.

Make sure to wait until all Ajax calls are completed before displaying the result

I make do with a problem after several tries and I rely on you to find a solution.
What I want to do is to add in a table the number of viewers of a specific streamer via the twitch api.
So I do my ajax call well:
viewerCount(streamer){
let viewers = [];
let streamerList = streamer;
for (let i = streamer.length-1 ; i >=0 ; i--){
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/helix/streams?user_login='+streamerList[i]+'',
dataType:'JSON',
headers: {
"Client-ID": 'bgbezb2vov7jc4twxauhw3yh30ubbx',
"Authorization": "Bearer "+this.auth
},
success: function(data) {
viewers.push([i, streamerList[i], data['data'][0]['viewer_count']])
},
error: function(data){
console.log(data)
}
})
};
}
Then I push the result in my table and at the end when I do console.log I have the index, the name of the streamer and the number of viewers in my table.
The problem is that before I want to display the result, I'd like all the ajax calls to be completed before displaying. I tested with promise.all but unfortunately I didn't get anywhere.
Thank you in advance for your help.
using the condition below, you will be able to check if all calls are completed: (check code comments):
viewerCount(streamer){
let viewers = [];
let streamerList = streamer;
let completedCalls = 0; // init a new variable to base on
for (let i = streamer.length-1 ; i >=0 ; i--){
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/helix/streams?user_login='+streamerList[i]+'',
dataType:'JSON',
headers: {
"Client-ID": 'bgbezb2vov7jc4twxauhw3yh30ubbx',
"Authorization": "Bearer "+this.auth
},
success: function(data) {
viewers.push([i, streamerList[i], data['data'][0]['viewer_count']]);
completedCalls++; // increase completedCalls
},
complete: function() { // <-- here the new code
if(completedCalls === streamer.length) {
displayYourResult();
}
},
error: function(data){
console.log(data)
}
})
};
}

How to get nested JSON data values with a "data-" attribute?

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

Function is returning value before running inner actions

Using SharePoint's PreSaveAction() that fires when the Save button is clicked, I am trying to run checks and manipulate fields before the form is saved. If PreSaveAction() returns true, the form will be saved and closed.
function PreSaveAction() {
var options = {
"url": "https://example.com/_api/web/lists/getbytitle('TestList')/items",
"method": "GET",
"headers": {
"Accept": "application/json; odata=verbose"
}
}
$.ajax(options).done(function (response) {
var actualHours = response.d.results[0].ActualHours
var personalHours = $("input[title$='Personal Hours']").val();
var regex = /^\d*\.?\d+$/ // Forces digit after decimal point
if (personalHours && regex.test(personalHours)) { // Run if input is not blank and passes RegEx
if (response.d.results[0].__metadata.etag.replace(/"/g, "") == $("td .ms-descriptiontext")[0].innerText.replace("Version: ", "").split('.')[0]) {
// Run if item's data from REST matches version shown in form
addChildItem(id, title, personalHours, actualHours)
}
}
});
return true; // firing before request above begins
}
The function is returning as true before running the jQuery AJAX call which runs addChildItem() that manipulates fields within the form and posts relevant data to a separate list.
function addChildItem(id, title, personalHours, actualHours) {
$.ajax({
method: "POST",
url: "https://example.com/_api/web/lists/getbytitle('ChildList')/items",
data: JSON.stringify({
__metadata: {
'type': 'SP.Data.ChildListListItem'
},
ParentID: id,
Title: title,
HoursWorked: personalHours
}),
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json; odata=verbose",
},
success: function (data) {
console.log("success", data);
var actualHoursNum = Number(actualHours);
var personalHoursNum = Number(personalHours);
$("input[title$='Actual Hours']").val(actualHoursNum + personalHoursNum);
$("input[title$='Personal Hours']").val('');
// Input is getting cleared on save but shows previous number when form is opened again
},
error: function (data) {
console.log("error", data);
}
});
}
This is causing the form to accept the field value manipulations but only after the save and before the automatic closure of the form.
I need PreSaveAction() to wait until after addChildItem() is successful to return true but I'm not sure how to do this. I have tried using a global variable named returnedStatus that gets updated when addChildItem() is successful but the return value in PreSaveAction() still gets looked at before the jQuery AJAX call is ran.
How can I solve this?
I got a similar case by setting async: false to add user to group in PreSaveAction.
Original thread
<script language="javascript" type="text/javascript">
function PreSaveAction() {
var check = false;
var controlName = 'MultiUsers';
// Get the people picker object from the page.
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
if (!peoplePicker.IsEmpty()) {
if (peoplePicker.HasInputError) return false; // if any error
else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
else if (peoplePicker.TotalUserCount > 0) {
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
for (var i = 0; i < users.length; i++) {
console.log(users[i].Key);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(22)/users";
$.ajax({
url: requestUri,
type: "POST",
async: false,
data: JSON.stringify({ '__metadata': { 'type': 'SP.User' }, 'LoginName': '' + users[i].Key + '' }),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
console.log('User Added');
check = true;
},
error: function (error) {
console.log(JSON.stringify(error));
check = false;
}
});
}
}
} else {
console.log('No user');
}
return check;
}
</script>

Validate list item in REST

I have a function that will add list item using REST. But I want to validate a list item if its already exist on my list first before I add it. How will do it?
function addListItem() {
var title = $("#txtTitle").val();
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists/GetByTitle('Employee')/items";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.Data.EmployeeListItem' },
'EmployeeID': $("#txtEmpID").val(),
'Name': $("#txtName").val(),
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: onQuerySucceeded,
error: onQueryFailed
});
function onQuerySucceeded(sender, args) {
alert("Item successfully added!");
}
function onQueryFailed() {
alert('Error!');
}
};
You can use the OData query operations in SharePoint REST requests
use the $filter parameter in a Get operation to validate if the user exists in the list, using something like this:
$filter=Name eq '<UserName>'
An example:
siteUrl + "/_api/web/lists/GetByTitle('Employee')/items?$filter=Name eq 'John'
< UserName > is the textbox value
You can see a Response sample here:
http://services.odata.org/Northwind/Northwind.svc/Customers?$filter=ContactName%20eq%20%27Maria%20Anders%27
Just do a Get request and count the elements to know if the user exists
$.get("/_api/web/lists/getbytitle('Employee')/items?$filter=Name eq '<Name>'",function(e){
if($(e).find("entry").length > 0){
console.log("user exists");
}
})
You can see a Complete basic operations using SharePoint 2013 REST endpoints using JQuery/Javascript here:
https://msdn.microsoft.com/en-us/library/office/jj164022.aspx

Categories

Resources