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;
}
Related
I have a dynamic page that can have a lot of input[type="file"] fields. I need to change the label of every input once a file is selected.
So, for each input, if:
Empty: text = "upload";
File selected: text = name of file.
Here is a sample of HTML:
<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>
I know how to do this for a single input, using this code:
$('label[for="upload-qm1"] span').text($(this).val());
However, I don't know how many input fields I will have on my page. I tried something like this:
$(this).parent('label').find('span').text($(this).val());
but unfortunately it doesn't work. Any help on how I can get a method for changing all input fields?
You can use DOM traversal to find the span related to the input which was changed. Try this:
$('input:file').change(function() {
$(this).prev('span').text($(this).val());
})
Working example
The most of the code you tried ist corret.
The problem is that you have set a parameter for the parent() function.
Try something like this:
$(this).parent('label').find('span').text($(this).val());
Also make sure that $(this) is the input field not the label itself,
if you click on the label $(this) is the label.
$('input[type="file"]').on('change', function() {
id = $(this).attr('id');
console.log("change event")
var file = $('#'+id).val().split('\\').pop();
if(file!='') {
$('label[for="'+id+'"] span').text(file)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>
I want to check a checkbox if a certain input field is populated.
The solution below works initially. After I enter input, the checkbox is correctly checked. After the input is deleted, the checkbox is unchecked. But after entering input again, the checkbox does not get checked.
<html>
<head>
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(":input").blur(function() {
var val = $(this).val();
var myclass = $(this).attr("class");
if (val != null && val.length > 0) {
$(":checkbox." + myclass).attr("checked", "checked");
} else {
$(":checkbox." + myclass).removeAttr("checked");
}
});
});
</script>
</head>
<body>
<form action="#" method="POST">
Name is selected? <input id="isNameSelected" type="checkbox" name="isName" class="name_input"></input><br/>
Name: <input class="name_input" id="name" type="text" name="Name"></input>
</form>
</body>
</html>
Operating on the attribute via .attr() is what's messing you up; I haven't thoroughly investigated but I suspect it has to do with the juggling that jQuery does with attributes like "checked".
You can replace the whole if statement with:
$(":checkbox." + myclass).prop("checked", !!val);
That'll check or uncheck the checkbox according as whether the text field is non-empty.
Note that because you trigger the handler for any :input element, it'll also trigger when you get a "blur" event from the checkbox.
Also, in my opinion it's a fragile coding practice to rely on the "class" attribute having just one string in it. If you need to group these fields, you can do that either with a container element from which you could use .closest() and .find() to locate companion fields, or else use a data- attribute for what you're currently using the "class".
This would also work (and take up 2 less lines of code):
$(document).ready(function() {
$("#name").blur(function() {
$('#isNameSelected').prop('checked', $(this).val());
});
});
I have horizontal jQuery checkbox. It should display some text when it is clicked and remove the text when it is clicked again and unchecked. However, when i first load the page and click on the box nothing happens. Then when i click it again to uncheck the text appears. It seems the opposite behaviour of what i expect is going on. Here is the code:
(I can solve this problem by simply inverting the boolean sign but i want to understand why this is happening).
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a">
<label for="checkbox-h-2a" onclick="onfilter()">Vegetarian</label>
</fieldset>
</form>
<script>
function onfilter(){
if ($("#checkbox-h-2a").prop('checked')){
document.getElementById("hehe").innerHTML = "Yo there";
}
if (!($("#checkbox-h-2a").prop('checked'))){
document.getElementById("hehe").innerHTML = "";
}
}
</script>
You're already loading jQuery , so just use jQuery for everything - it is much easier , works better, really the only downside to jQUery is having to load it - and you're already doing that. So I would suggest using something like this:
$(function(){
$(document).on('click', '#checkbox-h-2a', function(){
if ( $(this).is(':checked') ) {
// Do stuff
}
else{
//Do stuff
}
});
});
Also, I hope you are actually closing your input element in your HTML , and that this is just a typo in your question
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a"
try:
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Select your type of Restaurant:</legend>
<label for="checkbox-h-2a" >Vegetarian
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" />
</label>
</fieldset>
see how the label goes around the checkbox? also you can get rid on the inline function in HTML with the jQuery I provided
EDIT:
2 problems - one you selectd jQuery 1.6 , to you .on() you need a newer version , if you must use old jQuery let me know ,
the other problem is that all jQuery code must be wrapped in
$(document).ready(function(){
/// code here
});
or for short:
$(function(){
// code here
});
The problem is at the time of clicking on the label, the checkbox's checked has not been changed, so you have to toggle the logic (although it looks weird) or attach the handler to the onchange event of the checkbox input instead:
<!-- add onchange event handler -->
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a"
onchange="onfilter()"/>
<!-- and remove the click handler -->
<label for="checkbox-h-2a">Vegetarian</label>
Demo.
It involves how a label works, when clicking on the label, it looks for the attached input element via the for attribute and trying to change the appropriate property (checked for checkbox, radio, ...) or focusing the element (for textbox fields). So at the clicking time, it processes/calls your handler first. Hence the problem.
Note that this answer just fixes the issue, not trying to improve your code.
I am trying to add the class "current" to whatever radio option is currently selected. I can use
onClick="document.getElementById('volunteering').class += 'current';"
However, this will indeed add the class, but it sticks when you select another radio button (because it's on each button). Any thoughts on how to implement it across all radio buttons?
Here is the code I am using:
<form>
<ul>
<input type="radio" name="category" id="volunteering" value="volunteering"><li class="conversation">
<a href="#" onClick="document.getElementById('volunteering').checked = true;" >Volunteering</a>
</li>
<input type="radio" name="category" value="cityproblems" id="cityproblems"><li class="conversation">
<a href="#" onClick="document.getElementById('cityproblems').checked = true;" >City Problems</a>
</li>
<input type="radio" name="category" value="safety" id="safety"><li class="conversation">
Safety
</li>
</form>
You need to first remove that class from all radio buttons, then add it back to the clicked one. Define a function that does this by receiving the id as a parameter, and bind that to the onclick.
function selectRadioClass(radioId) {
// Note - there are more clever ways, like arrays and loops
// for this, but if it's only 3, this is fine
document.getElementById('volunteering').className = '';
document.getElementById('cityproblems').className = '';
document.getElementById('safety').className = '';
// Then add it back to the node passed in by id
document.getElementById(radioId).className = 'current';
// And check the button
document.getElementById(radioId).checked = true;
}
Then bind each radio button's onclick using:
Safety
There are 2 solutions:
Use CSS3 :checked selector
form input:checked {
/* your style rules here. */
/* No more scripting needed. */
}
http://www.quirksmode.org/css/enabled.html
Use A global function for this purpose.
// check Michael's solution.
Use CSS pseudo selectors and forget the JavaScript. There is one for element:checked.
http://css-tricks.com/pseudo-class-selectors/
This is a bit of a long question so please bear with me guys.
I needed to make a form submit automatically when a checkbox was ticked. So far I have the code below and it works perfectly. The form must submit when the check box is either checked or unchecked. There is some PHP that reads a database entry and shows the appropriate status (checked or unchecked) on load.
<form method="post" id="edituser" class="user-forms" action="--some php here--">
<input class="lesson" value="l101" name="flesson" type="checkbox" />
</form>
<script>
$('.lesson').change(function() {
$('.user-forms').submit();
});
</script>
However, when I introduce a fancy checkbox script which turns checkboxes into sliders it no longer works. The checkbox jQuery script is below:
<script src="'.get_bloginfo('stylesheet_directory').'/jquery/checkboxes.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("input[type=checkbox]").tzCheckbox({labels:["Enable","Disable"]});
});
</script>
The contents of the checkboxes.js called to above is as follows:
(function($){
$.fn.tzCheckbox = function(options){
// Default On / Off labels:
options = $.extend({
labels : ['ON','OFF']
},options);
return this.each(function(){
var originalCheckBox = $(this),
labels = [];
// Checking for the data-on / data-off HTML5 data attributes:
if(originalCheckBox.data('on')){
labels[0] = originalCheckBox.data('on');
labels[1] = originalCheckBox.data('off');
}
else labels = options.labels;
// Creating the new checkbox markup:
var checkBox = $('<span>',{
className : 'tzCheckBox '+(this.checked?'checked':''),
html: '<span class="tzCBContent">'+labels[this.checked?0:1]+
'</span><span class="tzCBPart"></span>'
});
// Inserting the new checkbox, and hiding the original:
checkBox.insertAfter(originalCheckBox.hide());
checkBox.click(function(){
checkBox.toggleClass('checked');
var isChecked = checkBox.hasClass('checked');
// Synchronizing the original checkbox:
originalCheckBox.attr('checked',isChecked);
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
});
// Listening for changes on the original and affecting the new one:
originalCheckBox.bind('change',function(){
checkBox.click();
});
});
};
})(jQuery);
There is also some CSS that accompanies this script but I am leaving it out as it is not important.
Finally, this is what the jQuery script does to the checkbox:
<input id="on_off_on" class="lesson" value="lesson11-1" name="forexadvanced[]" type="checkbox" style="display: none; ">
<span classname="tzCheckBox checked" class=""><span class="tzCBContent">Disable</span><span class="tzCBPart"></span></span>
When the checkboxes are changed into sliders the .change() function no longer detects the change in the checkboxes status.
How can I make the .change() function work or is their an alternative function I can use?
This plugin changes your checkboxes to span elements and hides the actual checkboxes themselves. Thus, when you click on them, nothing happens. Since span elements don't have onchange events, you can't bind change events to these.
However, span elements do have click events, meaning that you could instead bind a click event to the generated spans, using Firebug or Chrome Debugger to locate the correct element to bind to.
Your click-handler can then take the same action your change event would normally take if the plugin weren't being used.
Here is an example:
HTML (Source):
<!-- This is a checkbox BEFORE running the code that transforms the checkboxes
into sliders -->
<li>
<label for="pelda1">OpciĆ³ 1:</label>
<input class="pelda" type="checkbox" id="pelda1" name="pelda1" />
</li>
HTML (Generated From Chrome Debugger):
NOTE: This is the generated HTML after running the JavaScript that converts checkboxes to sliders! You must bind your click event AFTER this code is generated.
<li>
<label for="pelda1">Option 1:</label>
<!-- The hidden checkbox -->
<input class="pelda" type="checkbox" id="pelda1" name="pelda1" style="display: none; " />
<!-- the "checked" class on the span gets changed when you toggle the slider
if it's there, then it's checked. This is what you're users are actually
changing.
-->
<span class="tzCheckBox checked">
<span class="tzCBContent">active</span>
<span class="tzCBPart"></span>
</span>
</li>
JavaScript:
NOTE: This must be bound AFTER converting the checkboxes to sliders. If you try it before, the HTML won't yet exist in the DOM!
$('.tzCheckBox').click(function() {
// alert the value of the hidden checkbox
alert( $('#pelda1').attr("checked") );
// submit your form here
});
Listen for change like this:
$('.lesson').bind("tzCheckboxChange",function() {
$('.user-forms').submit();
});
Modify the plugin by adding the line:
$(originalCheckBox).trigger("tzCheckboxChange");
after
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
This way, anytime you use this plugin, you can listen for tzCheckboxChange instead of just change. I don't really know what's going on with the plugin, but seems kinda funky for it to be listening for a change event when it would only be fired through trigger (unless it doesn't hide the original checkbox).