How could i remove specific value from jquery array in jquery - javascript

I would like to remove specific value from an array , I have tried following script for delete value from an array but that not working.
HTML that contain values of an array
<input type="hidden" class="image_array" id="image_array" name="image_array[]" value="20200207050212.jpg,20200207050214.jpg">
So my array value is 20200207050212.jpg,20200207050214.jpg & I would like to remove 20200207050212.jpg from this array but not remove when i used following script.
1 Way
$(document).ready(function(){
$(document).on("click", '.profile_delete_image', function(){
var getImageName = $(this).attr('data-imagename');
console.log(getImageName)
var getImageArray =$('.image_array').val();
var checkValueExist = (getImageArray.indexOf(getImageName) > -1);
if(checkValueExist == true){
var itemtoRemove = getImageName;
getImageArray = $.grep(getImageArray, function(value) {
return value != itemtoRemove;
console.log(getImageArray)
});
}
});
})
2 Way
$(document).ready(function(){
$(document).on("click", '.profile_delete_image', function(){
var getImageName = $(this).attr('data-imagename');
console.log(getImageName)
var getImageArray =$('.image_array').val();
var checkValueExist = (getImageArray.indexOf(getImageName) > -1);
if(checkValueExist == true){
var itemtoRemove = getImageName;
getImageArray.splice(1,1);
}
});
})
NOte: when i do console.log it's return separated value like
2
0
2
0
0
2
0
7
0
5
0
2
1
2
j
p
g
So I don't want this i only want to remove given value from array and return an array with removed value.

