I have a working html form (in laravel) that is using a javascript call to employe Ajax.
Right now I'm using console log to make sure my click event shows the variables which it does.
However, because of how my values are below, I get multiple values in one variable and I'm wondering if there's a way to parse them into their own.
For example, in my form I have multiple values sharing table cells:
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
But when I log my variables I get
category: "categoryOne" //which is correct
detailColor: "123/Blue - Description"
productNumber: 123 - productOne
What I'd like to do is parse those and have it all as separate values like so:
category:"categoryOne"
detail: "123"
color: "Blue"
productNumber: "123"
productDescription: "productOne"
Is there a way to do that within my JS?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
I believe the simplest way is splitting your variables like this:
var detailColor = "123/Blue - Description";
var productNumber = "123 - productOne";
var first = detailColor.split(' - ');
var just_color = first[0].split('\/');
var detail = just_color[0];
var color = just_color[1];
var second = productNumber.split(' - ');
var product_number = second[0];
var product_description = second[1];
console.log(detail , color, product_number, product_description);
Related
I've page that contain the list button and search button.
index.php :
<li class="page-item" id="'.$i.','.$record_per_page.'"><a class="page-link" href="javascript:void(0);" >'.$i.'</a></li>
<input class="form-control" type="text" placeholder="insert your keyword ..." aria-label="Search" id="budget_keyword" name="<?=$record_per_page;?>">
script.js :
$(document).on('click','#table-content .page-item',function () {
var mode = this.id.split(',');
var page = mode[0];
var p = mode[1];
var keyword = $('#budget_keyword').map(function() {
return this.id.value;
});
$.ajax({
url: "paging.php",
method: "POST",
data: { page: page, p: p, keyword: keyword },
success: function (data) {
$('#table-content').html(data);
}
})
});
My Goals are :
When user click the li button, then it will pass 2 variables which containing values from #page-item and #budget_keyword id
I already got the value of #page-item from my script above, but for the #budget_keyword, it seems returning an object which i cannot understand below :
Object { length: 0, prevObject: Object(1) }
I just need the value from user input text inside searchbox (#budget_keyword)
Can someone give me an idea ?
sorry for my bad english
Seems like multiple inputs with same id="budget_keyword" exist in your HTML.Due to that keyword is not coming properly (or in other words to say map() not working).
You can use .next() to get desired keyword. Check below code:
$(document).on('click','#table-content .page-item',function () {
var mode = this.id.split(',');
var page = mode[0];
var p = mode[1];
var keyword = $(this).next('.form-control').val();
$.ajax({
url: "paging.php",
method: "POST",
data: { page: page, p: p, keyword: keyword },
success: function (data) {
$('#table-content').html(data);
}
})
});
Note:- if only one id="budget_keyword" exist in whole document,then directly do:
var keyword = $('#budget_keyword').val();
I am working on a Javascript that aims to return then manipulate an object from a clicked button. I am now stuck how can i get its object then process it on a post method. On my button I have this:
<button type="submit" name="submit" form="form-add" id="export-btn" class="btn btn-small" style="border-radius: 0;"><i class="fas fa-save"></i><span class="button-save"></span>Save</button>
and i have this javascript method:
<script type="text/javascript">
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');
...
// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};
// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h);
});
// Output the result
$EXPORT.text(JSON.stringify(data));
return data;
});
</script>
and on top of my page I have this:
if(isset($_POST['submit'])){
echo "Test";
// Process here the object
}
but How can i access those data, since $EXPORT.text(JSON.stringify(data)); output a JSON, that looks like this [{"id":"1","Val":"Sample","data":"Sample Date"}] on my paragraph tag.
You can't post data from paragraph.
Create hidden input in the form and assign the data to it.
$(this).append($("<input />", { name : "foo", value : data, type : "hidden" }))
So to cut this quick, here is what I am trying to do.
I have two JSON outputs and I am looping through all of the data, I can output the item name and website URL successfully, these are working. However, each job has a department_id and each department has an id. I can pass both sets of ids but I need to put the correct department with the job, so I need someway of cross-referencing the ids so the department is shown on the correct job.
Here is what I have so far
<script>
(function() {
const jobPositions = document.getElementById('jobPositions');
var jobs = $.ajax({
url : 'https://www.welcomekit.co/api/v1/external/jobs?access_token=redac&organization_reference=redac&websites=true&status=published',
dataType: 'json'
});
var jobDepartments = $.ajax({
url: 'https://www.welcomekit.co/api/v1/external/departments?access_token=redac&organization_reference=redac',
dataType: 'json'
});
$.when(jobs, jobDepartments).done(function(jobs, jobDepartments) {
var data1 = jobs[0];
var data2 = jobDepartments[0];
$.each(data1, function(i, item) {
var start = i++;
var jobDept = item.department_id;
var jobID = data2[i].id;
var JobDeptName = data2[i].name;
const dept = jobID === jobDept;
console.log(jobID, jobDept, dept);
if(start) {
$(jobPositions).append('\
<a target="_blank" href="'+ item.websites[1].url +'" class="jobPosition-item d-md-flex justify-content-between align-items-center flex-wrap">\
<div>\
<span class="jobPositions-name">' + item.name + '</span>\
</div>\
<div class="right right-info d-flex align-items-center">\
<span class="jobPositions-profession">' + JobDeptName + '</span>\
<div class="d-flex">\
<img src="/hubfs/www/about/white-icon-arrow.png" height="11" width="11" alt="arrow">\
</div>\
</div>\
</a>\
');
}
});
});
})();
</script>
The code here (I'll reference with comments)
//gets the department_id from item
var jobDept = item.department_id
//gets the department id from data2
var jobID = data2[i].id
//gets the name from each department to be used in the HTML
var JobDeptName = data2[i].name;
//This is to see whether both ids match, not sure if this is the right way to do this
const dept = jobID === jobDept;
//outputs everything
console.log(jobID, jobDept, dept);
The result I get is this:
Which displays this
This is incorrect as both of these jobs are under 10893 so not the right ID, it's also not showing all item responses I assume due too the undefined error but every job has a department.
I'm not sure what the best way to do this is, any suggestions welcome.
The error is here: var jobID = data2[i].id;. You apply index of data1 array to data2 array. It should be something like this.
var job = data2.find(d => d.id === item.department_id);
if(job)
var jobID = job.id;
I have a simple JavaScript function that I wrote:
function fireGENURL(a){
try{
var selectedFiles = $('.fileCheck:checked');
if(selectedFiles.length < 1 ){
alert("Please select at least one file.");
return false;
}
var fileID = $(selectedFiles[0]).attr('fileid');
/* var $fileChecks = $('.fileCheck:checked');
$fileChecks.each(function() {
var file = $(this).attr('fileid');
alert(file+"has been selected");
});
var count = $fileChecks.length;*/
$('body').pWin("open", {
x: 260,
y: 47,
height: 450,
width: 881,
title: "Generate URL",
skinMode:'dialog',
iframe:true,
url: "file/url/genurl.jsp",
data: {
nodeID:fileID
},
offResize:true,
offMove:true,
onTitle:false,
offBottom:true
});
}catch(e)
{
alert(e);
}
}
When I checked on tick box on any files and fire the GENURL button, the function above is called. Below is a screenshot of my screen:
And it calls genurl.jsp which retrives the fileID of the ticked checkbox.
GENURL.JSP:
<%
//grabs the file id of each file
long nodeID = Long.parseLong(request.getParameter("nodeID"));
//need to input logic to populate data on each row
int count = 0;
List files = fileFacade.list_items(nodeID);
for (Iterator rstltr = files.iterator(); rstltr.hasNext();) {
Fmedia fv = (Fmedia) rstltr.next();
Node nd = nodeFacade.get(fv.getNodeid(), false);
// Fmedia fm = fileFacade.get_file(fv.getNodeid());
count++;
%>
<tbody>
<tr>
<td width="5%">
<!-- Checkbox -->
<input type="checkbox" name="name1" />
</td>
<td>
<!-- No -->
</td>
<td width="28%">
<!-- Filename -->
<%=nd.getNodedesc()%>
</td>
</tr>
</tbody>
<%}
%>
As you can see nd.getNodedesc will return the file name and populate my jsp page table.
Anyway, it works if I checked one box and populate the table but how do I make it retrieve multiple file ID's if ticked more than once and populate the table?
I know this line var fileID = $(selectedFiles[0]).attr('fileid'); only retrieves one file ID but I can't figure how to get multiple files to pass it to the JSP page.
Edit
In my JavaScript function, under the code that is commented out, that snippet is able to retrieve multiple file id but it's unable to pass the value to data.
function fireGENURL(a){
try{
var selectedFiles = $('.fileCheck:checked');
if(selectedFiles.length < 1 ){
alert("Please select at least one file.");
return false;
}
cutFiles = new Object();
var count = 0;
for(var file in selectedItems){
var fileID = file.substring(0);
// post each selected fileID
cutFiles['fileID' + count] = fileID;
count += 1;
alert(fileID +" has been selected");
}
// var fileID = $(selectedFiles[0]).attr('fileid');
/* var $fileChecks = $('.fileCheck:checked');
$fileChecks.each(function() {
var file = $(this).attr('fileid');
alert(file+"has been selected");
});
var count = $fileChecks.length;*/
$('body').pWin("open", {
x: 260,
y: 47,
height: 450,
width: 881,
title: "Generate URL",
skinMode:'dialog',
iframe:true,
url: "file/url/genurl.jsp",
data: {
nodeID:fileID
},
offResize:true,
offMove:true,
onTitle:false,
offBottom:true
});
}catch(e)
{
alert(e);
}
}
Edit 4
String[] split = request.getParameter("nodeID").split(",",0);
for(int i=0;i<split.length;i++){
long file=Long.parseLong(split[i]);
}
Only way how you can pass array via HTML GET in JS using single data variable that I know, is to somehow stringify it:
var selectedFiles = [];
$('.fileCheck:checked').each(function() { selectedFiles.push($(this).attr('fileid')); });
var stringArray = JSON.stringify(selectedFiles);
$('body').pWin("open", {
x: 260,
y: 47,
height: 450,
width: 881,
title: "Generate URL",
skinMode:'dialog',
iframe:true,
url: "file/url/genurl.jsp",
data: {
nodeID:stringArray
},
offResize:true,
offMove:true,
onTitle:false,
offBottom:true
});
This will send a string that can be parsed into array with:
JSON.parse(request.getParameter("nodeID"));
See Fiddle example what output does it produce.
https://jsfiddle.net/h3Legzt6/1/
EDIT:
There are some limitations tho:
What is the maximum length of a URL in different browsers?
Other way how to do it is using local storage:
localStorage.setItem('IDs', JSON.stringify(selectedFiles));
and
JSON.parse(localStorage.getItem('IDs'));
This also has limitations but is limited to much more space, based on a browser default settings. Unfortunately this space is not guaranteed as users can configure how much space can localStorage take. What is the max size of localStorage values?
Also, be careful as mutiple tabs can interfere with this storage and including some call identification in storage name, unique for each tab name would be a good idea and provding this unique ID to JSP so it will be able to find it.
EDIT2:
To implement it into your code this should do:
function fireGENURL(a){
try{
var selectedFiles = $('.fileCheck:checked');
if(selectedFiles.length < 1 ){
alert("Please select at least one file.");
return false;
}
var filesList = [];
var $fileChecks = $('.fileCheck:checked');
$fileChecks.each(function() {
filesList.push($(this).attr('fileid'));
});
var count = $fileChecks.length;
var stringArray = JSON.stringify(filesList);
$('body').pWin("open", {
x: 260,
y: 47,
height: 450,
width: 881,
title: "Generate URL",
skinMode:'dialog',
iframe:true,
url: "file/url/genurl.jsp",
data: {
nodeID:stringArray
},
offResize:true,
offMove:true,
onTitle:false,
offBottom:true
});
}catch(e)
{
alert(e);
}
}
EDIT 3:
As per comments, it is also possible to generate a string of delimited numbers (ex.: 123,234) and split them in JSP and convert them to Long in loop.
EDIT 4:
This is just an attempt and syntax might be wrong, you got it almost there I think. You split, loop trough it and convert to Long and this long can be used with the rest of the code:
<%
String[] split = request.getParameter("nodeID").split(",",0);
for(int i=0;i<split.length;i++){
long file=Long.parseLong(split[i]);
//need to input logic to populate data on each row
int count = 0;
List files = fileFacade.list_items(file);
for (Iterator rstltr = files.iterator(); rstltr.hasNext();) {
Fmedia fv = (Fmedia) rstltr.next();
Node nd = nodeFacade.get(fv.getNodeid(), false);
// Fmedia fm = fileFacade.get_file(fv.getNodeid());
count++;
%>
<tbody>
<tr>
<td width="5%">
<!-- Checkbox -->
<input type="checkbox" name="name1" />
</td>
<td>
<!-- No -->
</td>
<td width="28%">
<!-- Filename -->
<%=nd.getNodedesc()%>
</td>
</tr>
</tbody>
<%}}
%>
I want to add toggle star functionality in my project. For which I'm calling this script on click. This code fails to compare value of starclass to the class defined in the string.
Here i m trying to add star/unstar functionality just like gmail messages to my project.
$(".mailbox-star").click(function (e) {
debugger;
e.preventDefault();
var $this = $(this).find("a > i");
var glyph = $this.hasClass("glyphicon");
var fa = $this.hasClass("fa");
var msgId = $("#MsgId").val();
var StarClass = $(".mailbox-star i").attr('class');
var StarStatus;
if (StarClass === "fa text-yellow fa-star-o") {
StarStatus = true;
} else {
StarStatus = false;
}
//var starstatus = document.getElementById('ReadstatusStarred');
if (glyph) {
$this.toggleClass("glyphicon-star");
$this.toggleClass("glyphicon-star-empty");
}
$.ajax({
url: "/Home/Starred",
type: "GET",
dataType: "json",
data: {
ChangeStarredStatus: StarStatus,
ChangeMessageId: msgId
},
success: function (status) {
if (status) {
alert(status);
if (fa) {
$this.toggleClass("fa-star");
$this.toggleClass("fa-star-o");
}
}
},
error: function () {
alert("starfailed1");
}
})
});
//HTML CODE
here i m fetching values from my controller using model .If I can send value of IsStarred parameter in my js code my problem will be sorted
<table class="table table-hover table-striped">
<tbody>
#{int count = 0;}
#foreach (var item in Model)
{
string[] dt = #item.DateTime.ToString().Split(' ');
<tr title="#item.DateTime" id="ReadMessage" class="#((item.IsRead != true) ? "row row-highlight" : "row")" >
<td><input type="hidden" value="#item.IsRead" id="Readstatus_#count"></td>
<td><input type="hidden" value="#item.IsStarred" id="ReadstatusStarred"></td>
<td><input type="hidden" id="MsgId" value="#item.MessageId" /></td>
<td><input type="checkbox"></td>
<td class="mailbox-star" ><i class="#((item.IsStarred==true)? "fa fa-star text-yellow":"fa text-yelow fa-star-o")"></i></td>
<td class="mailbox-name" id="Text1" onclick="location.href='#Url.Action("Read", "Home", new
{
NameRead = item.FullName,
SubjectRead = item.Subject,
BodyRead = item.Body,
DateRead = item.DateTime,
MessageIdRead= item.MessageId,
})'">
<a href="#" id="Name">
#item.FullName
</a>
</td>
<td class="mailbox-subject" id="Text1">
<b>#item.Subject</b>-
#if (item.Body == null || item.Body.Length == 0)
{
}
else
{
if (item.Body.Length >= 100)
{
#item.Body.Substring(0, 100)
}
else
{
#item.Body
}
}
</td>
<td class="mailbox-attachment"></td>
<td class="mailbox-date">
#dt[0]
</td>
</tr>
count++;
}
</tbody>
</table>
</div>
Try using jQuery's is() to check for classes instead
var StarStatus = $(".mailbox-star i").is('.fa, .text-yellow, .fa-star-o')
If I got your description right you wanna have something like gmail has, click to star a mail, click again to destar it?
It's hard to say what is broken without the HTML you are using but I would do this in the following manner:
When loading mails from back you have to set up class "starMarked" to starred mails depending on how you mark the starred mail in the data comming from back you would check if something is true or equal to some value and then .addClass("starMarked") to that element.
bind the .click(Function that does the logic below) to all elements that represent mail (list member, square, icon, depends on what you have in the UI)
A functionality of that click then checks if that mail is stared or not. Since the status is already represented with class no need to check through data pulled from the server or make an additional request to the server to get that email's status. This saves time and load on the server.
NOTE: You must be certain the request to change status on the server went through or your logic of toggling on front and status on backend might become inconsistent!
Toggle on front could be done numerous ways but simplest would be using the CSS class "starMarked" to represent it's starred and lack of it to signal it's not. It gives 2 birds with one stone (looks and logic). If you need to check the status you could use .hasClass("starMarked").
When toggling a class use .removeClass() to remove the class from the element