jQuery detects which element is visable - javascript

I have several tables with similar class names, but only one table is visible at a time. I am having troubles of using jQuery to detect and save the class name of the visible table (I can use .is(':visible') to check and save the class name of the positive ones, but it is kind of cumbersome.). I appreciate any suggestions.
HTML
<table class="tab_Chemical" border="0" style="display:none">
<tr><th><label for="id_wat_hl">Water Column Half life (days):</label></th>
<td><input type="text" name="wat_hl" id="id_wat_hl" /></td></tr>
</table>
<table class="tab_Physical" border="0">
<tr><th><label for="id_mas_tras_cof">Mass Transfer Coefficient (m/s):</label></th>
<td><input type="text" name="mas_tras_cof" value="1e-08" id="id_mas_tras_cof" /></td></tr>
</table>
JS
<script type="text/javascript">
$(document).ready(function() {
###CODE TO DETECT VISIBLE CLASS and SAVE the CLASS NAME###
});
</script>

Try using the :visible pseudo-selector, along with the ^ (starts with) selector:
$(document).ready(function () {
var visible = $("[class^='tab_']:visible");
});
But the starts with selector is a little fuzzy. If you can, give them all a common class (Good shout Kevin B)(the below assumes the class tab is the common class):
$(document).ready(function () {
var visible = $(".tab:visible");
});

Something like this maybe:
var classes=[];
$("table:visible").each(function(){
classes.push($(this).attr('class'));
});
Seems like an odd requirement though. You might want to take a step back and see if there is a more logical way to do what you want.

Related

Javascript select element with complicated ID

