I'm trying to create a page that generates simple custom reports based on the checkboxes a user clicks. On the left side I will have a vertical column of checkboxes. For simplicity's sake, lets say I have two checkboxes labeled "Population" and "Employment".
When a user is interested in seeing employment data they check the "Employment" box and the image file of the data "employment.jpg" will be displayed to the right. If they then uncheck the box, the image will disappear. If they check both boxes, both images will be similarly displayed, one below the other in the order clicked.
I'm am loosely familiar with HTML, and new to Javascript. I've been trying to do this with if statements and document.write but can't keep my checkboxes on the page when the image is generated.
Here's my current code:
<html>
<head>
<script language="javascript" type="text/javascript">
function checker(that) {
if (that.checked) {
document.write("<br /><br /><img src='employment.png'>");
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="Box" onclick="checker(this)"> Employment <br />
</form>
</body>
</html>
Here's a quick example to get you started. You can see it in action here.
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility=="visible") {
el.style.visibility="hidden";
}
else {
el.style.visibility="visible";
}
}
<label for="chkemployment">Employment</label>
<input type="checkbox" id="chkemployment" onChange="toggleVisibility('imgemployment');" /><br/>
<label for="chkpopulation">Population</label>
<input type="checkbox" id="chkpopulation" onChange="toggleVisibility('imgpopulation');" />
<hr />
<img id="imgemployment" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden"/>
<img id="imgpopulation" src="http://www.gravatar.com/avatar/c0d7be6d99264316574791c1e4ee4cc4?s=32&d=identicon&r=PG" style="visibility:hidden" />
This is how the solution looks like in AngularJS:
<script src="http://docs-next.angularjs.org/angular-0.10.1.min.js"
ng:autobind></script>
<p>
<input type="checkbox" name="production" id="production" />
<label for="production">Production</label>
</p>
<p>
<input type="checkbox" name="employment" id="employment" />
<label for="employment">Employment</label>
</p>
<img src="http://i.i.com.com/cnwk.1d/i/bto/20071106/OLPC_photo_540x360.jpg"
ng:show="production" />
<img src="http://www.sunriseenterprisesinc.com/main/Portals/0/EmploymentSmall.jpg"
ng:show="employment" />
You can play with the example here: http://jsfiddle.net/psyho/nrdnx/
You can handle the change event of the checkboxes. Here's a full example (without images, though): http://jsfiddle.net/minitech/hsF9s/
Usually people use a framework such as jQuery. It allows you to abstract away from the nitty gritty details and cross-browser pains. Using that, you would do the task you describe like this:
http://jsfiddle.net/3vQJZ/3/
And here's the code from that working demo:
<input type="radio" name="selectPicture" value="http://i170.photobucket.com/albums/u277/AmandaisAwesomeQUACK/monkey.gif"/>
<input type="radio" name="selectPicture" value="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" checked/>
<img id="image" src="http://freesmileyface.net/smiley/animals/monkey-crush2.gif" alt="image selected by radio buttons"/>
$(document).ready(function(){
$('input[name=selectPicture]').click(function(){
$('#image').attr('src', $('input[name=selectPicture]:checked').val());
});
});
Related
I didn't find an answer here (maybe because my knowledge in JS is very limited), so I decided to ask the question myself:
How can I execute my javascript after a certain event? I have a form and I want the JS to run after the last radio is selected but before submitting the form.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id="myform">
//various fields
</form>
<script type="text/javascript">
function myfunction() {}
</script>
</body>
</html>
I managed the function to run when loading the website and after the last field was filled/radio was checked, but i want it to run ONLY when the last radio was checked.
Thx for everyone to help me
You can use element.addEventListener(“event”, function) and element.removeEventListener(“event”, function) instead of the on attributes. It can make your code much cleaner! Here’s a simple example:
document.getElementById(“button”).addEventListener(“click”, myFunction);
function myFunction(){
alert(“hello world!”);
}
Try: onclick=“myfunction()”
For example if your code is <input type=“checkbox” onclick=“myfunction()”>
Then it might run something like this:
/* Notice how the function below corresponds with the onclick function */
function myfunction() {
alert("Box Checked!")
//Put whatever you want in here
}
function Yes() {
alert("Thanks!")
//Put whatever you want in here as well
}
function No() {
alert("Aw...")
//Put whatever you want in here as well
}
function Submit() {
alert("Thanks!")
}
<!Doctype html>
<html>
<p>Check this box!</p>
<input type="checkbox" onclick="myfunction()">Check me!</input>
<!-- notice the onclick function here -->
<br>
<br>
<p>Fill this form!</p>
<label for="username">Username: </label>
<input type="text" id="username" name="username">
<br><br>
<input onclick="Submit()"type="submit" value="Submit">
<!-- notice the onclick function here as well -->
<p>Is this answer good?</p>
<input onclick="Yes()" type="radio">
<!-- You know the drill ;) -->
<label>Yes! 😀</label>
<br>
<input onclick="No()" type="radio">
<!-- Ditto -->
<label>No! 😭</label>
</html>
This will work for most elements with a user required click (i.e Check Box, Submit button, so on...)
Just insert onclick="myfunction()".
For more information, go to this site:
https://www.w3schools.com/jsref/event_onclick.asp
Hoped this helped!
You can make a function that will do something when a certain condition is met(that is sorta an event in theory in the first place)
In other words, not every living thing that happens dispatches an event of some sort, especially composite things like that. For things like those, just wait until your logical event happens then execute some code.. the following function works like that
function onEvent(condition,whenFulfiled,eventParam){
var i=setInterval(()=>{
if(condition()){
clearInterval(i)
whenFulfiled(eventParam)
}
},0)
}
var checkboxes=document.getElementsByClassName('checkbox')
//example uses
onEvent(
function(){
return [...checkboxes]
.filter(a=>a.checked)
.length == checkboxes.length
},
function(boxes){
console.log("all boxes checked :D\nunchecking them...")
boxes.forEach(a=>a.checked=false)
},
[...checkboxes]
)
<div><h3>when checked all are checked(which is not a real event, this ad-hoc "event listener" would activate)</h3></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
<div><input class="checkbox" type="checkbox" /></div>
I would like to show specific posts on a Wordpress page and hide all others. What posts are to be shown, should depend on checkboxes checked on top of the page. A checkbox corresponds with a class. When (for example) two checkboxes are checked (two classes selected in essence), only posts containing at least those two classes in their wrapping div (besides a possible third or fourth class they may have) should be shown (and all the other posts hidden) instantly on the page.
Does anyone of you know how to pull this off?
I already managed to get the tags assigned to a post in the CMS and transfer those tags to the wrapping div of that very post as its class names, so far so good.
How to write the last piece of needed code from scratch I find very difficult to do with the small amount of knowledge I have. I understand that first the desired classes should be gathered (selected through the checked checkboxes). Then a condition should be formed (class1 AND class3 AND class7 have been selected). Then, if that condition is true for a post (‘your wrapping div contains class1, class3 and class7’), only then the post should be shown. The post could also (for example) contain class2, that’s fine, the filter though is made up of the combination of class1, class3 and class7 being present within the wrapper div, as long as that’s true, it may be shown).
I’m sure this should be a stroll through the park for a lot of you, for me it’s still pretty hard to realise from scratch, so any help you guys could give me is highly appreciated! Thanks in advance!
Thanks for your response so far, guys, closest thing I found online so far is this:
$("#filters :checkbox").click(function() {
$("div").hide();
$("#filters :checkbox:checked").each(function() {
$("." + $(this).val()).show();
});
});
It comes from this setup: http://jsfiddle.net/6wYzw/41/ > here it shows a post when its wrapping div contains classX AND/OR classY, see its working example. I reckon the part where it says
$("." + $(this).val()).show();
... needs to be adjusted, so that right here all the checked checkboxes/classes so far are taken into account using AND, not OR. Is this the only line which actually has to be adjusted in order to make my desired setup work the way I want it too?
#Lisrael > all posts should be displayed at first, then the filter starts to kick in as soon as checkboxes are starting to be clicked just like you said indeed.
Found out how to do this! With the help of an example which came close already and lot's of 'sub'examples here and there. See the code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3 align="center">Boardgamefilter</h3>
<form name="gamesettings">
<input type="checkbox" name="gamesetting" value="1p">1p<br />
<input type="checkbox" name="gamesetting" value="2p">2p<br />
<input type="checkbox" name="gamesetting" value="3p">3p<br />
<input type="checkbox" name="gamesetting" value="4p">4p<br />
<input type="checkbox" name="gamesetting" value="5p">5p<br />
<input type="checkbox" name="gamesetting" value="6plus">6plus<br />
<br />
<input type="checkbox" name="gamesetting" value="15m">15m<br />
<input type="checkbox" name="gamesetting" value="30m">30m<br />
<input type="checkbox" name="gamesetting" value="45m">45m<br />
<input type="checkbox" name="gamesetting" value="60m">60m<br />
<input type="checkbox" name="gamesetting" value="90m">90m<br />
<input type="checkbox" name="gamesetting" value="120mplus">120mplus
<br />
<br />
<input type="button" name="Un_CheckAll" value="Reset"
onClick="UnCheckAll(document.gamesettings.gamesetting)">
</form>
<br />
<br />
<div id="boardgames">
<div class="1p 2p 15m 30m" style="display: block;">1p 2p 15m 30m</div>
<div class="1p 2p 30m 45m" style="display: block;">1p 2p 30m 45m</div>
<div class="2p 30m 60m" style="display: block;">2p 30m 60m</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input[name=gamesetting]').change(function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(".")
var str = (".") + vals
$('#boardgames div').hide();
$('#boardgames div' + (str)).show();
})
function UnCheckAll(chk) {
for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
$('#boardgames div').show();
}
</script>
</body>
</html>
<script type="text/javascript">
function CheckBox(checkerbox, div) {
if (checkerbox.checked) {
document.getElementById(div, Urbanoo).style.display = "block"
} else {
document.getElementById(div, Rurall).style.display = "none"
$("#Rurall").find("*").prop("disabled", true);
}
}
function CheckBox1(checkerbox1, div) {
if (checkerbox1.checked) {
document.getElementById(div, Rurall).style.display = "block"
} else {
document.getElementById(div, Urbanoo).style.display = "none"
$("#Urbanoo").find("*").prop("disabled", true);
}
}
</script>
How to hide a checkbox in function another and disabled all elements to the checkbox disabled?
<input name="Rural" type="checkbox" onclick="CheckBox1(this,'Rurall');" />
<input name="Urbano" type="checkbox" onclick="CheckBox(this,'Urbanoo');" /> Urbanoo </center>
<div id="Urbanoo" style="display:none" >
<g:render template="../DomUrbano/form"/>
</div>
The problem is that when I turn on a check box not the other box is not disabled
<div id="Rurall" style="display:none">
</br>
<g:render template="../DomRural/form"/>
</div>
I think I see what you are attempting but frankly it's less than super clear.
SO what I think you want is;
Hide other checkboxes if I check one
If I do uncheck a box, show the other one again
Show a "partner" area if I check a box
Disable other NOT partner area inputs if I check a box
I modified your markup some to make it easier and also added some additional to clearly show what is happening. I also added a data element for the partner to the input so we can make this all simpler and only have one function; now called via an event handler and NOT with inline code in markup.
Revised markup:
<span class="myinputs"><input class="mycheck" name="Rural" type="checkbox" data-partner="#Rurall" /> Rurall</span>
<span class="myinputs"><input class="mycheck" name="Urbano" type="checkbox" data-partner="#Urbanoo" /> Urbanoo</span>
<div id="Urbanoo" class="hidden others">the Urbannoo
<g:render template="../DomUrbano/form" />
<input type="textbox"/>
</div>
<div id="Rurall" class="hidden others">the Rurall
<g:render template="../DomRural/form" />
<input type="textbox"/>
</div>
Code:
$('.mycheck').on('change', function() {
var amIChecked = $(this)[0].checked;
$(this).parent().siblings('.myinputs').toggle(!amIChecked);
var pt = $(this).data('partner');// get the partner selector
$(pt).toggle(amIChecked);// show the partner in the others list
//do the enable in the partner
$('.others').filter(pt).toggle(amIChecked).find("*").prop("disabled", !amIChecked);
//do the disable in the othes list not the partner
$('.others').not(pt).find("*").prop("disabled", amIChecked);
});
Play with it all here: https://jsfiddle.net/MarkSchultheiss/cLyb103x/1/
I am pretty new to jQuery and need some help with the following.
I have a HTML page with a large, dynamic number of checkboxes and would like to show a checkbox' value on mouseover without having to add a title attribute in the code for each of them.
Also, the value of a checkbox can be different to the text that is shown next to her (label).
The checkboxes are always in a div with the class '.divCheck' and the above applies to all checkboxes in these divs (all set up the same way).
So far I have the following which works as intended but seems to be very slow (at least in my test environment).
Is there a faster / better way to achieve this or can this be written different (either the jQuery or the HTML) to make it run faster ?
My HTML (simplified):
<div class="divCheck">
<input type="checkbox" name="language" class="checkSingle" id="language1" value="de - German" />
<label for="language1">de</label>
<input type="checkbox" name="language" class="checkSingle" id="language2" value="en - English" />
<label for="language2">en</label>
<input type="checkbox" name="language" class="checkSingle" id="language3" value="es - Spanish" />
<label for="language3">en</label>
<!-- ... -->
</div>
My jQuery:
$('div.divCheck label').on('mouseover', function(){
var checkID = $(this).attr('for');
var checkVal = $('#'+checkID).val();
$(this).prop('title', checkVal);
});
Many thanks for any help,
Mike
There is no need to use an event handler, you can set the title programatically like
$('div.divCheck label').attr('title', function(){
return $(this).prev('input').val()
});
$('div.divCheck label').attr('title', function() {
return $(this).prev('input').val()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="divCheck">
<input type="checkbox" name="language" class="checkSingle" id="language1" value="de - German" />
<label for="language1">de</label>
<input type="checkbox" name="language" class="checkSingle" id="language2" value="en - English" />
<label for="language2">en</label>
<input type="checkbox" name="language" class="checkSingle" id="language3" value="es - Spanish" />
<label for="language3">en</label>
</div>
You can set the title attribute of the checkbox to value. By this, you don't need any library/plugin.
$(':checkbox').prop('title', function() {
return $(this).val();
});
Demo: https://jsfiddle.net/zstupsbc/
a tooltip library such as qtip could help you
I'm attempting to get the Website URL field on this page to display only when the previous question has the radio button "Yes" selected. I've searched and tried a few code examples, but they aren't working. Does anyone have any suggestions for me?
Thanks in advance!
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No"> No</label></div>
</div>
</div>
<div class="editfield">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>
I noticed that you initally put the javascript I gave you at the top of the page. If you are going to do this then you need to encapsulate the code in a jquery $(document).ready(function(){ });. You only need to use a document ready when your html follows after the javascript.
$(function() {
// place code here
});
However, in this scenario I have created another alternative that will be better, but do not forget that you have to initially set the web url div as hidden. Also, I highly recommend that you set better control ids; it will make your javascript easier to understand.
$('input[name=field_8]').on("click", function(){
var $div_WebUrl = $('#field_19').closest('.editfield');
if($('input[name=field_8]').index(this) == 0)
$div_WebUrl.show();
else
$div_WebUrl.hide();
});
Live DEMO
I have created a little example:
<div class="editfield">
<div class="radio">
<span class="label">Do you have your own website? (required)</span>
<div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes" onclick="document.getElementById('divUrl').style.display='block'"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No" onclick="document.getElementById('divUrl').style.display='none'"> No</label></div>
</div>
</div>
<div class="editfield" id="divUrl" style="display:none">
<label for="field_19">Website URL </label>
<input type="text" name="field_19" id="field_19" value="" />
</div>
jsFiddle: http://jsfiddle.net/EQkzE/
Note: I have updated the div to include a style, cause I do not know what your css class looks like. Good luck.
Here's a pure JS Solution:
document.getElementById("field_19").parentNode.style.display = "none";
document.getElementById("option_9").onclick = toggleURLInput;
document.getElementById("option_10").onclick = toggleURLInput;
function toggleURLInput(){
document.getElementById("field_19").parentNode.style.display = (document.getElementById("option_9").checked)? "block" : "none";
}
Not a very dynamic solution, but it works.
Something like this will bind the click event to a simple function to look at the radio button and show the other div.
$('#option_9').on('click', function() {
if ($('#option_9').is(':checked')) {
$('#field_19').closest('.editfield').show();
} else {
$('#field_19').closest('.editfield').hide();
}
});
Run sample code