I am going to try to be as concise as I can :) I am working on a project. This project generates many pages full of thumbnail images with checkboxes next to them. There can be a varying ammount of total thumbnails. The thumbnails are sorted into 1000 item html pages. So 1000 thumbnails an html page. These pages full of thumbnails are called by a parent html page via iframe. My goal is to have the ability for a user to check checkboxes near these thumbnails, then load a new page into the iframe, checkboxes there, then be able to load the previous page into the iframe, and for the javascript to check the boxes the user had previously checked. I keep track of which checkboxes the user checked by using an array.
Here is the javascript. There is TWO issues! First issue is, I have the alert there for debugging. It does alert the correct values, but it alerts all of the values stored in the array. I wish it to only alert the checkboxes that exist within the iframe page, which is why I have it to the document.getElementByNames. Then... it doesn't check any of the boxes! No box checks :(
Any thoughts on how to accomplish this? the JS and HTML is below...
JS
function repGenChk(valNam) {
var chkN = valNam.name;
parent.genL.push(chkN);
alert(parent.genL);
}
function chkSet() {
for (var i = 0; i < parent.genL.length; i++) {
var item = parent.genL[i];
var item = document.getElementsByName(item);
if (item != null) { document.getElementsByName(item).checked=true; }
alert(parent.genL[i]);
}}
window.onload = chkSet();
HTML
<input type="checkbox" onClick="repGenChk(this);" value="1" name="1">
<input type="checkbox" onClick="repGenChk(this);" value="2" name="2">
<input type="checkbox" onClick="repGenChk(this);" value="3" name="3">
<input type="checkbox" onClick="repGenChk(this);" value="4" name="4">
so on and so forth for Xthousands of checkboxes....
Any thoughts, ideas, constructive criticism and critiques are EXTREMELY welcome! I've gotten alot of jQuery suggestions in the past, and i'm heavily starting to consider it.
Thanks so much everyone!
EDIT - I was able to figure it out. I didn't think I could use IDs with checkboxes, I can. Woo!
JS
function repGenChk(valNam) {
var chkN = valNam.id;
parent.genL.push(chkN);
alert(parent.genL);
}
window.onload = function chkSet() {
for (var i = 0; i < parent.genL.length; i++) {
if (document.getElementById(parent.genL[i]) != null) { document.getElementById(parent.genL[i]).checked=true; }
}
}
HTML
<input type="checkbox" onClick="repGenChk(this);" id="1">
<input type="checkbox" onClick="repGenChk(this);" id="2">
<input type="checkbox" onClick="repGenChk(this);" id="3">
<input type="checkbox" onClick="repGenChk(this);" id="4">
etc etc etc.....
:)
Consider putting a single click listener on an element containing the checkboxes. Give each checkbox a unique id or name. When you get a click on the container, check where it came from. If it's from a checkbox, add or remove the name/id of the checkbox to an object storing which ones are checked depending on whether the checkbox is checked or not.
When you want to re-check them, iterate over the object (using for..in) and use getElementById or getElementsByName(…)[0] to check the checkbox. That way you only iterate over as many object properties as there are checked checkboxes and also getElementById is very fast, so things should be simpler and faster.
BTW, getElementsByName returns a collection, which is array-like but it isn't an array.
Related
I think that my problem isn't very hard -but I'm pretty new to this and having issues finding an easy solution.
I have a form that collects a few items, and an output page that creates a table based on those few items. For example, one of the form options is "Which leg is affected?" And you must choose either "Left, Right, Both".
I would like to create a radio selection option on the view so that the person using this tool won't have to click the back button to update this one field. The table that is built changes based on this one selection, so it would be nice to see those changes without resubmitting the form.
If anyone can point me in the right direction - either JavaScript or some method that involves re-sending the form values from the view - I would be very grateful.
I believe what you're describing is exactly what the idea of "single page app" style coding with Javascript is for - modifying the page with logic without necessarily needing to make a server request. I.e., you want to make an "application." Albeit a simple one.
What I recommend you look into is "event handlers," specifically the click handler.
So, if you had html that looked like: (stolen from MDN's radio page)
<form id="radio_form">
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1"
name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2"
name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3"
name="contact" value="mail">
<label for="contactChoice3">Mail</label>
</div>
</form>
You could then have code that looked like
var radio = document.getElementById('radio_form');
radio.onclick = changeTable;
function changeTable(e){
// Do logic here to change table
}
The idea is your page is "waiting" for the form to be "clicked" (you could also look into onChange), and when it is clicked, a function is invoked that does further logic.
See here to figure out how to get the value of a selected radio.
See here for using javascript to insert a row into a table (what you may want to do in your changeTable function).
EDIT: One "gotcha" to look out for is if your script is running when the page is actually loaded. This can be a problem if your page loads asynchronously (doubtful). Just in case, also look into some kind of document.ready implementation: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
You can add an event listener for 'click' to each radio input and have the callback function modify the view in whatever way you want.
Here's an example:
const form = document.querySelector('.choice-form');
const display = document.querySelector('.display');
form.querySelectorAll('input[type="radio"]').forEach(input => {
input.addEventListener('click', () => {
display.innerHTML = "";
if (input.id === '1') {
display.innerHTML = "<span>You selected: <span class='red'>One</span></span>";
} else if (input.id === '2') {
display.innerHTML = "<span>You selected: <span class='blue'>Two</span></span>";
}
});
});
.red {
color: red;
}
.blue {
color: blue;
}
<div>
<form class='choice-form'>
<label for='choice'>Make a choice</label>
<input type='radio' id='1' name='choice'/>
<label for='1'>One</label>
<input type='radio' id='2' name='choice'/>
<label for='2'>Two</label>
</form>
<div class='display'>
</div>
</div>
Slightly odd question, but I'm trying to find a way (if possible) to select all radio buttons that have the same value. We regularly get hundreds of spam accounts signing up on our website, and it would be easier to set all radio buttons to "Reject" and double-check to make sure there's no legitimate ones, as opposed to constantly clicking on a radio button. (Lazy is my middle name, yes.)
Is this possible? If so, how? I haven't got access to the actual web pages to code in a button to do just this yet, but it's something I'm looking at long term. Right now though, I need something quick and dirty to do what I want it to do. I'm using Chrome, and can use Greasemonkey if that's required.
The value to select by is "reject".
A snippet of code that's being used. If it's of any consequence, our forum is running Xenforo:
<li>
<label for="ctrl_users16667action_reject">
<input type="radio" name="users[16667][action]" value="reject" class="Disabler" id="ctrl_users16667action_reject">
Reject and delete with rejection reason:
</label>
<ul id="ctrl_users16667action_reject_Disabler" class="disablerList">
<li>
<input type="text" name="users[16667][reject_reason]" value="" size="45" placeholder="Optional" class="textCtrl" id="ctrl_users16667reject_reason">
</li>
</ul>
</li>
You're looking for a bookmarklet or a GreaseMonkey (or TamperMonkey or similar) script.
Re bookmarklets, you can use the javascript: pseuedo-protocol to run script on the page you're looking at from your bookmarks manager. Just make the URL in your bookmark:
javascript:(function() { /* ...your code here ...*/ })();
Because it has to be URI-encoded, you can find "bookmarklet generators" out there to handle that part for you.
Alternately, there are GreaseMonkey, TamperMonkey, and similar add-ons/extensions for browsers.
Then it's a trivial matter of selecting the relevant radio buttons:
$('input[type=radio][value="reject"]').prop('checked', true);
So if jQuery is already loaded on the page in question, you could use this as a bookmarklet:
javascript:(function(){$('input[type=radio][value="reject"]').prop('checked',true);})();
Use :radio to get radio buttons, then for filtering use attribute equals selector
var $ele = $(':radio[value="reject"]')
or filter()
var $ele = $(':radio').filter(function(){ return this.value == 'reject'; });
FYI : It's a jQuery solution and it only works if you are loaded jQuery library in the page.
Try this it will work
$("input:radio[value=reject]")
you have to give unique name to all radio buttons then you can select multiple radio buttons using javascript
you have to give same class to radio button
<input type="radio" name="radio[]" class="my_class" value="1" />
<input type="radio" name="radio[]" class="my_class" value="1" />
<input type="radio" name="radio[]" class="my_class" value="0" />
$(".my_class").each(function(){
if($(this).val() == "1"){
$(this).attr('checked','checked);
}
});
Thanks
I'm trying to write JavaScript code where a radio button should be populated if a checkbox is checked.
Following is the HTML code:
<form>
<h3>Radio Buttons</h3>
<input type="radio" name="radio1" id="radio1"> Radio 1
<br>
<input type="radio" name="radio2" id="radio2">Radio 2
<br>
<br>
<h3>Checkbox Groups</h3>
<h4><u>Group 1</u></h4>
<p align="center"><u>PD</u></p>
<ul>
<li>
<input id="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1</li>
<li>
<input id="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2</li>
</ul>
<p align="center"><u>ID</u></p>
<ul>
<li>
<input id="idcb" type="checkbox" name="G1ID1" onclick="validate()">G1 ID1</li>
<li>
<input id="idcb" type="checkbox" name="G1ID2" onclick="validate()">G1 ID2</li>
</ul>
<h4><u>Group 2</u></h4>
<p align="center"><u>PD</u></p>
<ul>
<li>
<input id="pdcb" type="checkbox" name="G2PD1" onclick="validate()">G2 PD1</li>
<li>
<input id="pdcb" type="checkbox" name="G2PD2" onclick="validate()">G2 PD2</li>
</ul>
<p align="center"><u>ID</u></p>
<ul>
<li>
<input id="idcb" type="checkbox" name="G2ID1" onclick="validate()">G2 ID1</li>
<li>
<input id="idcb" type="checkbox" name="G2ID2" onclick="validate()">G2 ID2</li>
</ul>
</form>
So here's what I want the JavaScript to do: If any of the PD checkboxes are selected, then the radio button Radio 1 should get selected. If none of the PD checkboxes are selected, then the radio button Radio 2 should get selected. Similarly, if none of the checkboxes are selected, then NONE of the radio buttons should get selected.
So far, I've written the following JS code:
function validate()
{
if(document.getElementById("pdcb").checked) //if pdcb checkbox(es) is/are checked
{
document.getElementById("radio1").checked = true;
document.getElementById("radio2").checked = false;
}
else if (!document.getElementById("pdcb").checked) //if none of the pdcb checkbox(es) is/are checked
{
document.getElementById("radio1").checked = false;
document.getElementById("radio2").checked = true;
}
else //if no checkbox is checked, then don't populate any radio button
{
document.getElementById("radio1").checked = false;
document.getElementById("radio2").checked = false;
}
}
PS: I need the code to be in pure JavaScript. I can't use jQuery.
Edit
I apologize for getting my requirements wrong. But here's the correct requirement. If any of the PD checkboxes are selected, then the radio button Radio 1 should get selected. If none of the PD checkboxes are selected, then the radio button Radio 2 should get selected. Similarly, if none of the checkboxes are selected, then NONE of the radio buttons should get selected.
I want to first point out that if you were testing this in a JSFiddle, the LOAD TYPE needs to be set to "No Wrap-in " for your inline onclick events to work.
Now, to your code. Document elements can either be tied to a class or ID. Classes are for when you're using elements that share the same functionality, styling, etc.; ID's are for unique elements and unique elements only. For example, in your JavaScript, when you try to test for checked pdcb elements with
document.getElementById("pdcb").checked
JavaScript simply grabs the first element on the page with the ID of pdcb. You have four elements with this ID name; this means that the last three pdcb elements are ignored and never evaluated.
Instead, let's utilize
document.getElementsByClassName("pdcb")
Note the plural form of the word 'Element'. What this does is it returns an array of all elements with the class name of pdcb. We'll get to the fact that we're dealing with an array in a few minutes. First, let's change most of your HTML ID's to classes.
<ul>
<li>
<input class="pdcb" type="checkbox" name="G1PD1" onclick="validate()">G1 PD1</li>
<li>
<input class="pdcb" type="checkbox" name="G1PD2" onclick="validate()">G1 PD2</li>
</ul>
You're going to want to do this for all of your pdcb and idcb elements. Feel free to preserve radio1 and radio2 as ID's because they're unique elements, not reused like pdcb and idcb are.
Now we can address the JavaScript; you're HTML is fine from here assuming you've made the changes necessary from above. Since we changed things from ID's to classes, expressions like the following simply won't do.
document.getElementById("pdcb")
Recall the solution that I wrote earlier:
document.getElementsByClassName("pdcb")
Also recall that I said that this will return an array of elements; in your case, four pdcb elements.
One option that you have at your disposal for tackling this problem is that you can iterate through the array of elements returned by document.getElementsByClassName("pdcb") to evaluate whether any pdcb class has been checked. It'll look something like this:
var pdcbClass = document.getElementsByClassName("pdcb");
//for each pdcb class on our HTML document
for (var i = 0; i < pdcbClass.length; i++) {
if (pdcbClass[i].checked == true) {
//the next two lines are straight from your JavaScript code
document.getElementById("radio1").checked = true;
document.getElementById("radio2").checked = false;
}
}
As you can imagine, we can use the exact same idea for the idcb class elements on your page. By the time we're done, we should have something like what you see below.
function validate()
{
var pdcbClass = document.getElementsByClassName("pdcb");
var idcbClass = document.getElementsByClassName("idcb");
console.log(this);
for (var i = 0; i < pdcbClass.length; i++) {
if (pdcbClass[i].checked == true) {
document.getElementById("radio1").checked = true;
document.getElementById("radio2").checked = false;
}
}
for (var i = 0; i < idcbClass.length; i++) {
if (idcbClass[i].checked == true) {
document.getElementById("radio1").checked = false;
document.getElementById("radio2").checked = true;
}
}
}
But there's a problem! No matter what check box fires off this validate() function, no check box is ever turned off. That means if we check a box with the pdcb class and then check a box with the idcb class, the pdcb box still stays checked; we never said to uncheck it. What this means is that even though it was an idcb click that triggered validate(), all of the code in the function gets executed. Either you have to have the user manually uncheck the previous box before checking a new one, or you need to write some code that does this same thing. Specifically, when a new check box is checked, you need to clear the previous box(es) of their checked property.
That is an entirely different problem and merits a different question. Also consider that this isn't the only way to write this event/functionality, but you're making good progress.
Here's essentially the code you need to keep on going.
https://jsfiddle.net/a4k9xggu/
I want to make it so that the drop-down is only displayed when the radio button (option 3) is clicked and have it hidden if either 1 or 2 is selected. What would be the best way to complete this? I have a little bit of experience with JavaScript and slim to none with jQuery but it seemed like it might be the way to go.
Thanks for any help,
Dan
Here is the HTML code I have as of now:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" /> Option 1 </label>
<label><input type="radio" name="select" /> Option 2</label>
<label><input type="radio" name="select" /> Option 3</label>
</div>
<div id="list" style="display: none;">
<label>Please Select From the List:
<select>
<option>True</option>
<option>False</option>
</select>
</label>
</div>
$(document).ready(function(){
$("[name=select]").change(function(){ // Whenever the radio buttons change
$("#list").toggle($("[name=select]").index(this)===2); // Only keep the list open when it's the last option (First option = 0, Third option = 2)
});
});
This code in action.
Assuming you are using jquery, as it sounds like it from your question, you could modify your HTML like so:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" id="option1" /> Option 1 </label>
<label><input type="radio" name="select" id="option2" /> Option 2</label>
<label><input type="radio" name="select" id="option3" /> Option 3</label>
</div>
<div id="list">
<label>Please Select From the List:
<select id="mySelect">
<option>True</option>
<option>False</option>
</select>
</label>
</div>
</p>
Then you could write some jquery like so:
$(document).ready(
function()
{
$("#option1, #option2, #option3").click(
function()
{
if (this.id == "option3")
$("#mySelect").hide();
else
$("#mySelect").show();
});
});
You can see it working here: http://jsfiddle.net/AVFuY/3/
EDIT: I removed the unneeded class and just used the id's so as to not confuse and add unnecessary code.
Since this is a fairly basic question, I think it'll be instructional to walk you through the jQuery documentation while I answer your question. If you know truly nothing about jQuery, I recommend following this short tutorial first -- it will make things much, much easier for you in the future: jQuery Documentation - Getting Started With jQuery
Your requirement is that something happens (in this case, another element is hidden/shown) when we click the radio buttons. There's two parts to this problem: first, we need to find the radio buttons, then we need to make something happen when we click it.
1. Finding the radio buttons
Take a look at the jQuery Selector documentation here: http://api.jquery.com/category/selectors/
As you can see, there's a specific pseudo-selector for radio buttons, ":radio". We want to select everything inside of the element with ID "buttons", so this is how the selector will look in total:
$("#buttons input:radio");
By the way, it's called a "pseudo-selector" because it filters items we've already selected (in this case, input tags inside of a div with id "button"). Pseudo-selectors always start with a ":".
2. Making something happen when we click them
Consult the jQuery Events reference here: http://api.jquery.com/category/events/
We want the ".click()" event here, clearly. Once we've selected our elements, we can apply a click handler to them like this:
$("#buttons input:radio").click(function() {
// make something happen here
alert("input button clicked: " + $(this).index());
});
Note that this will apply the same click handler to all three of the input buttons, but you can access the specific element that was clicked via the "this" keyword. Wrapping $() around it makes it into a jQuery selection rather than just a Javascript object and allows us to call jQuery functions on it.
3. Hiding and showing the list element conditionally
Let's extend the code above to actually hide and show that other div, depending on which item was clicked. We're going to refer to the jQuery Effects documentation so that we can make hiding and showing it exciting: http://api.jquery.com/category/effects/
The functions we'll be using are ".slideUp()", which hides an element, and ".slideDown()", which shows it. We'll also be using the ".index()" function I used in the previous example to figure out which button was clicked, although I recommend giving the button a unique ID in the future so that your code isn't dependent on the order of the buttons. Here's the final code:
$("#buttons input:radio").click(function() {
// if it was the third button (0-indexed, so the 3rd one is index 2)...
if ($(this).index() == 2) {
// display the element with ID "list"
$("#list").slideDown();
}
else {
// hide the element with ID "list"
$("#list").slideUp();
}
});
Sorry for the length of this answer, but hopefully it was more conducive to your understanding of jQuery than "copy and paste this 3-line super-compact solution".
<label><input type="radio" name="select" onclick="document.getElementById('list').style.display=this.checked?'':'none'" /> Option 3</label>
Without changing your markup:
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
if (myindex == 2)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
EDIT: Another option: just show it on the last button in the list.
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
var lastone = $("#buttons input:radio[name=select]:last").index("#buttons input:radio[name=select]");
if (myindex == lastone)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.
Here is a thought:
As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. MSDN on Injecting Client Side Script
Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter
function TrackMyCheckbox(ck)
{
//keep track of state
}
<input type="checkbox" onClick="TrackMyCheckbox(this);".... />
You have to generate your javascript too, or at least a javascript data structure (array) wich must contain the checkboxes you should control.
Alternatively you can create a containing element, and cycle with js on every child input element of type checkbox.
If it's your only checkbox you can do a getElementsByTagName() call to get all inputs and then iterate through the returned array looking for the appropriate type value (i.e. checkbox).
There is not much detail in the question. But assuming the the HTML grid is generated on the server side (not in javascript).
Then add classes to the checkboxes you want to ensure are checked. And loop through the DOM looking for all checkboxes with that class. In jQuery:
HTML:
<html>
...
<div id="grid">
<input type="checkbox" id="checkbox1" class="must-be-checked" />
<input type="checkbox" id="checkbox2" class="not-validated" />
<input type="checkbox" id="checkbox3" class="must-be-checked" />
...
<input type="checkbox" id="checkboxN" class="must-be-checked" />
</div>
...
</html>
Javascript:
<script type="text/javascript">
// This will show an alert if any checkboxes with the class 'must-be-checked'
// are not checked.
// Checkboxes with any other class (or no class) are ignored
if ($('#grid .must-be-checked:not(:checked)').length > 0) {
alert('some checkboxes not checked!');
}
</script>