How to remove first comma when pushing inside input value with split(',')? - javascript

I have an issue with split() function, I have input in which I push ids that I'm getting through mapping objects.
My HTML:
<input class="custom-img-id" name="custom-img-id" type="hidden" value="" />
My JS:
frame.on( 'select', function() {
var imgIdInput = $( '.custom-img-id' );
var attachments = frame.state().get('selection').map(function( a ) {
a.toJSON();
return a;
}),
thesamepicture = false,
i;
for (i = 0; i < attachments.length; ++i) {
imgContainer.append('<img src="' + attachments[i].attributes.url + '"/>');
imgIdInput.val().split(",").push( attachments[i].id );
}
imgIdInput.val( imgIdInput.val().split(",").join() );
});
If for example I have two object with ids 100 and 101, I will get inside input value this:
value=",100,101"
How to remove first comma? I think I'm doing something wrong.

The issue is probably that "".split(",") gives you [""], not an empty array.
I'd suggest splitting the string once prior to the loop (handling the issue with ""), adding to the resulting array, and then converting it back to a string once at the end, see *** comments:
frame.on( 'select', function() {
var imgIdInput = $( '.custom-img-id' );
var attachments = frame.state().get('selection').map(function( a ) {
a.toJSON();
return a;
}),
thesamepicture = false,
i;
// *** Get the current IDs as an array
var val = imgIdInput.val().trim();
var ids = val ? imgIdInput.val().split(",") : [];
for (i = 0; i < attachments.length; ++i) {
imgContainer.append('<img src="' + attachments[i].attributes.url + '"/>');
// *** Add to the array
ids.push(attachments[i].id);
}
// *** Save the IDs in the hidden input
imgIdInput.val(ids.join());
});

you can use replace
imgIdInput.val( imgIdInput.val().split(",").join().replace(",","") );
console.log(",100,101".replace(",","")) // "100,101"

You need to use split, filter and join function of the array & String to get the expected output.
var value=",100,101"
value = value.split(",")
const finalValue = value.filter(tmp =>{
return tmp !== ''
})
console.log(finalValue.join(","));

Related

jQuery looping array to display each element at new line

