How to remove elements from a selector - javascript

I'm struggling to get a piece of code to work but I'm not a jquery guy so please bear with me.
I have an outer DIV ($scope). It contains all kinds of inputs.
I find all the entries for each input type and filter them to get the ones with values. These are stored in $entries.
$inputs contains all the inputs regardless of type or status.
What I'm trying to do is remove $entries from $inputs to leave the difference.
It doesn't work, and at the moment I'm not getting any errors firing back, so nothing to go on.
My first thought is that jquery is unable to match the elements in one list with the other as it just holds an index, not the actual object. This could be totally wrong (please refer back to line 1).
Either way, I need to find a way of getting all elements and segegating them into 2 bits - those with values and those without.
All help appreciated.
function inputLoaded(isPostback) {
if (typeof Page_Validators !== "undefined") {
$scope = $(".active-step:first");
$inputs = $scope.find(inputs);
$cb = $scope.find(checkboxes).filter(":checked");
$rb = $scope.find(radios).filter(":checked");
$sb = $scope.find(selects).filter(function () { return $(this).val() !== "None"; });
$ta = $scope.find(textareas).filter(function () { return $(this).val(); });
$tb = $scope.find(textboxes).filter(function () { return $(this).val(); });
$entries = $cb.add($rb).add($sb).add($ta).add($tb);
// Do things with $entries here
// Get elements that have not got entries
$el = $inputs.remove($entries);
}
}

The not() method can take a jQuery object whose contents will be excluded from the jQuery object you apply it to. It looks exactly like what you're looking for:
// Get elements, excluding entries.
$el = $input.not($entries);

Related

Array not updating when using JQuery

I'm trying to splice an array in order to delete an object from my array. I'm using angular-formly to display the forms and AngularJs and JQuery in order to handle the data.
The JQuery
$(document).on("click", ".delete-me", function () {
var id = $(this).parent().find('input, select, textarea').attr('id');
var splitid = id.split("_")[3];
angular.element(document.getElementById('View2Ctrl')).scope().removeField(splitid);
$(this).closest('.formly-field').remove();
});
The reason for the split and is that formly wraps an id like formly_1_input_textField-1_0.
The Angular Function
$scope.removeField = function (id) {
for(var i=0;i<$scope.formFields.length;i++){
if($scope.formFields[i].key == id){
$scope.formFields.splice(id, 1);
console.log($scope.formFields.length);
$scope.currentId = i;
}
}
};
The console log is displaying the actual length of the array however I have {{formFields.length}} on the template and it does not update, as well as {{formFields}} still showing the data in the array. I suspect that JQuery updating the DOM isn't being watched by Angular and have tried calling $scope.$apply() manually to no avail.
You have a couple of logic errors in your function:
When you remove an item from the array, you increase i anyway, which means you'll miss out the next item if it's a match.
You're using id instead of i in the splice
That second one is probably the culprit, but once you'd fixed that, the first would have bitten you (unless the id values are unique, as the name implies; in which case, you should probably terminate the loop when you find it).
Updates:
$scope.removeField = function (id) {
var i=0;
while (i<$scope.formFields.length){ // Use a while loop
if($scope.formFields[i].key == id){
$scope.formFields.splice(i, 1); // Use i, not id
console.log($scope.formFields.length);
$scope.currentId = i;
// DON'T increment i here, you've removed the element
// Or if IDs are unique, just terminate the loop
} else {
++i;
}
}
};

jQuery grep return on Multidimensional Array

