calling one javascript function affecting two html drop download list - javascript

My question is can you call just one javascript function and affect two html drop down list the idea is to use the codes below
javascript code:
document.getElementsByClassName("cmbRecom")
html code:
<Select name="drop1" class="cmbRecom" >
<option>Check Fields</option>
</Select>
<Select name="drop2" class="cmbRecom" >
<option>Check Fields</option>
</Select>
what is in my head, is the css behavior where you can name html elements with the same class names and all will follow that style that is declared for that class.

Yes, you can. One possible way is as follows:
document.documentElement.cmbRecomb;

When selecting elements using the function getElementsByClassName the code should work with the returned elements as an array, which will require iteration through the selected elements.
var selects = document.getElementsByClassName("cmbRecom"); //was cmbField
for(var i = 0; i < selects.length; i++){
selects[i].style.width = "200px";
}
Note: The class name and selector were different.
JS Fiddle: http://jsfiddle.net/LWxcX/

Related

jQuery find all attr rel

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
});

Replacing the inner.html of an unknown named element based on condition

I run into this problem frequently and never know the best approach. Imagine I have a structure that includes several instances of the following html:
<div class="known">
<div class="another unknown">
<div class="unknown">
<h4>Something a something</H4>
</div>
</div>
</div>
For each div of class known, I want to change the inner html of that div only if it contains a div inside it with some particular tag, in this case <h4>.
What is the best way to achieve that. I know that I could do it by taking the inner html of class known and doing a regex match. But is there a more robust way based on tags?
Simple, just use a selector that spans over the div.known and restrict it's context to div h4. If the selector selects at lease one element then the div.class has children as you expect.
if( $('.known div h4').length > 0 ){
$('.known').html('Some html');
}
Yes! You can do this.
var head = Array.prototype.slice.call(document.querySelectorAll("h4 #known"));
for(var i = 0; i < head.length; i++)
{
while(head[i].className !== "known")
head[i] = head[i].parent();
}
Now head will be an array of all the DOM elements have the tag known and have h4's in them.
With jQuery, you can use .has() to narrow your selection and even chain other methods, as in:
$(".known").has("h4").css("background","red");
Check out this fiddle for example. Notice that clicking the button will change the color of any div.known only if that element contains an h4 tag as a descendant.
Documentation on jQuery's .has() -- https://api.jquery.com/has/

JS class toggle not working with getElementsByClassName

I am trying to do a simple toggling of classes for multiple elements for a slide out menu without jQuery, pure JS.
function toggle_classes() {
var navicon = document.getElementById('nav-icon');
var overlay = document.getElementsByClassName('overlay');
navicon.classList.toggle('open');
overlay.classList.toggle('show');
}
document.querySelector('#nav-icon1').addEventListener('click', toggle_classes);
When I define the variables with getElementById it works, but it doesn't work with getElementsByClassName
Can someone tell me how to fix this? I'd much rather use getElementsByClassName so I can target multiple elements with a single line of code.
The data structure returned by getElementsByClassName is an array-like structure, not a dom element. so you must loop over the elements to toggle each one individually.
for (var i = 0; i < overlay.length; i++) {
overlay[i].classList.toggle(...)
}
document.getElementsByClassName... notice the "s" in Elements?
(in other words, that method returns an array, not a single element, so you need to do somehting like overlay[0].etc)

Dropdown menu choice hides fields through class

I have a dropdown menu, that when a value is chosen it hides/ shows fields, because of the php code behind it I need to use class to choose it.
I was also wondering if theres a way to add back the padding when hiding and showing the fields.
I tried using "document.getElementsByClassName("className");" But couldn't get it working.
HTML:
<select id="form" onchange="ChangeDropdowns(this.value);">
<option value="hide">hide</option>
<option value="show">show</option>
</select>
<input type="text" id="testField" class="testField" />
Javascript:
function ChangeDropdowns(value) {
if (value == "show") {
document.getElementById('testField').style.display = 'none';
} else if (value == "hide") {
document.getElementById('testField').style.display = 'block';
}
}
You are using the querySelectorAll function wrong, it returns an array of elements, if you want a single element use querySelector which in this case it looks like thats what you want.
HTML
<input type="text" id="testField" class="testField2"/>
JS
//Uses class, a period needs to be before the class name, when selecting by class
document.querySelector(".testField2").style.display='none';
//Uses id, a # needs to be before the id name, when selecting by id
document.querySelector("#testField").style.display='none';
When using querySelectorAll it will return an array, so you have to access it as such
var elements = document.querySelectorAll(".testField");
elements[0].style.display='none';
Your fiddle had a couple errors:
Function name in onchange didnt match the actual function name
you had onLoad selected for the wrap, which was making it so the function wasnt being declared in the global scope.
You werent using the proper css selector, classes have . prefixed to the name, ids have # prefixed, when no period or # before the name, the name is looked up as an element tagname

jquery class selector inside a loop

I have a simple question about the expression in jquery to select a class which involved a for loop. Basically, I have two steps:
1. Generate some html tables with a loop.
2. Use jQuery to unhide them.
Below is the simplified code to
1. generate html tables (I will add a loop index to separate each loop created tables) :
2. the key part of the second step is to unhide generated tables. My selector is written as: method_options_1'+i+', where i is a for loop index.
for (var i = 2; i <= 5; i++) {
<tr class="method_options_1'+i+'" style="display: none;"><th><label for="id_CAM_1">Chemical application Method (CAM):</label></th>
<td><select name="CAM_1_'+i+'" id="id_1_'+i+'">
<option value="2">2-Interception based on crop canopy</option>
<option value="9">9-Linear foliar based on crop canop</option></select>
</td></tr>
$('.method_options_1'+i).closest('tr').show();
}
However, this selector does not work, which means I could not show the hidden element. While, if I remove the index i from both the HTML and jquery, the selector works. Since I have to keep the i index, can anyone give me some suggestions (I tried to remove closest('tr'), but it does not work)?
'.method_options_1'+i is already a tr, so first try removing the closest('tr') step:
$('.method_options_1'+i).show();
See http://jsfiddle.net/WJDCm/
That's because as far as Javascript is concerned, name is simply a string: method_options_1'+i'. It does not evaluate any code inside that string. If you want to do it correctly, do something like this:
HTML:
<tr class="method_options">etc</tr>
Javascript:
$('.method_options:eq('+i+')').show();
EDIT:
Perhaps I misunderstood. You are generating this inside a Javascript for loop, so i is a valid variable in code space. If that's the case, then you simply have to take out closest(), as it tells jQuery to travel up the DOM and select the first tr that it finds. In this case, that appears to be nothing. You want to work on the tr that you selected, not a tr that is a parent of the one you are selecting.
I really wonder how you run the above code... however doing this does work
HTML:
​<table id='myTable'>
</table>​​​​​​​​
JavaScript:
$(function(){
for (var i = 2; i <= 5; i++) {
$('#myTable').append('<tr class="method_options_1'+i+'" style="display: none;"><th><label for="id_CAM_1">Chemical application Method (CAM):</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"> <option value="2">2-Interception based on crop canopy</option> <option value="9">9-Linear foliar based on crop canop</option></select> </td></tr>');
$('.method_options_1'+i).closest('tr').toggle('slow');
}
})
Solution

Categories

Resources