How to grab ID of element which ID has been dynamically given? - javascript

I’m trying to make a simple show when checkbox is checked kind of section but am unable to get a hold of the element because the IDs of the element are assigned dynamically by PHP.
The element will be inside a foreach loop so there will be multiple instances of it with dynamically given IDs.
example:
//Laravel blade template
<element id="attrb{{ $elem->id }}> "></element>
//Javascript
if ($("#attrb*ID").is(":checked")) {
$("#attrbs-container").show();
} else {
$("#attrbs-container").hide();
}

With Jquery
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="attrb1" value="1" />
Run, and check the box. You can replace console.log with your .show or whatever.
The selector input[id^="attrb"] means an input with an id that ^= starts with attrb. You could also use input[type="checkbox"] if these are the only checkboxes you have, but it's less specific.
Change vs Click
change fires when the data (state) of the element changes. click will trigger anytime you click. In this case it probably doesn't matter too much which you use. A better example of change vs click is using radio buttons, and clicking an already checked radio. Checkboxes un-click when checked, radio buttons not so much. I'm just in a habit of using change over click for state changes.
$('input[id^="attrb"]').click(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Run and click the radio 2x. It fires 2 times.
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Do the same thing here, but with change. That's the difference.
DYNAMIC vs Dynamic
What I mean here is DYNAMIC is something that changes at run time on the client, Dynamic is static HTML where the ID changes on the server side only. For DYNAMIC you want to use on like this
$(someparent).on('change', 'input[id^="attrb"]', function(e){ ... });
Where someparent is a static element that doesn't change at runtime. This will use event delegation and "bubbling" to find the content that was changed on the client side.
I don't think you meant DYNAMIC but I included it just in case.
Cheers!

you could create a function with a callback if you're assigning the id with javascript (after an ajax request)
function addID(add, callback)
Then use the funciton:
addId(function(){
//dynamically add ID
}, function(){
// callback function
if ($(“#attrb*ID”).is(":checked")) {
$(“#attrbs-container").show();
} else {
$(“#attrbs-container").hide();
}
})

Related

Disable one group of select elements with checkbox using javascript / jquery

I have a one or more groups of select elements. I need to disable one at a time but both are being disabled. I am using a checkbox to activate the disable action. I am using javascript / jquery.
$(document).ready(function(){
$('#hour-check').change(function() {
$('select').prop('disabled', this.checked);
});
});
JSFiddle LINK
You're using the same id for each check box. These should be unique, or preferably, use a class.
You should also wrap the tables in a containing class to make traversing the DOM easier.
<div class="table-container">
<p>
<input type='checkbox' class="hour-check"> 24hr
</p>
...
Once you've done this you can use the following to disable the appropriate selects:
$('.hour-check').change(function() {
$(this).parents('.table-container').find('select').prop('disabled', this.checked)
});
See https://jsfiddle.net/d58euhas/

How to show/hide a specific image based on which checkbox is clicked (clicking cbox3 should open tinypic3)

I have 10 different checkboxes, each with their unique ID - in sequential order like: cbox1, cbox2, etc.. Each checkbox has an associated "tinybox" div which contains an image, and each image has an ID also in sequential order, like tinypic1, tinypic2, etc.. I'm trying to write a jQuery script so that when a user clicks on any of the checkboxes, it will then either .show() or .hide() that associated tinypic.
For example, let's say a user clicks on the third checkbox, which has id="cbox3", the script should identify this is cbox THREE and therefore show or hide "tinypic3". Each checkbox has a unique ID, but has the same Class (called cboxes).
This jQuery script successfully uses the class to run when any cbox is clicked, but how do I get it to show/hide the associated TINYPIC instead of show/hiding the cbox itself?
<script type="text/javascript">
$(document).ready(function() {
$('.cboxes').click(function() {
if ($(this).prop('checked')) {
$(this).next().show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
$(this).next().hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
</script>
I've tried substituting $(this).next().show(); for $("[id^='tinypic']").show(); or $('input:checkbox[id^="tinypic_"]') but it won't work. I'm obviously not understanding the logic somehow.
Any help is huge! Thanks a lot :)
Here's a sample checkbox for cbox2:
<li>
<input id="cbox2" type="checkbox" name="cbox2" class="cboxes" />
<label for="cbox2">Show</label>
<div class="tinybox">
<img src="http://www.example.com/img/temp.jpg" alt="tinypic2" id="tinypic2" style="display:none;">
</div>
</li>
Here is a working code jsfiddle
$(document).ready(function() {
$('.cboxes').change(function() {
var image = $(this).siblings(".tinybox").find("img");
if ($(this).prop('checked')) {
image.show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
image.hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
So first we should use change event instead of click to handle not only clicks but any changes.
Secondly we should not operate only next item but find sibling by class if html changes we don't need to change the JS code.
And at the end when we find this element we should search within it for image to show it or hide based on checkbox checked state, here we can even improve my code
here is an updated version of jsfillde
$(document).ready(function() {
$('.cboxes').change(function() {
var image = $(this).siblings(".tinybox").find("img");
image.toggle($(this).prop('checked'));
});
});
JSfiddle link : http://jsfiddle.net/evjkvur1/
$(this).next() //refers to the label and not the image,
Try giving
$(this).closest("li").find("img");
This example will allow you to place the tinybox divs anywhere you want on the page, and show/hide them as appropriate.
We use a separator character (the "_") to make it easy to split-off the numeric identifier from the rest of the ID. Alternately, if you cannot refactor your ID tags, you can use the slice() method, thus:
$('input[type=checkbox]').click(function(){
var i = this.id.slice(-2).replace( /\D+/g, '');
alert(i);
});
Instead of using .show() / .hide(), which you probably know well, I used the .animate() method to change the opacity, for two reasons: (1) to demonstrate how it works, and (2) just to keep the DIVs in position (since the element isn't removed from the flow, it is only rendered invisible)
jsFiddle Demo
HTML:
CB 1: <input type="checkbox" id="cb_1" /><br>
CB 2: <input type="checkbox" id="cb_2" /><br>
<div id="tinypic_1"><img src="http://placekitten.com/50/51" /></div>
<div id="tinypic_2"><img src="http://placekitten.com/48/50" /></div>
javascript/jQuery:
$('input[type=checkbox]').click(function(){
var i = this.id.split('_')[1]; //split into array at the _ & choose 2nd element
var vis = ( $(this).prop('checked') ) ? 1 : 0; //1=checked, 0=not
$('#tinypic_'+i+' img').animate({
'opacity' : vis
},800);
});
CSS:
div{display:inline-block;margin:10px;}
img{opacity:0;}

Dynamically creating input elements onclick

Hey guys so I am creating input elements within a div when I click on a specific radio button with a javascript function.
It works great but when I first load the form the input elements dont appear in the div because the radio button has not been "clicked yet" although one of the radio buttons is default checked.
Basically if its checked I want them to appear, so on body load I have to call a function that checks the radio button I want default and I have to manually display the corresponding input elements that would appear if I had clicked the radio button.
This seems like a dumb work around of what I am trying to achieve, any ideas?
<body onload="startup()">
<input type="radio" name="type" onclick="createInput()" id="testradio" value="test">test</input>
<div id="area">
</div>
</body>
function startup()
{
document.getElementById("testradio").checked = true
createInput();
}
function createInput()
{
var testinput = "<input name='options' value='testing' type='checkbox'>test<br>"
document.getElementById("area").innerHTML = testinput
}
You should set the default value and then call the event. (say onchange)
something like this:
document.getElementById('elID').onchange();
this will then let your event listener fire as if the value where changed in the ui not in code.

Get widgetVar with JavaScript or check/uncheck all other PrimeFaces checkboxes

I have several PrimeFaces checkboxes on a page. If you click the master checkbox, all other checkboxes should be checked/unchecked. With plain HTML checkboxes this would be an easy issue. But because PrimeFaces does not show the checkbox itself, but an image, the following JavaScript code does not work:
<script type="text/javascript">
$(document).ready(function() {
var masterCheckbox = $(".ui-chkbox.master :checkbox");
var slaveCheckboxes = $(".ui-chkbox:not(.master) :checkbox");
updateMaster();
masterCheckbox.change(updateSlaves);
slaveCheckboxes.change(updateMaster);
function updateMaster() {
var allSlavesChecked = true;
slaveCheckboxes.each(function() {
if (!$(this).is(':checked')) {
allSlavesChecked = false;
}
});
masterCheckbox.attr("checked", allSlavesChecked);
}
function updateSlaves() {
var masterChecked = masterCheckbox.is(":checked");
slaveCheckboxes.each(function() {
$(this).attr("checked", masterChecked);
});
}
});
</script>
I know that I could use the PrimeFaces widgetVar to toggle the checkboxes, but I do not know how to get the PrimeFaces widget objects with JavaScript. I think RichFaces adds the component property to the DOM element, but PrimeFaces does not. Does somebody know a solution for this problem?
You were correct -- if you create your component like this:
<p:selectBooleanCheckbox value="val" widgetVar="myCheckbox"/>
You can access the checkbox simply by refering to its widgetVar, in this case calling the PrimeFaces client-side API to mark it as checked:
<script>
myCheckbox.check();
</script>
You could then tie the onchange event of your master checkbox to a javascript method that checked or unchecked the state of all the "slave" checkboxes depending on the state of the master checkbox (would suggest you store the state in a hidden field).
Note, it may make your life easier to instead handle the "change" ajax event and implement the check/uncheck logic on the server side. Just make sure that you provide all the ids of all the slave checkboxes in the update attribute of the p:ajax component:
<p:selectBooleanCheckbox id="masterChkBox" ...>
<p:ajax event="change" listener="#{yourBean.handleMasterChange}" update="...all slavecheckbox ids..."/>
</p:selectBooleanCheckbox>

Jquery checkboxes within containing table selector question

My current code:
<script type="text/javascript">
function checkAll(checked) {
$("input[type='checkbox']:not([disabled='disabled'])").attr('checked', checked);
}
</script>
<input type="checkbox" id="cbxSelectAll" onclick="checkAll(this.checked);" />
The short version:
How do I modify the function call and method above to check all checkboxes inside a table containing the checxbox form element.
The long version:
I am creating a WebUserControl containing a grid view in asp.net that is going to have a delete option. I would like the delete to be a series of checkboxes with one a box in the header to select all of them. What this amounts to for non ASP.NET people is a table with a header row that has a checkbox and every row also has a checxbox.
I have used the above code to check all boxes on the entire page. That won't work here though because I want to have multiple of these on the page at once each working independently. I know I could use a selector to select all the boxes if I ID'd the table but that would require some coding to name the table uniquely and then put that name in the script block.
Really what I would like is to modify the script above to check all checkboxes in the containing table of the "select all" box. The table containing the checkbox could be nested within others but I don't see any being nested within it, or if there are and the nested table also contains checxboxes I don't care if they also get selected.
Thanks for your help.
First, don't mix your HTML and your Javascript. Use event handler binding instead.
Second, use closest to get the nearest ancestor element of a particular type:
$(document).ready(function(){
$('#cbxSelectAll').click(function() {
$(this)
.closest('table') // get the parent table element
.find("input:checkbox:enabled") // find children that match the selector
.attr('checked', this.checked); // set their checked value
});
});
Change your inline attribute to this:
<input type="checkbox" id="cbxSelectAll" onclick="checkAll.call(this);" />
And your checkAll() to this:
function checkAll() {
$(this).closest('table').find("input:checkbox:enabled").attr('checked', this.checked);
}
Using .call(), it is called from the context of the element clicked.
Then the jQuery gets the closest()(docs) <table> and finds the inputs using the checkbox-selector(docs) and the enabled-selector(docs) .
Then when using the attr()(docs) method, you can use this.checked to set the checkboxes to the current state of the one checked.
You can find the table containing the select all using .closest
function checkAll(checked) {
var $table = $(this).closest('table');
$table.find("input[type='checkbox']:not([disabled='disabled'])")
.attr('checked', checked);
}
If there might be several nested tables it's often easiest to specify the one you want with a class, e.g. $(this).closest('table.tableOfCheckboxes'); where you add class tableOfCheckboxes to the table you want to find.

Categories

Resources