I am learning jQuery and am having issues trying to figure out how to select elements in a multidimensional array. I have a select list with database IDs and I want to set a var with the cost field in the database according to the id that selected. I have all the pieces except for translating the selected ID to a cost. Can someone please help me with getting this right please?
var rangeListData = [{"idrange_list":"1","range_cost":"0","target_range_name":"Self Only"},{"idrange_list":"2","range_cost":"1","target_range_name":"1 Space"},{"idrange_list":"3","range_cost":"2","target_range_name":"2 Spaces"},{"idrange_list":"4","range_cost":"3","target_range_name":"3 Spaces"},{"idrange_list":"5","range_cost":"4","target_range_name":"4 Spaces"},{"idrange_list":"6","range_cost":"5","target_range_name":"5 Spaces"}];
$('#slctPowerTarget').change(function () {
var targetID = $('#slctPowerTarget').val();
var cost $.grep(rangeListData, function(e) { return e.idrange_list == targetID }); // this is the line that is wrong
$('#spanTotalEffectsCost').text(cost);
});
If I put targetID in where cost is it lists fine. But when I try to look this up nothing happens. It is not right somehow and I am not sure what else to try. I think I get how idrange_list == targetID is supposed to match them but not sure how to call the related range_cost.
Thanks for any help you can offer! I read through the docs at jquery.com but can't seem to wrap my head around them.
You can do this :-
// Get the Multidimensional Array first
var data = $.grep(rangeListData, function (e) {
return e.idrange_list === targetID
});
// Get the range cost from the array
var cost = data[0].range_cost;
// Check the value in console for debugging purpose
console.log(cost);
Here is the final code. I also added an IF clause in there in case they select the default setting. This way it will reset instead of tossing an error and keeping page calculations working no matter if they change the drop downs or go back to "Select..."
$('#slctPowerRange').change(function () {
var rangeID = $('#slctPowerRange').val();
if (rangeID > 0) {
var rdata = $.grep(rangeListData, function (e) {
return e.idrange_list === rangeID
});
var rcost = rdata[0].range_cost;
}
else {
var rcost = 0 ;
}
$('#hdnRangeCost').val(rcost);
});

breaking out of an underscore each

