jQuery find all attr rel - javascript

I have a this select dropdown:
<select id="category">
<option value="cat1">Category 1</option>
<option value="cat2">Category 2</option>
</select>
and I have this code that everytime I select something form the dropdown it takes the value and find the same class and show it on the last line
$('#category').change(function () {
var selected_category = $(this).val();
$('#sub-category').find('.option').hide();
$('#sub-category').find('.'+selected_category).show();
});
I just want to change instead of class so it will find the attribute rel
** edited **

You definitely don't need jQuery for this. Here's the code to find all option tags with a rel attribute of "sub-cat1":
document.querySelectorAll('option[rel="sub-cat1"]')
The above will work in IE8 and up, which should satisfy all browsers you need to support. The jQuery solution is similar, and uses the same selector string:
$('option[rel="sub-cat1"]')
Furthermore, you don't need to add a class of "option". Simply select using the option tag name.

There can be an alternate way to your answer.
Using jquery try ,
$ (".classname").each(function(){
//iterate over similar *classname* elements one by one
$(this).someFunc(); //it will help you to preform operation at current value while iteration
});
With rel if you want to iterate over rel tag values , try
$("[rel='sub-cat-1']").each(function(){
//Some operation
});

Related

Adding onclick attribute to a dynamically created option

I have a script where I am appending options to a select item and would add the onclick method to them.
My piece of code is this:
$(obj).closest('td').next('td').find('.select').append(new Option("i", "i"));
and this is how it looks when I inspect them:
<option value="i">i</option>
but I want them to be
<option onclick="functionname" value="i">i</option>
Is there anyway to do it with jQuery? Thanks in advance
A much better idea would be to put a click event handler on the select itself, then read the value which was selected.
This is for two reasons. Firstly inline event attributes, such as onclick, are no longer good practice and should be avoided where possible. Secondly, event handlers on option elements are unreliable at best and just plain don't work at worst.
The best way to achieve what you need is to add a change event handler to the select and read the selected value from the chosen option at that point, something like this:
let $foo = $('#foo').on('change', e => {
console.log(e.target.value);
});
$('button').on('click', () => {
let ts = (new Date()).getTime();
$foo.append(`<option value="${ts}">${ts}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add option</button>
<select id="foo"></select>
I wouldn't do it for an onclick attribute since, as already stated, there are faster and better ways to reference it directly from JS. But for future reference or if you need to set other attributes, you can use the built in setAttribute. An example would be yourelement.setAttribute("class","classname").
After adding a new option, you could create a listener for that select like this:
jQuery('select').change(function(){
const value = jQuery(this).val();
console.log(value);
});
jQuery('select').append(new Option('New Option', 'value'));
jQuery('select').change(function(){
const value = jQuery(this).val();
console.log(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

How to select nth item inside select element in cypress

say I have the HTML:
<select name="subject" data-testid="contact-us-subject-field">
<option value="What is this regarding?">What is this regarding?</option>
<option value="Partnerships">Partnerships</option>
<option value="Careers">Careers</option>
<option value="Press">Press</option>
<option value="Other">Other</option>
</select>
Selecting an option with a known value, such as 'Careers' is as easy as:
cy.get('[data-testid="contact-us-subject-field"]').select('Careers');
How do I select the nth option in this field, regardless of its value?
Update
As pointed out by #dpstree in the comments, this doesn't answer the original question. Please see more recent answers for a complete solution.
Original
By using eq
cy.get('tbody>tr').eq(0) // Yield first 'tr' in 'tbody'
cy.get('ul>li').eq(4) // Yield fifth 'li' in 'ul'
In the particular context of selecting the nth option, this may be appropriate:
cy.get('select[name=subject] > option')
.eq(3)
.then(element => cy.get('select[name=subject]').select(element.val()))
Based on solution from Miguel Rueda, but using prevSubject option:
Cypress.Commands.add(
'selectNth',
{ prevSubject: 'element' },
(subject, pos) => {
cy.wrap(subject)
.children('option')
.eq(pos)
.then(e => {
cy.wrap(subject).select(e.val())
})
}
)
Usage:
cy.get('[name=assignedTo]').selectNth(2)
Explanation:
Using children('option') and .eq(pos) traverse children of select to specific element.
Call select method with value of selected element.
You can now select an option by index within the .select(index) command:
cy.get('select').select(0) // selects by index (yields first option) ie "What is this regarding?"
cy.get('select').select([0, 1]) // select an array of indexes
This should be easy now with the release of cypress v8.5.0. See documentation for more.
I had the same problem and solved it by creating a custom cypress command. No as pretty as I would like, but it did the job.
Cypress.Commands.add("selectNth", (select, pos) => {
cy.get(`${select} option +option`)
.eq(pos)
.then( e => {
cy.get(select)
.select(e.val())
})
})
then I used in the test as such
cy.viewport(375, 667)
.selectNth("customSelector", 3)
The option +option part was the only way I could find to get the full list of options inside a select and it's currently the bit of code i'm trying to work arround although it works fine.
since the working answers are using then anyways, eq or something fancier is redundant with array indexing...
// to click on the 1st button
cy.get('button').then($elements => {cy.wrap($elements[0]).click();});
// to click on the 4th tr
cy.get('tr').then($elements => {cy.wrap($elements[3]).click();});
// to click on the last div:
cy.get('div').then($elements => {cy.wrap($elements[$elements.length - 1]).click();});
Let's assume you wanna select 2nd option, you can do that simply by this
cy.get("select option").eq(2)
just keep in mind that cy.get() works like jquery's $().
Find dropdown using ID or Class -
cy.get('#ID').contains("dowpdown placeholder or name").click();
After Click dropdown result dropdown element will popup, find that result ID or Class using inspect element, Then -
cy.get('#result-ID').children().first().click();
This will click on the first element of the dropdown.
Capture all the elements in the drop-down using a selector. Get the length. Use math.random() to randomly get a number. Select the option at the index.
cy.get("ul > li").as("options")
cy
.get("#options")
.its('length')
.then(len => Math.floor(Math.random() * Math.floor(len)))
.then((index) => {
cy.get("#options").eq(index).click()
})
You can also rely on the :nth-child css pseudo-class:
cy.get("[data-testid="contact-us-subject-field"] option:nth-child(2)").click();
It's probably less flexible than using the cypress constructs but it is nice and clean. (And doesn't make me crawl through the cypress docs)
if you are looking a value to select then you cannot use .eq(), you need to use .contains()
.eq() is only for numbers(indexes)
Example: cy.get(dropdownOptions).contains(some_value).click()

Javascript get element by select class

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select"
name="tmcp_select_30"
data-price=""
data-rules=""
data-original-rules=""
id="tmcp_select_75"
tabindex="75">
<option value="5 (480 mm)_0" etc.......
To get value of this element, currently I am using this piece of code:
document.getElementById("tmcp_select_75").value
It works well, but how can I get value of element using "tmcp-field tillagg-width tm-epo-field tmcp-select" seen it top row of first code sample? Thanks :)
Use querySelector() or querySelectorAll() or getElementsByClassName()
// Gets the first match's
document.querySelector(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")
// Gets a collection of the selects;
document.querySelectorAll(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")
// Gets a collection of the selects;
document.getElementsByClassName("tmcp-field tillagg-width tm-epo-field tmcp-select")
jQuery
$(".tmcp-field.tillagg-width.tm-epo-field.tmcp-select")
You don't need jQuery for this. If I'm reading you right, you want to select the element using its class instead of by ID, as you're doing right now. Use document.querySelector:
document.querySelector('.tmcp-field.tillagg-width.tm-epo-field.tmcp-select');
You probably don't need to select for all of those classes, so remove any that you don't need to narrow down the result.

Getting second value in jQuery dropdown

How would I get the second value in a dropdown list using javascript or jquery?
<select id='dropdown'>
<option selected>Any</option>
<option>2</option>
<option>3</option>
</select>
e.g. i would like to get the value of number 2 in the dropdown
Neither of those options has a value. (Actually, see note below.) You can get the text like this:
var text = $("#dropdown")[0].options[1].text;
Or without jQuery:
var text = document.getElementById("dropdown").options[1].text;
Live Example | Live Source
Or you can use .value instead of .text, as the option elements will default their value property if you don't give them a value attribute. (You can't select them using a value= selector, but the property is defaulted.)
To get the second value in a dropdown list using jquery, you can do this using .eq():
var text = $("#dropdown option").eq(1).text();
In order, to get the n th number value in the dropdown list, you can do this:
var text = $("#dropdown option").eq(n - 1).text();
Try this
JS CODE
$(function(){
alert($('#dropdown option').eq(1).val());
});
LIVE DEMO
Why not try this so easy to understand then :eq(n)
http://jsfiddle.net/q9qCR/2/
$('#dropdown option:nth-child(2)').val()
Try
$(document).ready(function() {
alert($("#dropdown option").eq(1).text());
});

jQuery set click handler with per-element information

I have a onclick attribute ontag now that gets set serverside with the REQUIRED_ID for when the user clicks on it.
The problem now is that I am trying a more jQuery-like approach where I do set the click handlers on document ready but now I don't have the REQUIRED_ID at hand to set it.
I'm wondering what would be the jQuery way of doing this, perhaps setting another tag with the REQUIRED_ID and reading it on ready?
NOW:
$.ready(
$('select.attr_satus>option:not(:selected)').each(
/* I AM MISSING REQUIRED_ID, WHERE DO I GET THIS VVVVVV*/
$(this).click(function(){ statusChanged(this,REQUIRED_ID,$(this).val()); })
);
);
BEFORE:
<select class="attr_status">
<option onClick='statusChanged(this,REQUIRED_ID,"draft");' value='draft'>Draft</option>
<option value='publish' selected="true">Published</option>
</select>
REQUIRED_ID is an id that changes per row, as I have several of those select tags one after each other.
You can store your extra information in "data-" attributes:
<select class="attr_status">
<option data-requiredId='REQUIRED_ID' value='draft'>Draft</option>
Then in your event handler you can get it with ".data()":
$(this).click(function() {
statusChanged(this, $(this).data('requiredId'), this.value);
});
edit — Now "data-" attributes are standardized with HTML5. Another approach is to use the "class" string, which can contain pretty much anything. What I've done is use a "name:value" notation:
<select class="attr_status">
<option class='requiredId:REQUIRED_ID' value='draft'>Draft</option>
Then in the handler:
$(this).click(function() {
var id = this.className.replace(/^.*\brequiredId:(\S+).*/, '$1');
statusChanged(this, id, this.value);
});

Categories

Resources