I have a list of checkboxes while selecting checkboxes i have to add the values to arrays and while unchecking i have to remove that from array.
following code am using.
but it is not deleting while unchecking
<tr><td class="tdstyleSelect"><input type="checkbox" name="joblist" onclick="toNfroVmps(this.id);" id="' + i + '" checked>
var toNfroVmps = function(id) {
if($('#' + id).is(':checked'))
elementIds.push(id);
else
delete elementIds[elementIds.indexOf(id)]
}
Use Array.splice (which is, btw, a native JS method):
var index = elementIds.indexOf(id);
if (index !== -1) {
elementIds.splice(index, 1);
}
You might consider using hashes (instead or a plain Array) to store your data: with each key corresponding to an ID, and value either true or false.
var elementIds = {
el1: true,
el2: true,
el3: false
// ...
};
This way adding/removing an element will be even more straight-forward:
elementIds[id] = $('#' + id).is(':checked'); // either true or false
... and you still will be able to process this hash as array, using various jQuery list comprehension functions. For example, that's how you collect ids of all the checked elements:
var checkedIds = $.grep(elementIds, function(el) { return el; });
You can use the splice method to remove array items.
var toNfroVmps = function(id)
{
if($('#' + id).is(':checked'))
elementIds.push(id);
else
{
// Select the index
var i = elementIds.indexOf(id);
// Check if the index exists, to prevent any errors that might happen
// If exists, delete
if(i !== -1)
elementIds.splice(i, 1);
}
}
Related
How can I pass values from an array from one event click to another with jQuery?
Here is an example of I want to do: the first click event adds or remove values from the array if the input checkbox is selected or not. In the second click I want to loop trough all the elements of this array.
var array=[];
$( "input" ).on( "click", function() {
var $input=$(this)
if($input.is(":checked")){
array.push($(this).val()); //append check box value to array if is selected
}
else{
array.pop($(this).val()); // remove check box value to array if is not selected
}
})
$('#cmd').click(function() {
for (i of array) {
console.log(array[i]); // loop trough all elements in array
...
});
Your code looks ok except two things. First for for (i of array). Using of will return actual value as i, but you are using value as index in array[i].
If you want use index then use for (let i = 0; i < array.length; i++) instead.
You can also use Array.prototype.forEach() but you can't break out of it's loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Second thing is that .pop() doesn't support parameter. Use code below instead of .pop()
var index = array.indexOf($input.val());
if (index > -1) {
array.splice(index, 1);
}
If your event handlers are in different scope and #cmd handler can't see the array. You might use this little bit bad solution for sharing the array between scopes :)
$("input").on( "click", function() {
var array = $("#cmd").data("arr") || [];
var $input= $(this);
var value = $input.val();
if($input.is(":checked")){
array.push(value); /
} else {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
}
$("#cmd").data("arr", array);
});
$('#cmd').click(function() {
var array = $(this).data("arr") || [];
for (let value of array) {
console.log(value); // loop trough all elements in array
}
});
I am using the values input by the user to perform this action.
Here is the full code: https://jsfiddle.net/7196dfyz/
This is part of the code where the elements are traversed, where I'm having trouble:
var lists = $ul.getElementsByTagName("li");
for (var i = 0; i < lists.length; ++i) {
if (lists[i] == value) {
$("ul").css("background-color","black");
}
}
The first input should take the value in some li
and the second input should take the respective parent ul class name.
I think this is what you're looking for. (Here is an updated jsfiddle):
function func() {
var key = $("#key").val();
var value = $("#entry").val();
var $ul = $("." + key);
var lists = $ul.find("li");
for (var i = 0; i < lists.length; ++i) {
console.log($(lists[i]).text(), value);
if ($(lists[i]).text() === value) {
$(lists[i]).css("background-color","black");
}
}
}
You have several issues:
$ul.getElementsByTagName is not a valid function. Because $ul at this point is a jQuery array-like object, it wont work. You'd need to do $ul[0].getElementsByTagName, or simply use jQuery's find() like my example above.
You're trying to compare lists[i] to value, which happens to be an HTML element. When comparing to a string, it will return <li>Say</li> which will never match anything you type in. Using $(lists[i]).text() should get you what you need.
$("ul").css("background-color","black");: You were setting every ul to black if a match was found. I assume you only want to match the one that was matched. $(lists[i]).css("background-color","black"); fixes this.
You can even simplify this entire function down to this:
function func() {
var key = $("#key").val();
var value = $("#entry").val();
$("." + key).find("li").filter(function() {
return $(this).text() === value;
}).css("background-color","black");
}
Broken down:
$("." + key): Find the ul that has the class of key.
.find("li") Find all list items within each unordered list found.
.filter(...) For each element in this list, and return to me only the items that match my criteria: $(this).text() === value.
And finally .css("background-color","black"): Set all the background colors to black of the list items that were returned from the filter() function.
Hello I can't find out how to delete a specific value from string when clicking on an element with the string value. its for my todo list.
if (window.localStorage.fullName !== undefined) {
alert('Your browser does not support localStorage');
} else {
$(function () {
console.log('localSorage compitability detected. proceeding...');
global vars & functions
var tdli = [];
add list items
$('#tdladd').click(function () {
$('.todolist ul ul').append("<li class='tdli'>" + $('#tdlinput').val() + "</li>");
tdli.push($('#tdlinput').val());
$('#tdlinput').val('');
var array = tdli + "";
localStorage.setItem('tdlis', array);
console.log(array);
$('#todolist').hide().fadeIn('fast');
});
remove list items
$('li').click(function () {
var itemtoRemove = $(this);
tdli.splice($.inArray(itemtoRemove, tdli), 1);
console.log(tdli);
});
$('#clearall').click(function () {
localStorage.clear();
location.reload();
});
load list items
var tdlitems = localStorage.getItem('tdlis');
var array = tdlitems.split(',');
tdli.push(array);
for (var i = 0; i < array.length; i++) {
array[i] + "<br>";
$('.todolist ul ul').append("<li>" + array[i] + "</li>");
};
console.log(array);
});
}
Assuming that tdli is a jQuery wrapped set (which itself is an array-like-object), it will have DOM nodes stored instead of another jQuery objects. That means, just go like
var itemtoRemove = this;
and you should be fine.
After you posted your complete code, we can see you're actually pushing string values into your tdli Array, but you try to .splice() objects respectively DOM nodes, which of course doesn't make any sense at all (comparing apples to oranges).
I have an array of object, that contain key value pair of columnNames.
when i check if a particular columnName exists it alwayz returns -1
Here is an sample http://jsfiddle.net/trLkt/6/, Help will b appriciated
You're searching for string values in the columnModel array, but you're storing objects in it (columnModel.push({'colName': $(this).text()});). $.inArray() cannot decide by itself to compare against the colName property of each array element, it simply compares the value you're searching for against each array element.
Two things you can do:
Add strings to the array instead of objects using .push (as suggested by #lanzz), then $.inArray will work as you expect.
Alternatively, if you do need to store objects within the array (if for example you need to have multiple properties within each object) you would need to iterate over each object and see if the colName already exists:
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
Then change your check from if(colExists === -1) to if(!colExists).
Example
$(function () {
$('#ddlMain').change(function (event) {
$('option:selected', $(this)).each(function () {
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
if(!colExists) {
columnModel.push({'colName': $(this).text()});
alert($(this).text() + ' added to columnModel');
}
});
});
});
I have a hidden field that stores all of the id's of images that have been uploaded for a specific post.
The hidden field HTML looks something like this:
<input type="hidden" id="post_images" name="post_images" value="1,2,3,4,5" />
When an image is deleted from the post, I need to remove it's image_id from that hidden field. So if I delete image_id 4 from the post, the hidden field needs to update to be value="1,2,3,5"
I'm open to changing the way I store the image_id's for the post to a different format if there is a better way of doing this.
While you could use this dirty regex:
$("#post_images").val(function(i, v) {
return v.replace( new RegExp('(?=(?:^|,))(,?)' + id + '(?=(?:,|$)),?'), '$1' );
});
Here's the fiddle: http://jsfiddle.net/43hhs/
A more sane way would be to use array splicing:
$("#post_images").val(function(i, v) {
var values = v.split(','),
i = $.inArray(id.toString(), values);
if ( i != -1 ) {
values.splice(i, 1);
return values.join(',');
}
else {
return v;
}
});
Here's the fiddle: http://jsfiddle.net/khHPq/
jsFiddle: http://jsfiddle.net/4Mwsu/15/
$(".imageRemove").click( function()
{
$(this).hide();
var values = $("#post_images").val().split(",");
var newValue = "";
for ( var i = 0 ; i < values.length ; i++ )
{
if ( $(this).attr("id") != values[i] )
{
newValue = newValue + values[i] + ",";
}
}
$("#post_images").val( newValue );
});
You might consider using jQuery's data method instead, which lets you store true arrays. If you need data to be passed in the value of the elements, you can convert back and forth at your convenience, such as in an .on('submit', ...) handler.
The following code is a bit cumbersome, but I think it communicates the idea.
$pi = $('#post_images');
$pi.data('values', $pi.val().split(',') );
// now .data('values') is a true JS array
console.log($pi.data('values').indexOf("3")); // 2
$pi.data('values').splice(2,1); // removes the third element
console.log($pi.data('values')); // ["1","2","4","5"]
$pi.val( $pi.data('values').join(',') );
console.log($pi.val()); // "1,2,4,5"
http://jsfiddle.net/mblase75/vx3XL/2/
using that, to me easiest way to go would be to have the value start and end in ',', then you can just do a
$("#post_images").val($("#post_images").val().replace("," + idtoremove + ",", ",")
var theVals = $(':input').val().split(','); //split the values into an array
var myVal = '4'; //this should be the ID of the element you want to remove
if($.inArray(myVal, theVals)){ //is the item in the array
index = theVals.indexOf(myVal); //if it is, then get the index position
theVals.splice(index, 1); //starting at the index of the element in the array, remove 1 element
$(':input').val(theVals); //update the input with the new array of IDs
}
console.log($(':input').val()); //general purpose to visualize this output
a working jsFiddle