I am trying to find a model within a collection with an attribute equal to html select option value.
<div id="hospital-details">
<select name="hospitalnames">
<option><%- model.get('name') %></option>
</select>
</div>
whenever hospital name is changed, jquery change callback is triggered to find locationModel with selected option value as attribute value as shown below,
$('select[name="hospitalnames"]').change(function() {
var name = $(this).val();
locationListCollection.each(function(locationModel) {
if ($.trim(locationModel.get('name')) == $.trim(name)) {
that.locationModel = locationModel;
return false; // control is returned to underscore.min.js
}
});
});
console.log(that.locationModel); // this is not being displayed at all
After the locationModel with an attribute is found, I am unable to come out the loop. Any help ? At this moment I have looked into
this but without success.
You're using the wrong method if you're searching for the first match. Collections have lots of Underscore methods mixed in, in particular they have find mixed in:
find _.find(list, iterator, [context])
Looks through each value in the list, returning the first one that passes a truth test (iterator), or undefined if no value passes the test.
Something like this:
var name = $.trim($(this).val());
that.locationModel = locationListCollection.find(function(locationModel) {
return $.trim(locationModel.get('name')) == name;
});
and if the names in your model are pre-trimmed and nice and clean, then you could use findWhere:
findWhere collection.findWhere(attributes)
Just like where, but directly returns only the first model in the collection that matches the passed attributes.
like this:
var name = $.trim($(this).val());
that.locationModel = locationListCollection.findWhere({ name: name });
BTW, this:
console.log(locationModel);
won't give you anything because locationModel and that.locationModel are different things.
You can always go oldschool.
$('select[name="hospitalnames"]').change(function() {
var name = $(this).val();
for (var i = 0; i < locationListCollection.length; ++i) {
var locationModel = locationListCollection.models[i];
if ($.trim(locationModel.get('name')) == $.trim(name)) {
that.locationModel = locationModel;
break;
}
}
});
Try this,
var name = $(this).val();
var flag=true;
locationListCollection.each(function(locationModel) {
if (flag && $.trim(locationModel.get('name')) == $.trim(name)) {
that.locationModel = locationModel;
flag=false;
//return false;// to break the $.each loop
}
});
The short is no.
If you take a look at underscore's source you'll see that they use a breaker object to quickly stop a .each() but that is only available internally.
I would not recommend this but you could always modify the source to expose this breaker object (see baseline setup in the annotated source
http://underscorejs.org/docs/underscore.html). Then you would just return this object instead of returning false. But you would probably need to remove the native forEach call to keep the behaviour consistent. So it's not worth it!
_.each(function(arr) {
if(condition) {
return _.breaker; // Assuming you changed the source.
}
});
Since you are searching for a single item instead of .each() use:
var locationModel = _.find(arr, function(item) {
return $.trim(locationModel.get('name')) == $.trim(name);
));

How to check if two jQuery selectors have selected the same element

Is there a way for me to progamatically determine if two jQuery selectors have selected the same exact element? I am trying to loop over a set of divs and skip one of them. What I would like is something like this:
var $rows, $row, $row_to_skip;
$rows = $('.row-class')
$row_to_skip = $('#skipped_row')
$.each($rows, function (id, row) {
$row = $(row);
if (!$row == $row_to_skip) {
// Do some stuff here.
};
});
You can pass jQuery objects into .not():
$rows.not($row_to_skip).each(function() {
...
});
You can use .is()
if (!$row.is($row_to_skip)) {
// Do some stuff here.
};
You can compare the actual DOM element selected by jQuery:
var row_to_skip = $row_to_skip.get(0);
$.each($rows, function (id, row) {
if (row !== row_to_skip) {
// Do some stuff here.
}
});
Two jQuery objects will always be different from each other, even if they select the same elements (just like two empty objects are different).
However in your case, instead of comparing inside the loop, it's cleaner to just remove the element from the set:
$('.row-class').not("#skipped_row").each(function() {
// do stuff
});

Build a switch based on array

I want to create a Javascript switch based on an array I'm creating from a query string. I'm not sure how to proceed.
Let's say I have an array like this :
var myArray = ("#general","#controlpanel","#database");
I want to create this...
switch(target){
case "#general":
$("#general").show();
$("#controlpanel, #database").hide();
break;
case "#controlpanel":
$("#controlpanel").show();
$("#general, #database").hide();
break;
case "#database":
$("#database").show();
$("#general, #controlpanel").hide();
break;
}
myArray could contain any amount of elements so I want the switch to be created dynamically based on length of the array. The default case would always be the first option.
The array is created from a location.href with a regex to extract only what I need.
Thanks alot!
#Michael has the correct general answer, but here's a far simpler way to accomplish the same goal:
// Once, at startup
var $items = $("#general,#controlpanel,#database");
// When it's time to show a target
$items.hide(); // Hide 'em all, even the one to show
$(target).show(); // OK, now show just that one
If you really only have an array of selectors then you can create a jQuery collection of them via:
var items = ["#general","#controlpanel","#database"];
var $items = $(items.join(','));
Oh, and "Thanks, Alot!" :)
I think you want an object. Just define keys with the names of your elements to match, and functions as the values. e.g.
var switchObj = {
"#general": function () {
$("#general").show();
$("#controlpanel, #database").hide();
},
"#controlpanel": function () {
$("#controlpanel").show();
$("#general, #database").hide();
},
"#database": function () {
$("#database").show();
$("#general, #controlpanel").hide();
}
}
Then you can just call the one you want with
switchObj[target]();
Granted: this solution is better if you need to do explicitly different things with each element, and unlike the other answers it focused on what the explicit subject of the question was, rather than what the OP was trying to accomplish with said data structure.
Rather than a switch, you need two statements: first, to show the selected target, and second to hide all others.
// Array as a jQuery object instead of a regular array of strings
var myArray = $("#general,#controlpanel,#database");
$(target).show();
// Loop over jQuery list and unless the id of the current
// list node matches the value of target, hide it.
myArray.each(function() {
// Test if the current node's doesn't matche #target
if ('#' + $(this).prop('id') !== target) {
$(this).hide();
}
});
In fact, the first statement can be incorporated into the loop.
var myArray = $("#general,#controlpanel,#database");
myArray.each(function() {
if ('#' + $(this).prop('id') !== target) {
$(this).hide();
}
else {
$(this).show();
}
});
Perhaps you're looking for something like this? Populate myArray with the elements you're using.
var myArray = ["#general","#controlpanel","#database"];
var clone = myArray.slice(0); // Clone the array
var test;
if ((test = clone.indexOf(target)) !== -1) {
$(target).show();
clone.splice(test,1); // Remove the one we've picked up
$(clone.join(',')).hide(); // Hide the remaining array elements
}
here you dont need to explicitly list all the cases, just let the array define them. make sure though, that target exists in the array, otherwise you'll need an if statement.
var target = "#controlpanel";
var items = ["#general","#controlpanel","#database"];
items.splice($.inArray(target, items), 1);
$(target).show();
$(items.join(",")).hide();
items.push(target);

Categories

Resources