need some help! am trying to get the value of the below input id "j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" and have tried jquery and javascript such as: document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63") but keep getting a null result. ID can't be changed either, any help appreciated
<td class="sf42_cell_bottom_light"><span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61"><input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417"></span></td>
Use this:
$("[id='j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61']")
By the way, since you are apperently using JSF, this is a good practice to set id to each component to avoid such horrible ids (who can changes if you add/remove components).
See more information in this thread:
Handling colon in element ID with jQuery
Do you have any control of the element? Can you add a class to it?
var val= document.getElementsByClassName("TheClassName");
Or you can get the TD with class sf42_cell_bottom_light (if it is unique) then get its INPUT elements by:
var theTd= document.getElementsByClassName("sf42_cell_bottom_light");
var val = theTD.getElementsByTagName("INPUT");
I need to see more of the HTML to give you an better answer.
You may need to escape colon in your id .So
try this
function RemoveInvalidCharacter(myid) {
return '#' + myid.replace(/(:|\.|\[|\])/g, "\\$1");
}
And call like this
$(RemoveInvalidCharacter('j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61'));
Have a look at How do I select an element by an ID that has characters used in CSS notation
I have tested this code:
<td class="sf42_cell_bottom_light">
<span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61">
<input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417">
</span>
</td>
<script type="text/javascript">
document.write(document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63").value);
</script>
in FF, IE, Chrome (the latest versions)... and seems to work ok... ar you sure it is about this id?
Replace:
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63")
with
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63")
The id is different.
http://jsfiddle.net/wNePW/

Checking the names of elements from an array of objects selected by jquery

I'm a beginner in js and jquery library. I'd like to get an array of input fields with a particular name, and validate input. Each of my input fields have a name like NS[0], NS[1] etc. The total number of fields will have to be determined by the code, since the fields are generated by javascript.
I know that I can have jquery address the individual object like this:
$("input[name=NS\\[0\\]]").val() for <input type="text" name="NS[0]">.
However, how can I get an array of all these similiar elements, from NS[0] to NS[x] where x has to be determined based on how many fields have been generated? I already have other fields with different name patterns sharing the same css class, so using class is not an option. These boxes are in a particular div area, but in the same area are other input fields, so choosing all input boxes of the same area selects them as well.
In other words, how do I use jquery to check the name of each input field, after getting the entire array of input fields, to check each individual name?
Since I have input fields of various names in the area determined by the table id CNTR1, I would select them with $('#CNTR1 input'). I can also select individual fields by using $("input[name=]"). However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
The html code:
<table class="table" id="cnservers">
<thead>
<tr>
<th>Type</th>
<th>Preference</th>
<th>Value</th>
<th>Name</th>
</tr>
</thead>
<tr id="CNTR0">
<td>CNAME</td><td><input type="text" name="CN_PREF[0]" value=""></td><td>
<input type="text" name="CN_VAL[0]" value=""></td><td>
<input type="text" name="CN_NAME[0]" value="">
<a class="btn btn-danger" onclick="DelField(this.id);" id="CN_D0" >
<span class="btn-label">Delete
</span>
</a>
<a class="btn btn-primary" onclick="addField('cnservers','CN',10);" id="CN_A0" >
<span class="btn-label">Add
</span>
</td></tr>
</table>
[1]: http://i.stack.imgur.com/bm0Jq.jpg
I must be missing something. Is there a reason you can't use the http://api.jquery.com/attribute-starts-with-selector/?
$('#CNTR1').find('input[name^="NS"]')
Regarding,
However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
$("#CNTR1 input").each(function(index, elem) {
var $elem = $(elem),
name = $elem.attr('name');
var nameMatchesCondition = true; // replace with your condition
if (nameMatchesCondition) {
// do something!
}
});
EDIT 1:
Well, id is still an attribute of an html element. So you could do $('[id^="CNTR1"]') ... The value of the id attribute of an element doesn't contain the #. It's only part of the css/jquery selector. When using attribute style selectors, you don't need it. Though I can't comment on the performance of this.
Ideally, you want to attach a second class, say js-cntr to all elements that you created with an id starting with CNTR. Even though different name pattern elements may already have one class, that class is for styling. There is no stopping you from attaching custom classes purely for selection via js. This is an accepted thing to do and which is why the class name starts with js-, to denote that its purely for use via js for selection.
Try this
HTML
<table id="CNTR1">
<tr>
<td>CNAME</td>
<td><input type="text" name="CN_PREF[1]" id="CN_IN[1]"></td>
<td><input type="text" name="CN_VAL[1]"></td>
<td><input type="text" name="CN_NAME[1]"></td>
</tr>
</table>
JS
$(document).ready(function(){
$("#CNTR1 input").each(function() {
console.log($(this).attr("name"));
// Match With predetermined criteria
});
});
Use jQuery's .filter method, with a filter function:
filterCritera = /^CN_NAME\[/; // or whatever your criteria is
var inputs = $('#CNTR0 input');
// you could also cache this filter in a variable
inputs.filter(function(index){
return filterCritera.test(this.name);
}).css('background','red');
jsbin
The markup you posted does not the markup described in your question ( it does not contain NS[0]) but you can substitute it in the reguluar expression above.

Select all table rows between headers using JQuery

Having the following automatically generated table layout (I have nearly no influence over it)
<table>
<tr>
<th>First Header</th>
<th>
show/hide
</th>
</tr>
<tr>
<td>A question?</td>
<td><input value="User's answer" /></td>
</tr>
<!-- Some more rows -->
<tr>
<th>Second Header</th>
</tr>
<!-- Some more question blocks -->
</table>
... I'd like to select all the <tr>-elements between two headers using Javascript/jQuery
in order to provide such features like:
Hiding all the questions belonging to a certain header.
Automatically edit the <input>s (eg. check/uncheck all or restore default)
The links causing the desired actions are already in the correct headers.
What would be the best way to approach this issue?
You can use nextUntil() to solve this problem.
function getRows(start){
return start.nextUntil(function(i, v){
return $('th', v).length > 0;
});
}
Demo: Fiddle
Implementation of Show/Hide
$('table').on('click', '.used-for-some-action', function(){
getRows($(this).closest('tr')).toggle();
return false;
});
Demo: Fiddle
Update:
Based on comments by #BLSully
$('table').on('click', '.used-for-some-action', function(){
$(this).closest('tr').nextUntil('tr:has(th)').toggle();
return false;
});
Demo: Fiddle
I like Arun P Johny's answer. Here's what I originally thought (this code implements the hide/show functionality)
$(".used-for-some-action").click(function(e) {
e.preventDefault()
$(this).parents("tr").next().is(":visible") ? $(this).parents("tr").next().hide() : $(this).parents("tr").next().show();
});
Fiddle: http://jsfiddle.net/DQMht/1/
I would keep it real simple. You're using JavaScript, so when the page loads, just add a class to rows with a <th>, then use the class.
$(function() {
$("th").parent().addClass("hasTH");
});
Then you can simply target rows that have the hasTH class.
Another option would be to still do it when the page loads, but instead of adding a class, group the rows into new <tbody> elements. This would give you the most pure DOM representation.
Try this:
$("tr:has(th)").each(function(){
if ($(this).find('th').length==2) {
// here you have this: that represent the row which have two td
}
})

jquery function to show/hide textareas based on which option is selected

I'm working up a basic survey and one of the questions is a yes/no question. If the user selects no, I'd like to show a textarea below the question for the user to explain his/her reasons for the no answer. If they click yes, the text box remains hidden (or hides if they had clicked no and shown it).
Here is a snippet of my HTML (yes, I'm using tables for formatting :-) . It saves me time in this case). There are 4 yes/no questions. This is just one of them. The only difference among them are the id names (#explain1, #explain2, #explain3, #explain4)
<tr id="yesno1">
<!-- yes/no1 choices --> <!-- Yes(1) No(0) -->
<td class="center"><input name="yn1" value="1" id="yes1" type="radio"></td>
<td class="center"><input name="yn1" value="0" id="no1" type="radio"></td>
<!-- yes/no1 question -->
<td class="question">
Did you meet your goals during this program? (If no, explain.)
</td>
</tr>
<tr class="explain-box" id="explain1">
<td></td>
<td></td>
<td class="explain-text">
<textarea name="explain1" placeholder="Please explain..."></textarea>
</td>
</tr>
And here is my jQuery. This works with question one:
$(function() {
$('.explain-box').hide();
$('#no1').click(function() {
$('#explain1').show();
});
$('#yes1').click(function() {
$('#explain1').hide();
});
});
I'm fairly fuzzy with javascript and jquery, so my question is how can I make the jquery code work without typing out the condition for each and every ID of every yes/no question? I know that I can use this somehow, but I don't know how to go about it. Can someone provide an idea of a function to use in this case? Should I just bite the bullet and type in each question condition since it's only 4 questions?
Try using the starts with selector:
$(function() {
$('.explain-box').hide();
$('[id^=no]').click(function() {
$(this).parents("tr").next(".explain-box").show();
});
$('[id^=yes]').click(function() {
$(this).parents("tr").next(".explain-box").hide();
});
});
You could give the checkboxes a yes or no class, not just an ID.
Then, using the this syntax you could find the textarea associated with it. Something along the lines of:
$(function() {
$('.explain-box').hide();
$('.no').click(function() {
$(this).parents("tr").next().find('.explain-box').show();
});
$('.yes').click(function() {
$(this).parents("tr").next().find('.explain-box').hide();
});
});
EDIT
You could even simplify this further by writing one function to toggle the textarea:
$(function() {
$('.explain-box').hide();
$('.checkbox').click(function() {
var show = $(this).val() == "0";
$(this).parents("tr").next().find('.explain-box').toggle(show);
});
});
Here's how I would do it — without tables or switches.
$('input:radio').on('change', function(){
// compare against string value of input
if ($(this).val() === '0') {
// show textarea closest to $(this)
$(this).closest('div').find('textarea').show();
}
});
Demo

How do I select a collection of checkboxes...?

I have the html:
<tr>
<td><input type="checkbox" value="3" id="userListingSelect0" cssclass="cbDelete">
</td><td>general</td>
<td>Edit</td>
</tr>
<tr>
<td><input type="checkbox" value="1" id="userListingSelect1" disabled="disabled" cssclass="cbDelete">
</td><td>hmladmin</td>
<td>Edit</td>
</tr>
And im trying to use jQuery to get all of the checkboxes.
Im using:
console.log(jQuery('.cbDelete').html());
But all im getting is undefined. How do I...
1) Get all the elements
2) Iterate through them?
I tried using:
jQuery('.cbDelete').each(function () {
console.log('got here');
if (this.checked) {
selectionMade = true;
}
resultsGot = true;
});
And still it didn't get to to the 'got here' line so it looks like I cant get to collection. Not sure why....
The reason why this line doesn't work is because of the cssclass attribute
console.log(jQuery('.cbDelete').html());
Changing it to class will make this work. Or the answer from Igor.
jQuery class selector works when class attribute is defined, but you have cssclass. So in your case you may try:
$("input[cssclass='cbDelete']");
To iterate through just use each as usual.
You're using a non-standard identifier to give the checkbox a class. Change cssclass to class and then $('.cbDelete') will work; the . (dot) means "class".
As #Igor Dymov says rather abruptly in his answer, using
$("input[cssclass='cbDelete']");
works; this finds any input with the custom attribute cssclass, with a value of cbDelete.
Personally, I'd use a class as it's cleaner, validates well and the selector is simpler (and possibly a bit faster).
$("input:checkbox").each(function(){
console.log('got here');
if (this.checked) {
selectionMade = true;
}
resultsGot = true;
});
If you want to retrieve only those checkbox inside your specified table(let's say your table's id is "table_a"), it will be
$("#table_a input:checkbox").each(function(){
Yeah if the cssClass is just changed to class it works. So your view does not change the cssClass to class? Or was that in source? Some people gave you already answer for if you are using the cssClass in source.
If you are defining that in asp:
<asp:TextBox id="TextBox1" ForeColor="Red" CssClass="class1" />
should render to
<input type=text class="class1" style="ForeColor:red">
http://jsfiddle.net/SdHuK/

Categories

Resources