This might be an easy one for you, but I'm stuck, so I hope you can help me.
I'm creating checkboxes through a loop and want to specify a text somewhere in the website if a checkbox is clicked.
I'v seen solutions where a make a script for each checkbox, but that could turn out to be alot sometimes (something like this: chckbx.onchange = function(){} )
I'd rather have one function that is called from different checkboxes, but my javascript skills is basicly non-existing :)
This is what i got so far (which ofcourse dosn't work)
http://jsfiddle.net/Sz3BK/130/
You have jQuery tagged in your question, so I'm going to provide a jQuery answer:
You'd use jQuery's on() method to delegate the event to a non-dynamic ancestor of your checkbox:
$('elem').on('change', 'input[type="checkbox"]', function() {
...
});
Where elem is a non-dynamic ancestor of your checkbox.
In your JSFiddle your checkbox isn't dynamic, but assuming it was, the closest non-dynamic ancestor of it would be the document's body. Therefore, we can use:
$('body').on('change', 'input[type="checkbox"]', function() {
testing('hello', '1');
});
JSFiddle demo.
You may want to extend this by passing in "hello" and "1" as data-* attributes:
<input type="checkbox" name="test" data-newvalue="hello" data-spanid="1" />
<input type="checkbox" name="test" data-newvalue="second" data-spanid="2" />
Here I've created two checkboxes with our two data-* attributes. In our jQuery method we can pull these values and pass them into our testing() function using jQuery's data() method:
$('body').on('change', 'input[type="checkbox"]', function() {
testing($(this).data('newvalue'), $(this).data('spanid'));
});
JSFiddle demo.
We can then modify our testing() function to also use jQuery:
function testing(newValue, spanID) {
$('#'+spanID).text(newValue);
}
This pulls our spanID (e.g. "1") and places it within an ID selector $('#1'), then modifies the text using jQuery's text() method. If you wanted to modify the HTML instead, jQuery also has a html() method for this purpose.
Final JSFiddle demo.
because you are adding che checkboxes dynamicly,
to enable the change event for those added later, use code below
$(document).on('change', 'input[type="checkbox"]', function() {
...
});
Change your jsfiddle code http://jsfiddle.net/Sz3BK/136/ like this...
Add <head></head> in HTML code at top..
and change on load to "No wrap - in head"
This code works fine for me:
$('input[name=test]').change(function(){
if($(this).is(':checked'))
{
alert("chk");
// Checkbox is checked.
}
else
{
alert("unchk");
// Checkbox is not checked.
}
});
Check the fiddle. Hope it helps.
Related
I have an element which listens to the onclick event. It calls a function once it was clicked. After that element is a < dd > which I want to select in a CSS selector. The element which is clicked, is a < select >. How would I do that?
This is the HTML:
<select onclick="myFunction();">...</select>
<dd>...</dd>
function myFunction() {
// What do I have to write for the ??????
$$('?????? dd').toggle();
}
Note: There are many of those select/dd combination, so I really have to get the next dd after the firing element.
The minimal change is: Pass this into your function:
<select onclick="myFunction(this);">...</select>
...and then:
function myFunction(select) {
$(select).next().toggle();
}
$ enhances the element, then you can use next to move to the next element. If you like, you can use .next('dd'), but in your case the dd is the next element.
That still uses onxyz attributes, which is a bit old-hat. You might consider hooking things up via observe instead.
I am guessing you mean this:
this.next("dd");
(specifying dd so when there's an error in the mark up, no other element is selected)
If you are trying CSS selectors only, try the following:
$("select + dd").toggle();
Note: this will toggle all dds that follow a select.
Note 2: apparently this does not work in Prototype but it does work in jQuery.
See T.J.Crowder's comment:
[This doesn't work in Prototype] because $ in Prototype looks up elements by ID. $$ is more like
jQuery's $, but what it returns doesn't do set-based operations like
jQuery does (or rather, not the same set-based operations as the ops
you can do on individual elements; you have to use invoke).
next() works on both jQuery as Prototype.
Use:
$(this).next("dd").toggle(); --> this is Jquery
$(element).next("dd").toggle();
see the link Element.next
<select>...</select>
<dd>...</dd>
$('select').change(function(){
$(this).next("dd").toggle();
});
Better use unobtrusive javascript, so your js is better coupled from html markup.
HTML:
<select><option value="test">Test</option></select>
<dd>Test</dd>
JS:
//Event.observe(window, "load", function() {
document.observe('dom:loaded', function() {
$$('select')[0].observe('click', function(event) {
var next = event.element().next();
next.toggle();
});
});
JSFiddle
I have a couple of drop down boxes with ids country1, country2, ... When the country is changed in a drop down the value of the country shoudl be displayed in an alert box.
if I add the onchange handler for one box like this it works fine:
$('#country1') .live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
But I need to do this dynamically for all drop down boxes so I tried:
$(document).ready(function() {
$('[id^=country]') .each(function(key,element){
$(this).live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
});
});
This doesn't work. No syntax error but just nothing happens when the seleted country is changed. I am sure that the each loop is performed a couple of times and the array contains the select boxes.
Any idea on that?
Thanks,
Paul
The reason .live() existed was to account for elements not present when you call the selector.
$('[id^=country]') .each(function(key,element){ iterates over elements that have an id that starts with country, but only those that exist when you run the selector. It won't work for elements that you create after you call .each(), so using .live() wouldn't do you much good.
Use the new style event delegation syntax with that selector and it should work:
$(document).on('change', '[id^=country]', function(e) {
// ...
});
Replace document with the closest parent that doesn't get dynamically generated.
Also, consider adding a class to those elements along with the id attribute.
Instead of incremental ids I'd use a class. Then the live method is deprecated but you may use on with delegation on the closest static parent or on document otherwise.
$('#closestStaticParent').on('change', '.country', function() {
// this applies to all current and future .country elements
});
You don't need an each loop this way; plus events are attached to all the elements in the jQuery collection, in this case all .country elements.
The following code (*) for toggling the disabled attribute beetween two buttons works and you can check it at http://jsfiddle.net/cNSVX/3/.
I was wondering what is the best way to generalise this code in order to attach this behaviour to a couple of buttons.
Something like the following.
body.onload(togglingButton(elem1, elem2));
$('#filterOpened').click(function() {
$('#filterOpened').attr('disabled', 'disabled');
$('#filterClosed').removeAttr('disabled');
});
$('#filterClosed').click(function() {
$('#filterClosed').attr('disabled', 'disabled');
$('#filterOpened').removeAttr('disabled');
});
function togglingButton (elem1, elem2) {
if (elem2.attr('disabled')) {
elem1.attr('disabled', 'disabled');
elem2.removeAttr('disabled');
} else {
elem2.attr('disabled', 'disabled');
elem1.removeAttr('disabled');
}
};
You can do it like below with jQuery. Also if you are using jQuery 1.6+ then you should be using .prop() to toggle your disabled property.
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The prop method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.
$('button').click(function(){ //<--- attaches click to all button's
$(this).prop('disabled',true); //<-- only disable the clicked button
$('button').not(this).prop('disabled',false); //<-- all button's but the clicked one should be enabled
});
here's an example fiddle http://jsfiddle.net/cNSVX/5/
If you are planning on excluding some buttons out of the toggling it would be a good idea to give them a class so you can select the ones you need/don't need easier
One simple way to do this would be to use jQuery's .data() function to link the two elements, then assign a single event handler to both:
function disableToggle(el1,el2) {
el1.data('partner',el2);
el2.data('partner',el1);
el1.add(el2).on('click',function(){
$(this).prop('disabled',true);
$(this).data('partner').prop('disabled',false);
});
}
$(function(){
var opened = $('#filterOpened');
var closed = $('#filterClosed');
disableToggle(opened,closed)
});
I've created a demo:
jsFiddle DEMO
I'm using a javascript function to set the value of a text field, based on the option chosen from a select field.
The javascript contains a lot of other stuff, but only the following is relevant to this question.
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next('.target')[0];
----other stuff----
});
});
I originally had my form set up as follows, and everything worked fine.
<select class="source"></select>
<input class="target"></input>
I've subsequently added some styling, which has required extra divs.
<select class="source"></select>
<div class="level1">
<div class="level2">
<input class="target"></input>
</div>
</div>
Now the javascript function does not work, because the next method only targets siblings and not descendants.
So my question is, what method should I be using to target a specific descendant?
An important fact: this markup is part of a nested form, and is repeated several times on the same page. It is important that the function targets the correct .target field, i.e. immediately subsequent and descendant.
I've tried obvious candidates – .find(), .children() — but these don't seem to work. Would appreciate any ideas or pointers.
Thanks!
Now that in the new markup structure .target input is wrapped in a div with class level1 you can find that div first using next() and then use find() method to get to the .target input.
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next('.level1').find('.target')[0];
----other stuff----
});
});
Note: Even if you don't pass any selector to next() also it will work fine because it only selects the immediate next sibling optionally filtered by the selector which we pass.
In your case this would work:
$(function (){
$('.source').live("change", function(e) {
var target = $(this).next().find('.target')[0];
----other stuff----
});
})
;
It's a descendant of the sibling, so this should do the trick:
var target = $(this).next('.level1').find('.target')[0];
I am loading data dynamically by AJAX into a cluetip (http://plugins.learningjquery.com/cluetip/#).
I want to toggle the results from a link like so:
$(document).ready(function() {
$("#calendarLink").live("click",( function() {
$("#result").toggle();
}));
});
For some reason the above will not work. Can you suggest an alternative?
Couple of questions/points
Do you really need to use .live() You're using an ID selector, so there should only ever be one of these.
Also, you have an extra set of brakets. Probably not a problem, but you could remove them:
$(document).ready(function() {
$("#calendarLink").click( function() {
$("#result").toggle();
});
});
Perhaps the toggle() function isn't be used properly?
See here http://api.jquery.com/toggle/
I'm not sure if this is new functionality only for jQuery 1.4 but it appears the toggle function requires parameters.
The following code is correct (demo online - http://jsbin.com/ehate/edit):
$("#calendarLink").live("click", function(e){
$("#result").toggle();
});
You use $.live() only if #calendarLink will be added dynamically later. If it isn't, use a regular click:
$("#calendarLink").click(function(e){
$("#result").toggle();
});
If this is not working for you, be sure to check your #calendarLink and #result elements in your HTML. Make sure the ID values are correct. Mainly, be sure your casing is correct.
Two elements in the same page can't have the same id.
u used
$("#result").toggle();
'I want to toggle the results from a link ...'
So the result elements should have the same class , not id.
The code should be :
$(".result").toggle();
'#' changed into '.'