Just use split() to make string as array.
var getImageName = '20200207050212.jpg' // Get your delete image name.
var getImageArray = [];
getImageArray = $('.image_array').val().split(',');
getImageArray = getImageArray.filter(e => e !== getImageName);
console.log(getImageArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="image_array" id="image_array" name="image_array[]" value="20200207050212.jpg,20200207050214.jpg">

Take a look at the snippet,
This is a simple example, here we have an array of images, when the button is clicked, it will get the images to delete from image_array.
Checks for if images_array has value, and convert it to array using .split(). Then iterate through the array and delete if the value in images array matched.
var $ = jQuery;
var images = ['20200207050212.jpg', '20200207050214.jpg', 'abc.jpg', 'image_123123.jpg'];
$('#delete_image').on('click', function() {
console.log('before delete', images);
var image_arr = $('#image_array').val();
image_arr = image_arr ? image_arr.split(',') : image_arr;
if (image_arr.length) {
image_arr.forEach(function(img) {
if (images.indexOf(img) !== -1) images.splice(images.indexOf(img), 1)
})
console.log('after delete', images);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<input type="hidden" class="image_array" id="image_array" name="image_array[]" value="20200207050212.jpg,20200207050214.jpg">
<button id="delete_image">Delete Image </button>

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

Removing a particular element from an array causing an issue

I have an array where if i delete a specific element it will remove it but later if i again remove another element the newly selected element will be deleted but previously deleted element will be present as shown in fig.
refer above picture at first i removed phone from a array and next i removed Account Disabled but in the second table the previously deleted element phone is still present
var selectedOpts = $('#lstBox1 option:selected');
var text = selectedOpts.val();
var colData = [];
this.firmData.forEach(function (dta) {
colData.push(dta.DisplayName);
})
const removeItem = value => colData.filter(item => item !== value)
console.table(removeItem(text))
console.log(text);
UPDATE
actual requirement
my requirement is i need to move data viceversa while moving i also want to remove it from array for now i can only append those values but i am not able to remove it from an array
1st column html
<div class="menu">
<select multiple="multiple" id='lstBox1' >
</select>
</div>
1st column JS code
self.firmData.forEach(function (data) {
$("#lstBox1").append($('<option class="items">').text(data.DisplayName).attr('value', data.DisplayName));
});
2nd column HTMl
<div class="menu">
<select multiple="multiple" id='lstBox2' >
</select>
</div>
2nd column JS code
self.data.forEach(function (data) {
$("#lstBox2").append($('<option class="items">').text(data.columnsexpo).attr('value', data.columnsexpo));
});
Button functions
"click #btnRight": function(e){
var selectedOpts = $('#lstBox1 option:selected');
var text = selectedOpts.val();
$('#lstBox2').append($(selectedOpts).clone())
this.data.push(columnsexpo: text);
}
"click #btnLeft": function(e){
var selectedOpts = $('#lstBox2 option:selected');
var text = selectedOpts.val();
$('#lstBox1').append($(selectedOpts).clone())
this.data.push(columnsexpo: text);
}
Not sure from the question what you're trying to do, but this should remove the item you want from the original array. Warning - may contain bugs / errors, however Array.prototype.splice removes items from an array.
var selectedOpts = $('#lstBox1 option:selected');
var text = selectedOpts.val();
var colData = [];
this.firmData.forEach(function (dta) {
colData.push(dta.DisplayName);
})
function findItem(item) {
return item == text;
}
colData.splice(colData.findIndex(findItem), 1);
console.table(colData)
console.log(text);
.filter don't remove item from array
To remove item in your array you can do
colData.splice(colData.indexOf(text), 1)
Live demo
var colData = ['a', 'b', 'c', 'd'];
const removeItem = value => {
let arr = colData.splice(colData.indexOf(value), 1);
return arr;
}
removeItem('a');
removeItem('d');
console.log(colData);

How to get a list of <a> href found in an element?

Given an html like this:
<tr>
<th style="padding-right:1em">Location</th>
<td>
<span class="location">Lower reaches of the Geum River, Korea</span>
</td>
</tr>
How do I get Geum_River and Korea?
This is what I am doing at the moment:
countryLinks = doSelect("Location").siblings('td').find('a').attr('href');
function doSelect(text) {
return $wikiDOM.find(".infobox th").filter(function() {
return $(this).text() === text;
});
}
function countryList() {
let pattern = new RegExp('\/wiki\/');
string = countryLinks;
countryListLinks = string.replace(pattern, '');
console.log(countryListLinks);
}
if (doSelect('Location').length > 0 && doSelect('Date').length > 0) {
countryList();
};
I am splitting /wiki/ from the string and it works but I am only getting the first one Geum_River while I would expect all of the <a>s href.
You were only selecting first <a> element .href, .attr() returns a single value. Also second condition at if && doSelect('Date').length > 0 is false given HTML at Question.
You can use .map() and .get() to return an array of <a> element .href values, then pass countryList function to Array.prototype.forEach() to iterate .href values.
The RegExp should also be adjusted to replace all characters up to and including "wiki" '^.+\/wiki\/'.
function doSelect(text) {
return $(".infobox th").filter(function() {
return $(this).text() === text;
});
}
countryLinks = doSelect("Location").siblings('td')
.find('a').map(function(i, el) {return el.href}).get(); // .attr('href');
// we can pass this function to `.forEach()` or `.map()`
function countryList(string) {
let pattern = new RegExp('^.+\/wiki\/'); // adjust `RegExp`
// string = countryLinks;
countryListLinks = string.replace(pattern, '');
console.log(countryListLinks);
}
// the second condition is `false` given HTML at Question
if (doSelect('Location').length > 0 /* && doSelect('Date').length > 0 */) {
countryLinks.forEach(countryList);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="infobox">
<tr>
<th style="padding-right:1em">Location</th>
<td>
<span class="location">Lower reaches of the Geum River, Korea</span>
</td>
</tr>
</table>
Your main issue is when you call countryLinks = doSelect("Location").siblings('td').find('a').attr('href'); specifically, when you call the last bit .attr('href'); which the docs state this of
Description: Get the value of an attribute for the first element in the set of matched elements.
So basically, you're getting a collection of the links then reducing that collection to just the first element and return it's href attribute.
Here is how I would do this using .map() instead:
var $wikiDOM = $('.some-container');
var links = $.map($wikiDOM.find('td a'),function(link, i){
return (link.href || '').replace(/^.*[\\\/]/, '');
});
console.log(links);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="some-container">
<table>
<tr>
<th style="padding-right:1em">Location</th>
<td>
<span class="location">Lower reaches of the Geum River, Korea</span>
</td>
</tr>
</table>
</div>
you can use jQuery each() to get all the hrefs in a array and then display then one by one using for loop.
Here is the code:
var hrefs = new Array();
jQuery('.location').find('a').each(function() {
hrefs.push(jQuery(this).attr('href'));
});
function countryList() {
let pattern = new RegExp('\/wiki\/');
for(var i=0; i < hrefs.length ; i++){
string = hrefs[i];
var countryListLinks = string.replace(pattern, '');
alert(countryListLinks);
}
}
countryList();
Complete Code, should look somthing like this:
function doSelect(text) {
return $wikiDOM.find(".infobox th").filter(function() {
return $(this).text() === text;
});
}
var hrefs = new Array();
jQuery('.location').find('a').each(function() {
hrefs.push(jQuery(this).attr('href'));
});
function countryList() {
let pattern = new RegExp('\/wiki\/');
for(var i=0; i < hrefs.length ; i++){
string = hrefs[i];
var countryListLinks = string.replace(pattern, '');
console.log(countryListLinks);
}
}
if (doSelect('Location').length > 0 && doSelect('Date').length > 0) {
countryList();
};
var hrefs = new Array();
jQuery('.location').find('a').each(function() {
hrefs.push(jQuery(this).attr('href'));
});
function countryList() {
let pattern = new RegExp('\/wiki\/');
for(var i=0; i < hrefs.length ; i++){
string = hrefs[i];
var countryListLinks = string.replace(pattern, '');
alert(countryListLinks);
}
}
countryList();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<tr>
<th style="padding-right:1em">Location</th>
<td>
<span class="location">Lower reaches of the Geum River, Korea</span>
</td>
</tr>
First of all, I'm going to pop an id onto your span element so that I can locate it easily in my script.
<span id="locations"
Next, I'm going to drop your implementation, and instead, iterate through the child elements of the span with id="locations". Next, I'll get the substring of the href of these elements that we want, and push them to an array.
var locations = document.getElementById("locations").getElementsByTagName('a');
var rawLocations = [];
for (i in locations) {
if (locations[i].href) {
var lastIndex = locations[i].href.lastIndexOf('/') + 1;
rawLocations.push(locations[i].href.substring(lastIndex));
}
}
Now, console.log(rawLocations); gives us what we want:
(2) ["Geum_River", "Korea"]
This was not as easy as I thought:-)
But here we go:
// cache the element, you could do QuerySelectorAll and iterate through the
// node list, but let's keep it simple
var ts = document.querySelector('a');
// This is caching the href attribute from the link
var garbage = ts.href;
// here you take the link and run the native string method
// to find the lastIndexOf, this is great if you suck at regex like myself
var n = garbage.lastIndexOf('/');
Here we extract only the part after lastIndexOf and cache it in "result"
var result = garbage.substring(n + 1);
alert(result);

How to get element by name with $key

PHP
//Here is my html for qty
<p>Qty : <input type="number" value="" name="qty<?php echo $key ?> onChange="findTotal()"/>
JS function
function findTotal() {
var arr = document.getElementsByName('qty');
...
document.getElementById('result').value = decimalPlaces(tot, 2);
}
My qty name needs key for post array. How do I get name inside js function to calculate quantities?
You can use
document.querySelector("input['name^='qty']").value
if you don't have jQuery.
This will select an input with name attribute starting with "qty". If you have multiple inputs which match the criteria you can select them all using
document.querySelectorAll("input[name^='qty']")
which will return a NodeList. You can read more about this here.
You can do something like this
var myVar = document.getElementsByTagName("somename");
//do something else
If you are using jquery
value = $( "input[name^='qtd']" ).val();
//it will pick the input wich name starts with 'qtd'
In pure DOM, you could use getElementsByTagName to grab all input elements, and loop through the resulting array. Elements with name starting with 'qty' get pushed to another array:
var eles = [];
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('qty') == 0) {
eles.push(inputs[i]);
}
}
Don't query the element by the name attribute's value. I'm not sure what's the purpose of the key and why you need it in the findTotal method, but here's an example:
<p>Qty : <input type="number" value="" name="qtyMyKey" onChange="findTotal(event)" /></p>
<script>
function findTotal(e) {
var inputEl = e.target,
inputName = inputEl.getAttribute('name'),
myKey;
if (typeof inputName === 'string') {
myKey = inputName.replace('qty', '');
}
console.log(myKey);
//var arr = document.getElementsByName('qty');
//document.getElementById('result').value = decimalPlaces(inputEl.value(), 2);
}
</script>
Here's the jsFiddle demo.

Couldn't append span element to array object in Angularjs/Jquery

Am struggling hard to bind an array object with list of span values using watcher in Angularjs.
It is partially working, when i input span elements, an array automatically gets created for each span and when I remove any span element -> respective row from the existing array gets deleted and all the other rows gets realigned correctly(without disturbing the value and name).
The problem is when I remove a span element and reenter it using my input text, it is not getting added to my array. So, after removing one span element, and enter any new element - these new values are not getting appended to my array.
DemoCode fiddle link
What am I missing in my code?
How can I get reinserted spans to be appended to the existing array object without disturbing the values of leftover rows (name and values of array)?
Please note that values will get changed any time as per a chart.
This is the code am using:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
Am giving another try, checking my luck on SO... I tried using another object to track the data while appending, but found difficult.
You should be using the scope as a way to bridge the full array and the tags. use ng-repeat to show the tags, and use the input model to push it into the main array that's showing the tags. I got it started for you here: http://jsfiddle.net/d5ah88mh/9/
function rdCtrl($scope){
$scope.dataset = [];
$scope.inputVal = "";
$scope.removeData = function(index){
$scope.dataset.splice(index, 1);
redoIndexes($scope.dataset);
}
$scope.addToData = function(){
$scope.dataset.push(
{"id": $scope.dataset.length+1,
"name": $scope.inputVal,
"value": 3}
);
$scope.inputVal = "";
redoIndexes($scope.dataset);
}
function redoIndexes(dataset){
for(i=0; i<dataset.length; i++){
$scope.dataset[i].id = i;
}
}
}
<div ng-app>
<div ng-controller="rdCtrl">
<div id="tags" style="border:none;width:370px;margin-left:300px;">
<span class="tag" style="padding:10px;background-color:#808080;margin-left:10px;margin-right:10px;" ng-repeat="data in dataset" id="4" ng-click="removeData($index)">{{data.name}}</span>
<div>
<input type="text" style="margin-left:-5px;" id="inptags" value="" placeholder="Add ur 5 main categories (enter ,)" ng-model="inputVal" />
<button type="submit" ng-click="addToData()">Submit</button>
<img src="../../../static/app/img/accept.png" ng-click="assign()" id="assign" style="cursor:pointer;display:none" />
</div>
</div>
<div id="status" style="margin-top:100px;"></div>
</div>
</div>

Categories

Resources