get all selected checkbox value and display them
wanted to separate each element in the array into new line
$('#generate').on('click', function() {
var array = [];
$("input:checked").each(function() {
array.push($(this).val());
});
$("#selectedSubject").text(array+'<br>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
ok so i fixed it myself
on last line i kept using .text instead of .html thats what made me failed oof
$('#generate').on('click', function() {
var array = [];
$("input:checked").each(function() {
array.push($(this).val());
});
let text = "";
for (let i = 0; i < array.length; i++) {
text += array[i] + "<br>";
}
$("#selectedSubject").html(text);
use each agian to iterate over the new array
ie:
$.each(array, function( index, value ) {
$("#selectedSubject").append( value );
});

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

javascript loop form values by name then element id

I have loop going though form values, it is working fine throwing out the values based on the input name. But I would also like to be able to target by specific element id.
This is an example form:
_inputFields: function() {
var rows = [];
for(var i = 1; i <= 12; i++) {
var placeHolder = 'Intro text line ' + i;
var inputID = 'inputIntroText ' + i;
rows.push(<input type="text" className="form-control input-size-lg" name="formInput" id="inputText" placeholder={placeHolder}/>);
rows.push(<input type="text" className="form-control input-size-lg" name="formInput" id="inputTime" placeholder={placeHolder}/>);
}
So I can loop through and grab everything by name i.e. 'formInput' but how can I then grab formInput[inputText] and formInput[inputTime]?
This is my current loop through the values :
// gather form input
var elem = document.getElementsByName('formInput');
console.log(elem);
// Build the object
var obj = {
"DataObject": {
"user": {
"-name": "username"
},
"contentFile": {
"-filename": "Breaking_News",
"lock": {
"-fileIsBeingEdited": "false"
},
"content": {
"line": []
}
}
}
};
var line = obj.DataObject.contentFile.content.line;
for (var i = 0; i < elem.length; i++) {
if (elem[i].value != '') {
line.push({
"-index": i,
"-text": elem[i]['inputText'].value,
"-time": elem[i]['inputTime'].value
});
}
};
If I try:
"-text": elem[i]['inputText'].value,
"-time": elem[i]['inputTime'].value
I get the error: Cannot read property 'value' of undefined
This errors because elem[i]['inputText'] is undefined. This is because you are trying to lookup the inputText property of the element, which doesn't exist.
elem is an array, so I'd recommend using something like filter.
"-text": elem.filter(function(item) {
return item.id === 'inputText';
})[0].value;
Also, you should remove the for loop or you will get a duplicate line.
function getElementById(elems, id){
return elems.filter(function(item) {
return item.id === id;
})[0];
}
var line = obj.DataObject.contentFile.content.line;
line.push({
"-text": getElementById(elem, 'inputText').value,
"-time": getElementById(elem, 'inputTime').value
});
Here's an example jsfiddle.
You can use elem[i].id:
var line = obj.DataObject.contentFile.content.line;
for (var i = 0; i < elem.length; i++) {
if (elem[i].value != '') {
line.push({
"-index": i,
"-text": elem[i].id
// Since you are looping through the inputs, you will get the `inputTime` in the 2nd iteration.
});
}
};

jQuery plugin DataTables: How to highlight the current search text?

I have started using the DataTables plugin (v1.6.2) for jQuery(v1.4.2), and I would like to ask you if you know a settings or a plugin that allow me to highlight the text used in search textbox on the filtered rows.
Thank you in advance
I would have to suggest the highlight plugin :)
I'm using this in about the same scenario right now, it's given me no issues thus far.
The usage is pretty simple:
$("#myTable").highlight($("#searchBox").val());
Just put the highlight CSS class in your stylesheet styles like you want and that's it:
.highlight { background-color: yellow }
I know that this question is now over 6 years old and the answers here may helped you at the time of asking. But for people still searching for this, there is a new plugin to integrate mark.js – a JavaScript keyword highlighter – into DataTables: datatables.mark.js.
Usage is as simple as:
$("table").DataTables({
mark: true
});
Here is an example: https://jsfiddle.net/julmot/buh9h2r8/
This is the cleanest way and also gives you options none of the given solutions offers you.
There's now an official DataTables blog article available.
You can use this function by coping this content :
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(oSettings.aoPreSearchCols[i].sSearch);
}
}
}
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++) {
regRules += "|("+ regRulesSplit[i] +")";
}
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
if (aData[j]) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
this.innerHTML = aData[j].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
this.innerHTML = aData[j];
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
inside :
dataTables.search-highlight.js
an call it like this example:
<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.search-highlight.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#example').dataTable();
oTable.fnSearchHighlighting();
} );
</script>
and add this code to you css file:
.filterMatches{
background-color: #BFFF00;
}
<link href="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.js"></script>
$("#tableId").dataTable({
mark: true
});
You can use the following add on
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
// Initialize regex cache
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
// searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
var searchTxt = $('input[type="search"]').val();
// console.log("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(searchTxt);
}
}
}
// Create the regex built from one or more search string and cache as necessary
/*if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
}
var regex = cache[sSregex];
}*/
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++) {
regRules += "|("+ regRulesSplit[i] +")";
}
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
// console.log("data "+ aData[j] + " j " + j);
// console.log("data 1 "+ nRow);
if (aData) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
//console.log("here :: "+$(this).text());
this.innerHTML = $(this).text().replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
this.innerHTML = $(this).text();//aData[j];
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
This solution is working for me.
Note: Currently it does not support individual column filtering, but you just have to uncomment following in the code.
searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
I have tested this with datatables 1.10.2 and jquery 1.9.2 version.
This add on have better feature for highlighting search text. if you have created datatable in a dialog , then on dialog reopen you need to reinitialize datatable.
In DatatableHighlighter.js
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
// Initialize regex cache
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
// searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
var searchTxt = $('input[type="search"]').val();
// console.log("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(searchTxt);
}
}
}
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++) {
regRules += "|("+ regRulesSplit[i] +")";
}
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
//cache[sSregex] = new RegExp(regRules+"", 'ig');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
if (aData) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
//For removing previous added <span class='filterMatches'>
var element = $(this);//convert string to JQuery element
element.find("span").each(function(index) {
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
}).remove();
var newString = element.html();//get back new string
this.innerHTML = newString.replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
//For removing previous added <span class='filterMatches'>
var element = $(this);//convert string to JQuery element
element.find("span").each(function(index) {
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
}).remove();
var newString = element.html();
this.innerHTML = newString;//$(this).html()//$(this).text();
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
and call it like this ....
$("#button").click(function() {
dTable = $('#infoTable').dataTable({"bPaginate": false,"bInfo" : false,"bFilter": true,"bSort":false, "autoWidth": false,"destroy": true,
"columnDefs": [
{ "width": "35%", "targets": 0 },
{ "width": "65%", "targets": 1 }
]});
$(".dataTables_filter input[type='search']").val('');
$("span[class='filterMatches']").contents().unwrap();
dTable.fnSearchHighlighting();
$("span[class='filterMatches']").contents().unwrap();
$("#AboutDialog").dialog('open');
});

Get Next and Previous Elements in JavaScript array

