jQuery attr('id') returns undefined - javascript

I have a list of items and when a user clicks on one of them, it gets assigned a class called 'active-child'. Just one item could be selected at the moment, and when the user clicks on another item, this item is cleaned of 'active-child' class and then this class gets assigned to the newly selected item. Just like any other non-multiple list.
Here is the selected element's HTML:
<div id="5" class="new-child-item new-child-item-active active-child"> Software </div>
When I want to submit the selected item's "id" to a php script to process it further, the jquery does not retrieve the id value of the element and says it is undefined. My approach to getting the selected item's id attribute is as follows:
$('.active-child').attr('id');
I also have tested this, but still returns undefined:
$('.active-child:first-child').attr('id');
The strange thing is that I first check to see if the user has selected anything at all, and if yes, then do the ajax, at this moment, the jquery returns 1, means the user has selected one item. Here is the code block which checks to see the selection and then send it through ajax:
if($('.active-child').length > 0)
{
$('.new-item-cats-list-holder').empty();
$('.new-item-cats-list-holder').hide()
$('.big-loader').show();
console.log("This is the id: " + $('.new-child-item-active:first-child').attr('id'));
$.ajax({
url : base_path('ajax/set_credentials/step_2'),
type: "POST",
data : ({'set_sess':true, 'category' : $('.active-child').attr('id')}),
success : function(msg){
if(msg!=0)
{
//window.location.href = base_path('panel/add/step/ads/3');
}
},
});
}// end of length if

The empty() and hide() functions before the ID retrieval destroys and DOM and does not allow it to exist and then to be fetched of its id value.

I have an inkling that you are using numerical values as IDs, or at least have ID that starts with a number. My suspicion comes from the fact that your console log returns 1, and you have specified in your question that you are logging the active child's ID.
This is invalid — classes and IDs have to start with an alphabet or an underscore or a dash, and then followed by any alphanumeric, underscore or dash characters and a combination thereof.
See here: Which characters are valid in CSS class names/selectors? and http://www.w3.org/TR/CSS21/syndata.html#characters
This is unless you are using HTML5, but you need to declare the doctype correctly: <!DOCTYPE html>
Also, have you checked that your IDs are unique?

Related

How to check a checkbox element according to the value in cypress while the value does not exist

How do I check a checkbox element according to the value in cypress, while the value attribute does not exist.
I want to check the checkbox according to the value, not the id, because the id is different for each page.
Because in some pages, the id starts with c1, and some page ids start with c2, and some start with c5.
How would I check the element according to value?
I got the selector for all 3 checkboxes, but it checked all the 3 elements. I want specific element according to value attribute, but there there is no value attribute.
i tried this
cy.get('.x-overlay__wrapper--right input[type="checkbox"]').check()
but it checked all the element
and this checked the first element
cy.get('.x-overlay__wrapper--right input[type="checkbox"]').first().check()
but I want the checked according to value, but here in attributes there is no value attribute.
the value that i want is just written next to checkbox
and here in html
Looking at the html, perhaps search for the text then use parent and sibling commands to shift the subject to the checkbox, something like
cy.contains('span', 'Free Shipping') // find your text
.parent('div') // move to parent div
.siblings('span.checkbox') // move to checkbox span
.find('input') // select it's input
.check();
Example with comments explaining the code:
cy.get('.x-overlay__wrapper--right input[type="checkbox"]').each((checkbox, i) => { // Get the elements and run .each() on them
if (cy.get('.cbx.x-refine__multi-select-cbx')[i].innerHTML === "value") { // If the value is something, perform an action. Replace "value" with the value that you need to test it for
checkbox.check()
}
})

Angular multi-select dropdown and lodash countby

