jQuery: using ".each" for a select's options by $(this) - javascript

I know there are a lot of similar questions but I still could not find one about my exact problem. I haven't got the selector of my <select>; I am iterating form fields and so i only got access to my select by using $(this).
how can I iterate this select's options by using jQuery's '.each' function?
i tried to chain it, but this doesn't work:
$(this).$('option').each(function(){
if (this.value == val) {
// do something
}
});
note: $(this) is my select not my form.

Try this : you can use .find() to get option under select.
Note: - this.value refers to current option value inside loop.
$(this).find('option').each(function(){
if (this.value == val) {
// do something
}
});

Because your this is a reference to the select element you also have access to its .options property which you can wrap in a jQuery object:
$( this.options ).each( function(i, option){
if (this.value == val) {
// do something
}
});
http://jsfiddle.net/x57d8msL/

$.each($('select'), function (key, val){
console.log($(val));
});

Related

Select returns no value even it already have a default value

I have a select item and I already added a default value for it, but after submitting the form, it returns an empty string. Why is this?
My code:
var c = $('#c').val();
populateSelect(cs, '#c', 'My select option');
function populateSelect(json, element, defaulttext) {
$(element).find('option').remove().end().attr('disabled', false).append($('<option selected>').text(defaulttext).attr('value', ''));
$.each(json, function(i, value) {
$(element).append($('<option>').text(value).attr('value', value));
});
if (defaulttext != undefined) {
$(element).val(defaulttext);
}
}
Although you set the selected attribute in your jQuery, you're not actually setting a value for that selection. You need to change .attr('value', '') to something like .attr('value', 'default'). To pass it through from your function parameter, you're looking for .attr('value', defaulttext).
In addition to this, you'll also need to ensure that your select field has a name attribute, in order for the value to be picked up once the form is submitted.
Hope this helps! :)

Jquery if $this attribute selector contains a word

Is it possible to use the jquery attribute contains selector on $(this)? I cannot find any examples. I am trying to see if input fields contain a certain word.
$("#form input").keyup(function() {
if ($(this).filter( "[name~='someWord']" )) {
console.log('yes');
}
});
The code returns yes for all input even if they don't contain someWord.
You have to use .is() at this context,
if($(this).is( "[name~='someWord']" )) {
console.log('yes');
}
Because .filter() would return a jquery object (element collection), and that would never be false.
You can do this even better with Vanilla JS in the event handler
$("#form input").keyup(function(evt) {
if (evt.currentTarget.name.indexOf('someWord') > -1) {
console.log('yes');
}
});
This checks the name attribute of the actual DOM element and does not add the overhead of the jquery wrapper.
Try
$("#form input").keyup(function() {
if ($(this).filter("[name~='someWord']").length) {
console.log('yes');
}
});
or better:
$("#form input").keyup(function() {
if ($(this).is("[name~='someWord']")) {
console.log('yes');
}
});

Jquery - wrapping a bind function to THIS elements

