Unable to set selected value within for loop - javascript

I'm having trouble changing the selection of a dropdown within a for loop.
Here is my code:
var costbases = $('[id$="cost_basis"]');
costbases.each(function() {
var costoption = $('option:selected', this).attr('value');
if ( costoption == '2' ) {
$('this option[value="0"]').prop('selected', true);
}
});
I'm pretty sure this selector is the problem, but I can't figure out the correct syntax:
$('this option[value="0"]')

You can use find() method to find the children and eq() to get the child with the index:
$(this).find('option[value="0"]').eq(0).prop('selected', true);

Related

How to use jQuery to select deeply nested elements created dynamically with javascript

So I have an object in my code and I use js to add the properties of the object to an array named rec based on users interaction. then I use a function named unRec to get unique elements of the array. Then I add the values returned by unRec to the HTML. Then I use jquery to wrap each of the values in anchor tags. So the code is basically like this
obj= {
0: "<span>module1</span>",
1: "<span>module1</span>",
2:"<span>module1</span>",
3:"<span>module2</span>",
4:"<span>module2</span>",
5:"<span>module3</span>",
6:"<span>module3</span>",
7:"<span>module3</span>",
8:"<span>module3</span>",
9:"<span>module4</span>"
}
function unRec(arr){
preRec = [];
for (j of arr){
if (preRec.indexOf(j)=== -1) {
preRec.push(j);
}
}
return (preRec);
}
Recom.innerHTML = unRec(rec);
$('#congrat #recom span').wrap('')
Now am unable to select the created anchors. Hence this function doesn't work
$('#congrat #recom .disp').click(function(e) {
var url = $(this).attr('href') + '#' + $(this).text();
$('#module').html('loading...).load(url); e.preventDefault();
});
I have tried to use find to select the anchors but it still doesn't work. This is the test
var t = $('#congrat #recom').find ('a').length;
console.log(t);
The HTML is basically like this:
<div id="congrat">
<span id="recom"></span>
</div>
<div id="module">click on one of the modules above<div>
Please provide a solution to select the created anchors. Thanks in advance

Unable to click an element on element all

Unable to click on element all method. I am getting Object Object has no method filter. While researching I found out that it has to do with some strings. Please advise. Thanks
var sflag = $('a[ng-click="flagPhoto()"]');
browser.wait(EC.elementToBeClickable(sflag), 30000, "not clickable");
$('a[ng-click="flagPhoto()"]').filter(function(elem, index) {
return elem.getText().then(function(text) {
return text === 'flag for abuse';
});
}).then(function(filteredElements) {
expect(filteredElements[0].isPresent()).toBe(true);
filteredElements[0].click();
});
You are not selecting multiple elements with this selector. Only the first found element will be selected:
$('a[ng-click="flagPhoto()"]').filter...
Instead, use this:
$$('a[ng-click="flagPhoto()"]').filter

Compare Elements via jQuery

I'm in a situation where I want to check if two elements (one is clicked and another one a reference) are the same, what I'm trying to do is:
$("#process li").click(function() {
currentElement = $(this);
referenceElement = $("#process li:first-child");
if (currentElement === referenceElement) {
$(".mark").removeClass("mark");
$(this).addClass("mark");
}
});
So what I want is to check if the clicked <li> is the first child of the ul#process and if so first remove a .mark class from another element and then add it to the clicked one. I don't get any working result - ideas anyone?
UPDATE:
Thanks you very much! This is my solution:
$("#processlist li").click(function() {
currentElement = $(this);
if (currentElement.is('li:first-child')) {
$(this).addClass("mark");
}
});
Now if I click on a , if it is the first child of this list, the class .mark is added - sweet!
Comparing objects in JS is very troublesome. The simplest way is to just pick a few key properties and compare those, eg:
if (currentElement.prop('id') === referenceElement.prop('id') {
// rest of your code...
}
However, given your use case you could use is:
if (currentElement.is('#process li:first-child')) {
// rest of your code...
}
Example fiddle
You need to extract the DOM element from the jQuery object. You can use the get method of jQuery for this.
e.g. if( currentElement.get( 0 ) === referenceElement.get( 0 ) )

How to remove empty elements from a form in ember, when saving/submitting?

Let's say I have an action in my controller like:
actions: {
save: function() {
var self = this;
this.get('model').save().then(function() {
self.transitionToRoute('surveys');
}, $.noop);
}
The model "hasMany" elements of type "element" (another model, with just a field "title"), that I can access from the controller as:
var elements = this.get('elements');
I want to remove the elements with empty title before I save. I've tried iterating over the "elements" with forEach and filter, but none of my approaches have worked so far.
Any suggestions? Thank you! :)
The problem was residing in the way I was deleting the elements.
Instead of calling destroyRecord() on the elements, the solution is to call removeObject() on the elements array, with the element we want to remove as an option.
Such as:
var elements = this.get('elements');
elements.forEach(
function (element) {
if(element && ! element.get('title')){
elements.removeObject(element);
}
});

How to clear a selected value in Selectize.js dropdown?

I have a selectize.js dropdown and I have to clear the selected value .
I have tried this (as suggested in another question):
var selectize = $("#optionNetFlow")[0].selectize;
selectize.clear();
But it gives the following error:
When I change it to this:
var selectize = $("#optionNetFlow").selectize;
selectize.clear();
I gives this error:
What I am doing wrong here?
I finally found the answer here Selectize.js Demos
What works for me is:
var $select = $('#optionNetFlow').selectize();
var control = $select[0].selectize;
control.clear();
what I was missing var $select = $('#optionNetFlow').selectize(); before applying the solution provided in above question's answer.
Now I am to get all the functions in console like :
Try this,
$("#optionNetFlow")[0].selectize.clear();
Try this out:- http://jsfiddle.net/adiioo7/2gnq1ruv/204/
JS:-
jQuery(function ($) {
var $select = $('#input-tags').selectize({
persist: false,
create: true
});
$("#btnClear").on("click", function () {
var selectize = $select[0].selectize;
selectize.clear();
});
});
All other answers either clear a single selectize or need a specific reference to the selectize in the moment of it's creation.
The solution below, on the other hand, works for any number of selectize elements you have inside any form; you just need to specify the desired form:
$('form').find('.selectized').each(function(index, element) { element.selectize && element.selectize.clear() })
The rationale is that Selectize keeps the original element in the DOM (hiding it), adds a reference to the selectize on the .selectize property of the DOM element and adds a CSS class selectized to it.
So the solution finds all the elements that have the CSS class selectized, loops through them and calls element.selectize.clear().
$(document).on('click', 'div.selectize-input div.item', function(e) {
var select = $('#services').selectize();
var selectSizeControl = select[0].selectize;
// 1. Get the value
var selectedValue = $(this).attr("data-value");
// 2. Remove the option
select[0].selectize.removeItem(selectedValue);
// 3. Refresh the select
select[0].selectize.refreshItems();
select[0].selectize.refreshOptions();
});
This do not remove the item from the select, just remove it from the selected options.
Or if you have multi select, and do want to restore selected items in the drop-down list (hide selected set to true).
var selectize = $("#select-item").selectize;
//clone array
var items = selectize.items.slice(0);
for (var i in items) {
selectize.removeItem(items[i]);
}
selectize.refreshOptions();

Categories

Resources