I'm using a bit of Mootools to access the values of an HTML select element but the thing is that the way to do it with Mootools [.getSelected()] returns an array and I don't know how to handle it.
my code :
<script type="text/javascript">
window.addEvent('domready', function(){
$('votconj').addEvent('click', function() {
// This works great
$('jj_conjoint').addClass("validate['required']");
$('mm_conjoint').addClass("validate['required']");
$('aaaa_conjoint').addClass("validate['required']");
$('conjoint_regime').addClass("validate['required']");
new FormCheck('form');
});
if ($('nb_children').getSelected() == 1){
// this doesn't work because .getSelected() returns an array and never equals 1
$('jj_enfant1').addClass("validate['required']");
$('mm_enfant1').addClass("validate['required']");
$('aaaa_enfant1').addClass("validate['required']");
new FormCheck('form');
}
if ($('nb_children').getSelected() == 2){
// this doesn't work because .getSelected() returns an array and never equals 2
$('jj_enfant2').addClass("validate['required']");
$('mm_enfant2').addClass("validate['required']");
$('aaaa_enfant2').addClass("validate['required']");
new FormCheck('form');
}
new FormCheck('form');
});
</script>
getSelected() returns an array because some select elements allow multiple selection. If yours doesn't, you could just try $('nb_children').getSelected()[0]. To get the value you can use $('nb_children').getSelected()[0].get("value").
You can use .each to traverse an array in MooTools:
var selected = $('nb_children').getSelected();
selected.each(function(element) {
var val = element.get('value');
$('jj_enfant' + val).addClass("validate['required']");
//etc
}
new FormCheck('form');
For more info: http://mootools.net/docs/core/Types/Array#Array:each
The reason why getSelected() returns an array at all times, is that code like this can always be reused when you decide to add multiple selectable items instead of just one.
Edit
Note that the above code is directly written. Might need some tweaking to get it working for your case.
Edit 2
Updated code to a more comprehensive example.
You want to check the value of the selected item, right?
Try with:
if ($('nb_children').getSelected().get('value') == 1){//...
Related
Clicking on an element:
$('.my_list').click(function(){
var selected_object = $(this);
$('.my_list').each(function(){
var current_object = $(this);
if( selected_object == current_object ) alert('FOUND IT !');
});
});
I don't know why, but I don't get the alert message "FOUND IT !".
You can use the jQuery.is function:
Check the current matched set of elements against a selector, element,
or jQuery object and return true if at least one of these elements
matches the given arguments.
if (selected_object.is(current_object)) {
...
}
An alternate solution is to use jQuery.get function to get the raw elements and compare them using == or === operator:
if (selected_object.get(0) == current_object.get(0)) {
...
}
jsFiddle demo
There's good answer provided... but it's important to understand, why you directly can't compare selectors in jQuery.
jQuery selectors return data structures which will never be equal in the sense of reference equality. So the only way to figure this out is to get DOM reference from the jQuery object and to compare DOM elements.
The simplest comparison of DOM reference for the above example would be:
selected_object.[0] == current_object.[0]
This question already exists:
Closed 10 years ago.
Possible Duplicate:
Call same function by a cloned list row
I am trying to make a simple calculation to work.
I have the following running:
http://jsfiddle.net/vSyK6/41/
Basically, the way it works now is this:
When you select an option on the drop down list it will display the content based on the option selected. Then when you select the same option again it will add, basically clone the same row.
Now, when the second option is selected "Option2" it will display an empty textbox. When you enter a number it will or should call the a function where we make a basic calculation. The function is already in the script.
However, when we have two empty textboxes it should call the same calculation function but calculate seperately and puts it in a different div. The div# where we display the amount is a called "amount"
Basically, it should work like this:
First Empty textbox -> 100 -> 100 * 22.38 = display result in div#1
Second Empty textbox -> 230 -> 230 * 22.38 = display in div#2
any idea on how to accomplish that ?
When cloning elements the id is cloned as well. It is best practice to create a new ID for the cloned elements, which will also help in accomplishing what you want. The same goes for the name attribute as well.
With a few modification to your code, http://jsfiddle.net/dNQVQ/3/, I was able to get what you were after. Let me first say that this might not be the ideal way to go, but it is a start. Like I said earlier the key is going to be setting unique ids for the cloned elements. What I did in this example was use a index as part of the list element id that is cloned with a matching index in an 'amount' div. This way when an input is updated the index is retrieved and then used to update the appropriate div. Additionally, I moved the function that did the calculation and updates to an anonymous function in the settimeout call. This makes it easy to use a reference to the updated input in the function call.
Joining the party quite late here :) Here is one vernon: http://jsfiddle.net/KVPwm/
ALso if its assignment bruv, put an assignment homework tag!
People around SO community are awesome folks so be truthful, guys will help man!
Use .on instead of live - recommendation. i.e. upgrade your JQ source if keen read this - What's wrong with the jQuery live method?
you have 2 document.ready functions also I chained few things for you.
Also think of using isNan check as well.
Rest you can read the code and play around a bit to make it more concise.
I have added 2 divs and using the id number to populate the stuff accordingly.
This should fit the cause :)
code
$("document").ready(function() {
/////////////////////////////////CALUCATIONS/////////////////////////////////
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 0; //time in ms, 5 second for example
$('input[name=Input2], input[name=Input1]').live('keyup', function() {
var str = $(this).prop("id");
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
amount = parseFloat($(this).val()) * 22.38;
typingTimer = setTimeout(doneTyping(matches), doneTypingInterval);
});
$('#Input2').keydown(function() {
clearTimeout(typingTimer);
});
function doneTyping(matches) {
$('#amount'+matches).text(amount.toFixed(2) + " lbs");
}
$("#List-Option1,#List-Option2").hide();
$('#category').change(function() {
var str = $('#category').val();
if (str == 'Option1') {
var option1 = $("#List-Option1:first").clone().show();
$('#box li:last').after(option1);
}
if (str == 'Option2') {
var option2 = $("#List-Option2:first").clone().show();
$('#box li:last').after(option2);
}
});
});
I'm pretty new to js/jquery. For each checkbox with the ID of check$ (where $ is a sequential number), I want to toggle the class "agree" of the surrounding span that uses the same check$ (but as a class). I don't want to have to hard-code the list of matching checkboxes, as this may vary.
Here's my code. This function works as expected:
agree = function (checkbox, span) {
$(checkbox).change(function(){
$(span).toggleClass('agree');
});
};
This is what I'm trying to pass to the above function, which does not work:
$(function() {
var elemid = 'check',
checks = Array($('[id^='+elemid+']').length);
console.log(checks);
for (i=0; i < checks; i++) {
agree('#'+elemid+checks[i], "."+elemid+checks[i]);
}
});
console.log(checks) returns [undefined × 4]. The number of elements is correct, but I don't know why it's undefined, or whether that is even significant.
The following code works as expected, but as I say, I'd rather not have to specify every matched element:
$(function() {
var checks = ["check1", "check2", "check3", "check4"];
for (i=0; i < checks.length; i++) {
agree('#'+checks[i], "."+checks[i]);
}
});
Thanks.
Edit: Thanks to Jack, I was overlooking the most simple method. I added the same class to all checkboxes and spans, and solved the problem with this:
$('input.check').change(function(){
$(this).closest('span.check').toggleClass('agree');
});
I might be totally missing something, but I'm pretty sure you are just trying to attach a change handler to each checkbox. In this case you can give them all the same class. I'm also guessing at your html structure for the span.
For reference:
http://api.jquery.com/closest/
http://docs.jquery.com/Tutorials:How_jQuery_Works
$('.yourcheckboxclass').change(function(){ //grab all elements with this class and attach this change handler
$(this).closest('span').toggleClass('agree');
});
The reason that the array is full of undefined values, is that you are just getting the number of items in the jQuery object, and create an array with that size. The jQuery object is discarded.
Put the jQuery object in the variable instead:
var elemid = 'check', checks = $('[id^='+elemid+']');
checks.each(function(){
agree(this, "."+elemid+checks[i]);
});
I have an AJAX script that receives a string from a mySQL query returned by PHP.
This string is then parsed and put into an array in Jquery and the results are printed to the screen using .html()
The length of this array varies from 0 items to many, how would I count the items in the array then loop through and print them to the screen.
Here is my UPDATED code per the advice below, though I am still not sure if the for loop goes inside the .html() function or outside?
UPDATED CODE TO INCLUDE .each()
UPDATE 2: Replace (this) in the .html() function with the element I want the text written in and it is working partially, issue is now it is only printing the last item in the array?
UPDATE 3: Seems you can only have a single .html() function run, for instance if I add another .html() statement under the one that is returning the last item in my array it will only now echo on the screen the test value.
$("#n_detail").html(partsArray[index]+"<br />").addClass('jText').fadeTo(900,1);
$("#n_detail").html("Test").addClass('jText').fadeTo(900,1);
It will only print "Test", not the last item in the array like it was previously?
<script type="text/javascript">
$(document).ready(function() {
$("#primary").change(function()
{
$.post("lib/ajax_load_job_detail.php",{ _primaryid_n:$(this).val() } ,function(data)
{
var string = data;
var partsArray = string.split('|');
$("#n_detail").fadeTo(200,0.1,function() //start fading the messagebox
{
$.each(partsArray, function(index) {
$("#n_detail").html(partsArray[index]+"<br />").addClass('jText').fadeTo(900,1);
});
});
});
});
});
Sample value of array partsArray[0]12/12/2005, partsArray[1]This is a sample note from December, etc...
partsArray.length
will give you the items in the array. You can loop either with
for(var i=0;i<partsArray.length;i++){
or using the jquery addon
$.forEach
If you are iterating through an array then you could use the jQuery function each().
Here's a link to the docs: http://api.jquery.com/jQuery.each/
Here's a sample from the docs using your array:
$.each(partsArray, function(index, value) {
alert(index + ': ' + value);
});
EDIT - based on a comment the OP added to another answer, here's a better example using the OPs code:
$.each(partsArray, function(index, value) {
value.addClass('jText').fadeTo(900,1);
});
EDIT 2 - you need the part of the code that is per element of the arry inside the loop and based on your edits I think it should look like this:
$.each(partsArray, function(index) {
$(this).append(partsArray[index]+"br />").addClass('jText').fadeTo(900,1);
}
Cheers,
James
Here is a typical loop structure:
var partsArray = string.split('|');
for(var x=0;x<partsArray.length;x++) {
//...your code ...
//x is the index., so partsArray[x] is the current element
}
Use for ... in, it's significantly faster than jQuery's $.each method, and isn't much different - it provides you with the index of the item in i, rather than the value.
for (var i in partsArray)
{
// You can access values via...
console.log( partsArray[i] );
// Alternatively, this will make it an exact clone of $.each
var value = partsArray[i];
console.log( value );
}
I know this has been asked and answered a couple times already, but I'm still confused about how to reference the current object when iterating over a jQuery array. For example, the following code gives me the error TypeError: genH3Array[i].next is not a function. What is the right way to reference the current array object?
var genH3Array = $('#Generation_II').parent();
genH3Array.push($('#Generation_III').parent());;
genH3Array.push($('#Generation_IV').parent())
$.each(genH3Array, function(i, value)
{
if(genH3Array[i].next().attr("align") == "center")
{ genH3Array[i].next().next().next().insertBefore(heading.next())
}
genH3Array[i].next().next().insertBefore(heading.next())
genH3Array[i].next().insertBefore(heading.next())
})
EDIT: Thanks for all your help, everyone. I know this was probably a cinch for most of you, but it was a major headache for me. The corrected code is below:
var genH3Array = $('#Generation_II,#Generation_III,#Generation_IV').parent();
$.each(genH3Array, function(i, value)
{
console.log($(this).next());
if($(this).next().attr("align") == "center")
{
$(this).next().next().next().insertBefore(pokemonHeader.next())
}
$(this).next().next().insertBefore(pokemonHeader.next())
$(this).next().insertBefore(pokemonHeader.next())
$(this).insertBefore(pokemonHeader.next())
})
This part:
var genH3Array = $('#Generation_II').parent();
genH3Array.push($('#Generation_III').parent());
genH3Array.push($('#Generation_IV').parent());
...isn't really the way to use .push() against a jQuery object. When you .push() a value in, it should be a DOM element. Not a jQuery object.
You could simplify that entire bit like this:
var genH3Array = $('#Generation_II,#Generation_III,#Generation_IV').parent();
Now you'll have the .parent() of all three in the object.
Not entirely sure what the each is supposed to do, but it seems like you're trying to take the next three elements of each one, and insert them after some heading element.
$.each(genH3Array, function(i, value) {
if($(this).next().attr("align") == "center") {
heading.after( $(this).nextUntil('sometarget:last') );
}
heading.after( $(this).nextUntil('sometarget') );
});
I really don't know if this is what you want. It's a little hard to tell.
Both value and this point to the current item in the iteration, but that isn't your problem. Your problem is that the item returned by [] on a jQuery object isn't a jQuery object. You could do this:
$(genH3Array[i]).next()
Adding to what #patrick dw said: once you get the right selector, you can use the following syntax:
var getH3Array = ('#Generation_II,#Generation_III,#Generation_IV').parent().each(function() {
$(this); // this references the dom element matched, so:
if($(this).next().attr("align") == "center") {
// do something here
}
});
I think what you want is
var array = $("#c1, #c2, #c3").parent();
$.each(array, function(){
console.log($(this).next());
});
In $.each callback, the this variable point to the current element. If you are iterating through a jquery array like what you have, it will be iterating through the dom elements not jQuery objects, so you need to get the jQuery objects corresponding to them by using $(this).
jQuery.each