I am kinda drawing a blank on this one facet, and I can't seem to quite figure it out.
So I have a simple HTML select => option element which is populated from the back-end (not really relevant tho)
My question is this:
Let's say I have a pre-made object such as this:
{
keyName1: 450,
keyName2: 800,
keyName3: 300
}
What I want to do is to check if the key name matches a name of an option value in my multi-select dropdown (the values come from an array, using 'ng-repeat' on the option), and if the option value matches the key, add the number value to some sort of increment variable, so I can display the total number of 'keyNames' found.
For example - if a user selects 'keyName1' the incrementer value will total 450. If a user selects 'keyName1' and 'keyName2' the incrementer value will total 1,250.
I am lost on how to accomplish this - right now it is reading only the very first item in the dropdown.
Here is the code doing that:
_.forEach($scope.widget.instance.settings.serviceContractTypes, function (type) {
// if item in array matches what is selected in multi-select option
if(type === $('#contractType:selected').text().trim()) {
// do stuff
}
});
Hope this all made sense, and thanks very much for any direction you might offer...
(does not have to utilize lodash, I'm just used to using it)
jQuery's :selected selector only works for HTML options:
"The :selected selector works for elements. It does not work for checkboxes or radio inputs; use :checked for them."
(https://api.jquery.com/selected-selector/)
You say "I have a simple HTML select => option element which is populated from the back-end (not really relevant tho)"
This could be relevant. By default, an HTML option tag does not support multiple selections; it has to explicitly be created as a select multiple in order to support that. Can you share the HTML code for the option to make it clear whether that's a problem or this is a red herring?
Also, can you echo $scope.widget.instance.settings.serviceContractTypes and share to make sure it's actually matching what's available in the text of the options?
ADDENDUM - Wait, I think I figured it out!
The $('#contractType:selected') selects all the selected options in #contractType and concatenates them. Then $('#contractType:selected').text().trim() trims this down to the first word, which is just the first selected option. You should do something like $('#contractType:selected').text().split(" ") and then check if each type is in the resulting list.

Delete Dropdown values using jquery

I have a situation here,
Using JQuery I'm appending some values in drop down list.. Even it is one or two value that appended in drop down list..
For Add,
tableui+='<option value="">'+resourceadd+'</option>';
$('#resourcess').append(tableui);
When the page reloads automatically the value stored in db.
For example 4 values added in dropdown list (Values are not stored in db), I want to delete last value. I'm using,
$("#resourcess :last-child").remove();
The same condition, I want to delete middle of two values, How to do it??
Assuming you know the value of the option you want to remove, you could use filter:
$('#resources option').filter(function() {
return this.value == 'foo'; // insert your value here.
}).remove();
Or an attribute selector:
$('#resources option[value="foo"]').remove();
If you don't know the value, but do know the position of the option within the select, you could remove it by index using eq():
$('#resources option').eq(1).remove(); // remove the 2nd option

Passing jQuery this.id in class selector

I have two different input fields, it uses typeahead.
In first field we enter Country and in other we should select City, depending on Country.
So I'm making a javascript/jQuery function, to pass field ID, to know, which of 3 pairs of Country+City pair am I selecting.
i'm using
$('.demoTypeAhead').typeahead({
source: getCityForCountry($(this).id)
});
in function getCityForCountry, I would like to pass a field specific id, but neither $(this), or this works, since it returns whole DOM object.
A jQuery object does not have an .id property. You either want
this.id // or
$(this).prop("id") // or even
$(this).attr("id")
$(this) on this scope does not return input as an object, but whole page as an object...
Just made jsfiddle for it:
Jsfiddle http://jsfiddle.net/s1d8nmqr/3/
I would like to reload data source of typeahead for second input, when I select first one (2 level select)

jQuery: Selecting option elements by their value

I'd like to remove a specific option from some select boxes (all with the same values) if their value is "1". The problem is, I'm having difficulty filtering elements down to that specific value.
At the moment, the closest I've got is
$('.demoClass').find('option:contains(1)').remove();
but there are two problems. Firstly, this seems to iterate over the (displayed) contents of the option, not its value...and secondly, it seems to return true the contents contain that value, as opposed to being that value. (Eg contains(1) will return true for (1, 10, 11, 12)...when I want it to return true for "1" only)
In short, what I'm looking to do is find the timeslot option with value X inside all select boxes of class ".demoClass" and remove them. Any suggestions appreciated.
Try this...
$('.demoClass').find('option[value="1"]').remove();
This utilizes the Attribute Equals Selector
Try this:
$('.demoClass').find('option[value=1]').remove();

Categories

Resources