I have a large array, with non-sequential IDs, that looks something like this:
PhotoList[89725] = new Array();
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
PhotoList[89726] = new Array();
PhotoList[89726]['ImageID'] = '89726';
PhotoList[89726]['ImageSize'] = '234';
PhotoList[89727] = new Array();
PhotoList[89727]['ImageID'] = '89727';
PhotoList[89727]['ImageSize'] = '345';
Etc....
I'm trying to figure out, given an ID, how can I can get the next and previous ID... So that I could do something like this:
<div id="current">Showing You ID: 89726 Size: 234</div>
Get Prev Get Next
Obviously, if we're at the end or beginning of the array we just a message...
Why don't you add properties 'Prev' & 'Next' to that array?
PhotoList[89725] = new Array();
PhotoList[89725]['Prev'] = 89724;
PhotoList[89725]['Next'] = 89726;
PhotoList[89725]['ImageID'] = '89725';
PhotoList[89725]['ImageSize'] = '123';
This is just 'doubly-linked list' data structure.
Based on your example the IDs are sequential...
This is another way of writing your example. new Array() really isn't what you should be using because those are objects you are creating. Also, I left the numbers as strings, but I'm not sure why you would want to do that. You could add next and prev like kuy suggested
PhotoList[89725] = {ImageID: '89725',
ImageSize: '123'};
PhotoList[89725] = {ImageID: '89726',
ImageSize: '234',
Next: '89727',
Prev: '89725'};
PhotoList[89725] = {ImageID: '89727',
ImageSize: '345'};
All of these are accessible just like your other structure.
There's really no way other than to iterate through the possible ids sequentially until you find one which has an entry in your array. For example:
function findClosest(arr, id, increasing) {
var step = increasing ? 1 : -1;
for(var i=id+step; i>=0 && i<=max_id; i+=step)
if( arr[id] )
return id;
}
Obviously, this approach requires that you keep track of the max_id so that you don't iterate forever; here I assume that it's a global variable, but you might want to make it a parameter to the findClosest function. You'd call this function like so:
var prev = findClosest(arr, id, false);
var next = findClosest(arr, id, true);
I agree with the rest quotes you should be using objects not an array. Also make sure you create new arrays using the literal notation and not the new keyword with built in types. The new keyword is bad news and you could clobber the global object. Check out JSLint.
var a = new Array(); //bad dont use
var a = []; //this is the best way to create a new array
var o = {}; //create new objects like this
As for the problem at hand. Why not write a simple container that has its own internal counter?
function PhotoListContainer(PhotoList)
{
if(PhotoList === undefined)
throw("no photo list");
this.counter = 0;
var self = this;
this.current = function(){
return PhotoList[self.counter];
};
this.next = function(){
return PhotoList[self.counter + 1];
};
this.prev = function(){
return PhotoList[self.counter - 1];
};
// You could even write a function that loops each value from the current counter :)
this.each_from_counter = function(callback){
for(var i = self.counter; i < PhotoList.length; i++)
{
callback(PhotoList[i], i);
self.counter++;
}
};
}
//use
var pc = new PhotoListContainer(PhotoList);
pc.counter = 500;
pc.next(); //returns the 501st object
pc.prev(); //returns the 499th object
pc.each_from_counter(function(photo, index){
photo.somehting;
});
No arrays at all are better..
images = {
0: {
size: 12345, /* dont realy need as you can use JS to mesure the size. */
title: "day 1 on holiday"
},
1: {
size: 13549, /* dont realy need as you can use JS to mesure the size. */
title: "day 2 on holiday"
},
2: {
size: 16548, /* dont realy need as you can use JS to mesure the size. */
title: "day 3 on holiday"
},
}
for(x in images){
/* x = "the id of the image." */
url[] = "/images/" + x + ".png";
title[] = images[x].title;
size[] = images[x].size;
console.log("File: " + url[x] + " , Title: " + title[x] + " , Size: " + size + "bytes")
}
var sibNum = 0;
var sibList = [];
var prevSiblingID = false;
for (n in w) {
sibNum++;
sibList[n] = {
title : n,
prevSiblingID : prevSiblingID
};
if (prevSiblingID) {
sibList[prevSiblingID].nextSiblingID = n;
}
prevSiblingID = n;
};
sibList[prevSiblingID].nextSiblingID = false;
you can use grep function and calculate prev or next item of specified array:
object = $.grep(data, function(e) {
if(e.id == yourId) {
return data[data.indexOf(e) + 1]; // or -1 for prev item
}
});
i think your image list will come from DB so you may can try this code, this code is working for me.
<?
$prev="";
$next="";
$cur=0;
$i=0;
$pid=$_GET['pid'];
while($rowcon=mysql_fetch_assoc($result))
{
$arr[$i]=$rowcon['pid'];
if($rowcon['pid']==$pid)
{
$cur=$i;
}
$i++;
}
if($cur<$num_rows)
$next=$arr[$cur+1];
else
$next="";
if($cur>0)
$prev=$arr[$cur-1];
else
$prev="";
echo $prev." ".$cur." ".$next;
?>

Categories