I have multiple tables on a page (there will be over 100) and I want to use one function for all of them. When the user selects "Custom" in the drop-down menu, additional questions apply TO ALL OF THEM. How do I wrap my function in a THIS statement to have it only added to that individual table. I apologize in advance for my description of the issue.
$(document).ready(function(){
$('td.additional_content').css('visibility', 'hidden');
$('#srds_mapping').bind('change', function (e) {
if( $('#srds_mapping').val() == 'Custom') {
$('td.additional_content').css('visibility', 'visible');
$('td.additional_content .custom').show();
} else {
$('td.additional_content').css('visibility', 'hidden');
$('td.additional_content .custom').hide();
}
}).trigger('change');
});
It is better explained by looking at it
http://jsfiddle.net/2Q7J7/2/
this is the targetted element inside the event handler:
$('#srds_mapping').bind('change', function (e) {
if( $(this).val() == 'Custom') { // traverse to find the target input element
Note that you should not use more than one ID on the page. Use classes or other selectors instead, f.ex:
$('select').bind('change', function (e) {
if( $(this).val() == 'Custom') {
jQuery .each() function would be a good option:
Assuming $('#srds_mapping') is your table. Firstly, instead of id you could add a class to the tables. For example <table id="srds_mapping" class="srds_mapping"></table>. After that is in place you could do something like this.
$('.srds_mapping').each(function(){
$(this).bind('change', function (e) {
// other function stuff
}).trigger('change');
});
Also, this thread may be worth a read, or something to think about.

Need to get empty Dropdown ID

I have a web form and Dropdown Box. We can clone dropdown and can create some more. My problem is needs to know any of them are empty. My every dropdown id is begin with 'abcd'.
For example
<select id='abcd_1'></select>
<select id='abcd_3'></select>
<select id='abcd_10'></select>
<select id='abcd_5'></select>
I tried following code but no luck
$( "input[id^='abcd']" ).val();
Try to use :empty selector to filter out the required elements,
var emptySelects = $( "select[id^='abcd']" ).filter(function(){
return $(this).is(':empty');
});
or simply,
var emptySelects = $("select[id^='abcd']:empty");
And if you want to traverse it just use .each()
emptySelects.each(function(){
console.log(this.id);
});
Try this
$('select').each(function(){
if($(this).find('option').length == 0){
alert($(this).attr('id'))
}
});
DEMO
If you want to check if dropdowns are empty then you can use this:
if( $( "select[id^='abcd']").has('option').length > 0 ) {
Because you have multiple dropdowns , you must repeat the code above with $.each:
$.each($( "select[id^='abcd']"), function(i, dropdown){
if ($(dropdown).has('option').length == 0){
alert($(dropdown).attr('id'));
}
})
I made an example: http://jsfiddle.net/mihutz/M3FfZ/

$(.class) only executes for the first tag of that class name

I am trying to make a javascript function that goes through the web page and looks for all of the tags of class name "option" and hides the ones that match the text in each of the if statements shown below.
In the example below, I tried using jquery to get the classes, but it only gets the first class with that name, not all of the classes of that name.
I have also tried using var element = document.getElementsByClassName('option'); to see if that would work but when I iterated through the list of elements and changed their display to none, the changes didn't show up.
What is a better way to iterate through a list of classes and update the css of only some of the elements?
Any help is appreciated. Thanks.
$(document).ready(function(){
if($('.option').html() == "C. "){
$('.option').css('display','none');
}
if($('.option').html() == "D. "){
$('.option').css('display','none');
}
if($('.option').html() == "E. "){
$('.option').css('display','none');
}
if($('.option').html() == "F. "){
$('.option').css('display','none');
}
});
You're not getting only one element, you just simply only manipulating the "first" element in the jQuery Object that is returned by the $('.option') call. What you need to is jQuery's .each() function in order to iterate through ALL of the elements returned by the jQuery call. Also, the long if statement can be shortened, but I assume you knew that and have other purposes. Anyway, once .each is called, you can use the callback function to manipulate EACH element as it is passed through. This is much like a for loop. The parameter i in the following example represents the index value of the element as the object is iterated through. It is 0 based, in other words, the 3rd option element to pass through would set the param i to 2
Try this && Good Luck:
$(function() {
$(".option").each(function(i) {
var txt = $(this).text();
if (txt == "C." || txt == "D." || txt == "E." || txt == "F.")
$(this).hide();
});
})
Alternate links to investigate
.html()
Use this method to get or set the innerHtml of an element
.val()
Use this method to get or set the value of an element
Primarily HTML tags select, input, && textarea
If I understood what you want, this should work:
$(document).ready(function(){
$('.option').each( function(i,e) {
var current = $(e).html();
if (current == "C" || current == "D" ||
current == "E" || current == "F") {
$(e).hide();
}
});
Use the .each function
$('.option').each(function(index) {
if($(this).html == "E")
$(this).hide();
});
$('.option').html() will only get the innerHTML of the 1st element. If you want to look at all of them, you need to use $.each.
$('.option').each(function(){
if($.inArray($(this).html(), ['C', 'D', 'E', 'F']) !== -1){
$(this).hide();
}
});
I see You are using jQuery.
When you wrapp some class with jQuery function like this $('.option') you will get an element set, meaning it will containg all of those elements wrapped in special jQuery classes that offer you a lot of functionality
Best way to iterate trough element set is by using jquery .each() function, http://api.jquery.com/jQuery.each/
it will apply callback function to every element.
Something like this:
$(document).ready(function(){
$('.option').each(function() {
//Here you can access coresponding element to each iteration with this kyeword
// you can wrap it again like this $(this) and get all of jQuery functionality on that object again
$(this).hide();
});
}
Try this:
$(document).ready(function(){
$('.option:contains("C.")').hide();
$('.option:contains("D.")').hide();
$('.option:contains("E.")').hide();
$('.option:contains("F.")').hide();
});
The JQuery selector '.option:contains("C.")' finds all tags of the option class that contain the text "C.", and the .hide() function hides each element in that collection.
http://jsfiddle.net/b3hVw/
Or alternatively, in a single statement:
$(document).ready(function(){
$('.option').filter(function() {
var html = $(this).html();
return html === "C." || html === "D." || html === "E." || html === "F.";
}).hide();
});
$('.option') finds all the elements with the option class. The .filter(function() { ... }) call filters that list to just the ones for which the filter function returns true, and then the call to .hide() hides those elements.
http://jsfiddle.net/H7Lu8/

Categories

Resources