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

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/

Related

Create a checkbox when checked it should show certain input fields & hide other input fields, within a Modal

<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); } else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
I've been attempting to do this with jQuery, but it hasn't been functioning properly, I have also done a thorough amount of research for ways to condense this code. I was trying to condense the statement with a ternary operator. If you could please assist me with a possible solution that would be great! Thanks (Ternary Solution would be amazing)
The issue with your code is that you have mis-matched quotes in the HTML due to the console.log("X") calls in your code that is messing up the attributes of the input element. If you check the console you'll most likely see some errors relating to this.
It's for this reason, amongst many others, that it's considered bad practice to use inline script (or CSS styling for that matter). The other issues are that it's bad for separation of concerns and makes the code harder to read an edit. It's far better practice to attach your event handlers using unobtrusive Javascript, like this:
$('.seasonal-checkbox').change(function() {
$('#ShowIfChecked').toggle(this.checked);
$('#HideIfChecked').toggle(!this.checked);
});
#ShowIfChecked {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal" class="seasonal-checkbox" />
<div id="ShowIfChecked">Checked!</div>
<div id="HideIfChecked">Not Checked!</div>
Note the use of the change event over click, so that the event is still fired for user who navigate the web using the keyboard. Also note the simplified logic using toggle() to hide and show the relevant content in a single call to each method which negates the need for an if statement - and by proxy a ternary expression too.
You can change your onclick to a function, because at least for me, it is easier to see whats really going on.
So change
<input type="checkbox" runat="server" name="Seasonal" value="Seasonal" id="isASeasonal"
onclick=" if ($(this).is(':checked')) { console.log('Worky'); $('#ShowIfChecked').show(); $('#HideIfChecked').hide(); }
else { $('#HideIfChecked').show(); console.log("No Worky"); }" />
to
<input type="checkbox" runat="server"
name="Seasonal" value="Seasonal" id="isASeasonal" onclick="myFuncton(this)" />
Within your view:
<script>
myFunction(myCheckBox)
{
if(myCheckBox.Checked)
{
console.log('Worky');
$('#ShowIfChecked').show();
$('#HideIfChecked').hide();
}
else
{
$('#HideIfChecked').show(); console.log("No Worky");
}
}
</script>
Now to get the expression/Ternary Solution you want, you can change this script to look like this:
<script>
myFunction(myCheckBox)
{
myCheckBox.Checked ? (console.log('Worky'), $('#ShowIfChecked').show(),
$('#HideIfChecked').hide()); : ($('#HideIfChecked').show(), console.log("No Worky"));
}
</script>
You can find more Info about Ternary Solutions here
We dont write code like this. It fails on every code review.
Do this:
$('#isASeasonal').click(function() { ...});
https://api.jquery.com/click/
Seasonal Address:&nbsp <input type="checkbox" runat="server" clientidmode="Static" name="Seasonal" value="Seasonal" id="isASeasonal"/>
$('#ShowIfChecked').hide(); //Hid What needs to be shown if checked.
$("#isASeasonal").click(function () { //Used Click event on checkBox
($("#isASeasonal").is(':checked')) ? (console.log('worky'), $('#ShowIfChecked').show(), $('#HideIfChecked').hide()) : (console.log('no worky'), $('#HideIfChecked').show(), $('#ShowIfChecked').hide());
What fixed my issue was that in ASP.net I needed to add clientidmode="static" to the div's that I was trying to hide & show. I still don't understand the reason why, I'm currently looking more into it but this is what worked for me but above you can see the majority of the final product with the ternary operator!! Yay.

jQuery click function on an array of inputs

I try to implement a change function on every input field named plz_von.
<input type="text" name="plz_von[]" class="plz_von" placeholder="10000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="20000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="30000">
<input type="text" name="plz_von[]" class="plz_von" placeholder="40000">
I want to do it this way:
$('input[name="plz_von[]"]').change(function() {
alert("got it");
});
I don't know what's going wrong. Any idea? I tried it with the class name as well.
Because [ ] is an attribute selector. You need to escape it.
$('input[name="plz_von\\[\\]"]')
Since you have a class that is common, you might as well use that instead.
$('input.plz_von')
Thanks all for the support. Finally I found the failure.
I had to put the jQuery code into the ready function! This is quite clear, because the function cannot by added to the inputfield, when the input field isn't already loaded in the DOM.. grrr
$(document).ready(function() {
$('input[name="plz_von[]"]').change(function() {
alert("hu");
});
});
Best regards,
Marco

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/

jQuery detects which element is visable

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.

linking HTML checkbox with element to hide when checkbox is unchecked

What's a good pattern for adding additional data to an HTML element? For example, I'd like to link a checkbox to HTML I'd like to hide when the checkbox is unchecked. Like the for attribute of a label element, I want to specify the linkage in markup so I can write a simple, generic script to iterate through all checkboxes and hook up a jquery event handler to do the hiding/showing.
For example, in this HTML:
<input type="checkbox" id="showFoo" />
<div id="foo">
Some HTML here. Hide this when the checkbox is unchecked.
</div>
What's a good to let my script know that #showFoo is related to #foo? Ideally something that doesn't make my HTML non-validating or and doesn't require me to use a specific naming convention for IDs. Extra credit if it makes my script more efficient.
use a data-[key] attribute to identify what #showFoo should control
example jsfiddle
HTML:
<input type="checkbox" id="showFoo" data-toggles="foo" />
<div id="foo">
Some HTML here. Hide this when the checkbox is unchecked.
</div>
jQuery:
$('#showFoo').change(function() {
$('#' + $(this).data('toggles')).toggle();
});
This seems like a perfect case for data elements.
<input type="checkbox" id="showFoo" data-relateddiv="foo" />
Then in an event handler on the checkboxs:
$('#' + $(this).data("relateddiv")).show();
You can use the "rel" attribute
<input type="checkbox" id="showFoo" rel="foo" />
$('#showFoo').click(function(){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
if(element.is(':hidden')){
element.slideDown();
//element.show();
}
else{
element.slideUp();
//element.hide();
}
});
I use this currently
element.each(function(i, e) {
var checked = $(e).prop('checked'),
foo = */Relationship betweeen element and foo*/;
foo .toggleClass('invisibleClass', checked)
.toggleClass('visibleClass', !checked);
});
in case you have multiple foos and elements (you have to define the relationship between them first)
Run it on the event of your choice
Try below
if (checkboxIsChecked) {
foo.visibility:visible;
} else {
foo.visibility:hidden;
}

Categories

Resources