jQuery Selector from jQuery objects - javascript

How can I listen to the onChange Event of multiple jQuery objects?
var el1= jQuery('input[type="checkbox"][name="x"]');
var el2= jQuery('input[type="checkbox"][name="y"]');
jQuery(el1, el2).change(function (e) {
//....
});
Of course I could just put the 2 element selectors as a string into the
.change function, but this is a simplified example. I would like to work with the jQuery objects, not with string selectors.
This looked like a simple "let me google for you" question to me, but I have not been able to find a solution for the past hour.

You can use add() or merge() method:
Add:
el1.add(el2).change(function (e) {
//....
});
Merge:
$.merge(el1, el2).change(function (e) {
//....
});

Try this
var el1 = jQuery('input[type="checkbox"][name="x"]');
var el2 = jQuery('input[type="checkbox"][name="y"]');
$(document).on('change', [el1, el2], function() {
console.log('multiple')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="el1">Element 1</label>
<input id="el1" type="checkbox" name="x" value="test1" />
<label for="el2">Element 2</label>
<input id="el2" type="checkbox" name="y" value="test2" />
Also it is the first result of google and the main link is this

You can use .add():
el1.add(el2).on('change', function () { /* body */ });

Related

On Radio Button execute onChange function

ive got the (working) following code
$('#selBookable').change(function () {...
and
<div class="radio radio-search">
<label><input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" >Neueste</label>
which executes when #selBookable gets another value.
Now i want to execute this function when a Radio button somewhere else is clicked.
i tried :
$('#selBookable, #radio-new-pop').change(function () {...
but that does not work.
now i thought about giving this ".change(function NAMEHERE"
a name and execute that function but doesnt work either.
any help is appreciated.
edit: i tried using the onchange event but then again i have no function name to call.
You could define the function independently of its use, giving it a name. Then you could attach it to as many targets you wish, making a call as the one that works (using the name instead of the definition), each with a different target.
(The reason your second attempt didn't work is that the second argument to $ is not another target to attach the function to, but a constraint on where to find the first target.)
You have two buttons radio with the same name :
<div class="radio radio-search">
<label>
<input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" />
Neueste
</label>
<label>
<input id="radio-new-pop2" type="radio" name="radio_newest_popular" value="new" />
Other
</label>
</div>
Add a javascript function to handle this change :
var onRadioButtonChange = void 0;
{
onRadioButtonChange = function (e) {
theFunctionYouWantToExecute(); // pass this or e.target if needed
return false;
}
}
Attach it to your elements :
Array.prototype.forEach.call(
document.querySelectorAll('input[type="radio"]'),
function (element) {
element.addEventListener('change', onRadioButtonChange, false);
}
);
Perhaps try putting the jquery listener inside of a $(document).ready().
OR
You could add a click handler on the radio, like this:
<div class="radio radio-search">
<label>
<input id="radio-new-pop" type="radio" name="radio_newest_popular" value="new" onclick="handleClick(this)">
Neueste</label>
and in the JS:
handleClick(myRadio) {
// click function logic
}
Adapted from this answer.

What is the best way to iterate input inside a div using this

i'm trying to know (without success), what is the best way to iterate all input element with a specific class in a specific div after a click on a button.
<div>
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="anotherclass">
<input type="text" class="anotherclass">
<button class="full">click me</button>
</div>
So i want to get the value of every input with the class inputtext (but not the one with the class anotherclass). I've tried this :
$(".full").click(function() {
console.log($(this).parent().children(".inputtext").val());
});
Thanks for your attention !
Use .map
var values = $(".inputtext").map(function() { return this.value }).get();
values will be an array of each input value.
Use the .each method of JQuery:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){console.log($(this).val());});
});
Working Fiddle: https://jsfiddle.net/jx6d4neh/
Try with
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
You could use the each() function, somewhat like this:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){
console.log($(this).val());
});
});
https://api.jquery.com/each/
Or better traverse using siblings() instead of parent().children() like this
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
https://api.jquery.com/siblings/

Javascript - Swap input element on click

saw something on xe.com where they swap currency on the form. I need something for my site also. Basically this is not a question, solve the problem and sharing here:
HTML
<form target="">
<input name="input1" id="firstinput" value="input #1">
<input name="input2" id="secondinput" value="input 2">
</form>
<a class="swap">Swap</a>
Javascript
$(document).ready(function () {
$("a.swap").click(function(){
var axix = document.getElementById("firstinput").value;
var byiy = document.getElementById("secondinput").value;
document.getElementById('secondinput').value = axix;
document.getElementById('firstinput').value = byiy;
});
});
demo: http://jsfiddle.net/Z5Vse/
any better way to do it?
share with us. :)
Shorter (not necessarily "better"):
$("a.swap").click(function () {
$('#pickup').val([$('#destination').val(), $('#destination').val($('#pickup').val())][0])
});
jsFiddle example
IMO "better" would mean clean, clear, and concise.
$("a.swap").click(function () {
var temp = $('#pickup').val();
$('#pickup').val($('#destination').val())
$('#destination').val(temp);
});
Using JQUERY and one less variable used:
$(document).ready(function () {
$("a.swap").click(function(){
var axix = $("#pickup").val();
$('#pickup').val($("#destination").val());
$('#destination').val(axix);
});
});

JS / JQuery - Check All Checkboxes

I have a photo gallery. Underneath each photo is a checkbox, with the ID containing a prefix of 'checkbox_', followed by the photo ID.
<input type="checkbox" id="checkbox_<%=photoID%>" name="photos">
When I check a 'selectAll' checkbox, like this one:
<input type="checkbox" id="toggleAll" name="toggleAll" onclick="toggleAll()">
I want to check/uncheck all checkboxes that have the name 'photos', so I have this function that should do that... but it doesn't:
function toggleAll() {
if (document.getElementById('toggleAll').checked == true)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500);
document.getElementByName('photos').checked = true;
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
document.getElementByName('photos').checked = false;
}
}
The rest of the function works okay, it animates the background colors of the containing DIV (#photoBlob) when the toggleALL() function is called. But, I really can't get all the checkboxes to check and I have tried so many different variations!
Can anybody see what I am doing wrong? The problem lies with these two lines:
document.getElementByName('photos').checked = true;
document.getElementByName('photos').checked = false;
Any suggestions gratefully received...
You can do like this,
don't use same name for several check boxes because the name shroud be unique. Instead of use the class.
<input type="checkbox" id="checkbox_<%=photoID%>" class="photos">
an the jquery,
$('#toggleAll').click(function(){
var checked =$(this).attr('checked');
$('.photos').attr('checked', checked);
}
$('#toggleAll').click(function(){
$(':checkbox[name="photos"]').prop('checked',this.checked);
});
Fiddle demo: http://jsfiddle.net/uNeX2/
I think you're missing an "s" in getElementByTagName. Try getElementsByTagName.
This might also work:
$("#toggleAll").click(function() {<br/>
$("input[name='photos']").attr("checked",!!$(this).attr("checked"));
});
well, since you said, you have multiple checkboxes with the name 'photos', selecting only one element by using the function getElementByName, can't be ur choice of game. Using jQuery simplifies the task your trying to do;
$("input[name=photos]").each(function(elem){
elem.checked=true;
}
or simpler;
$("input[name=photos]").attr('checked','checked');
its its js-only, youd need to select all input elements via getElementsByTagName and then filter out the ones that don't comply with having a name of 'photos'.. and then do your task.
Here is simple example using jQuery:
html
<input type="checkbox" id="all" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
<input type="checkbox" name="photo" >
js
$('#all').click(function() {
if ($(this).attr('checked') == undefined) {
$('input[name=photo]').removeAttr('checked');
}
else {
$('input[name=photo]').attr('checked', 'checked');
}
});
Code: http://jsfiddle.net/b8Y9t/3/
I would use:
$('.photos:checkbox').attr('checked','checked');
There is no function called getElementByName. Did you have a javascript-error? I think it should be getElementsByName. This returns a list with elements. That means you have to loop trough it to check all checkboxes.
BTW I think it is not correct to use a name called 'photos' for a checkbox, since a checkbox is a single object and does not display a photo itself. I would name it 'photoCheckbox' or 'cbPhoto' to clearify it is a checkbox.
var checkboxList = getElementsByName('photoCheckbox'); // returns list with checkboxes with name 'photoCheckbox'
if (checkboxList)
{
for (var i = 0; i < checkboxList.length; i++)
{
var checkbox = checkboxList[i];
checkbox.checked = false;
}
}
Thats how the getElementsByName function works. So if you would evaluate this method, you would say this is unnecessary since you are already using jQuery? I would simplify the code of the checkbox:
<input type="checkbox" onclick="toggleAll(this)" />
The new toggleAll function looks like this:
function toggleAll(checkbox)
{
if (checkbox.checked)
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,102,204,0.5)'}, 500);
$('.photoBlob').animate({backgroundColor: 'rgba(204,204,204,1)'}, 1500); // btw why 2 animations on the same elements..?
$('input[name="photos"]').prop("checked", true);
}
else
{
$('.photoBlob').animate({backgroundColor: 'rgba(0,0,0,0)'}, 1000);
$('input[name="photos"]').prop("checked", false);
}
}
// jquery check all or uncheck all
$('.checkall').click(function(){
var status = 'false';
status = $('.checkall').is(":checked");
//alert ('status is ' + status); // you should see true or false
$('.metacheckbox').each( function() {
$(this).attr('checked', status);
});
});
<input class="checkall" type="checkbox" />Check/UnCheck All
<input class="metacheckbox" type="checkbox" id='checkboxone' name="checkboxone" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxtwo' name="checkboxtwo" value="Y" />
<input class="metacheckbox" type="checkbox" id='checkboxthree' name="checkboxthree" value="Y" />
this worked for me.

Better method of retrieving values of checked input boxes via jQuery?

I have several checkboxes and a fake submit button to make an AJAX request:
<form>
<input type="checkbox" value="1"/>
<input type="checkbox" value="2" checked="checked"/>
<input type="checkbox" value="3"/>
<input type="checkbox" value="4" checked="checked"/>
<input type="button" onclick="return mmSubmit();"/>
</form>
Within the mmSubmit() method, I would like to retrieve an array of values that have been selected. Here is what I am currently doing.
mmSubmit = function() {
var ids = [];
$('input[type=checkbox]:checked');.each(function(index) {
ids.push($(this).attr('value'));
});
// ids now equals [ 2 , 4 ] based upon the checkbox values in the HTML above
return false;
};
I'm wondering if there is a shorthand method in jQuery used to retrieve the values into an array, or if what I have is already optimal.
I think this can be accomplished with map. Try the following..
mmSubmit = function() {
var ids = $('input[type=checkbox]:checked').map(function(){
return $(this).val();
}).get();
// ids now equals [ 2 , 4 ] based upon the checkbox values in the HTML above
return false;
};
Take a look at: jQuery Traversing/Map
Well you can use .val() instead of .attr('value').
$.serializeArray() may also do what you want (http://docs.jquery.com/Ajax/serializeArray).
It's needs some optimization, buts generally it is right way. My variant:
mmSubmit = function () {
var ids = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
ids[ids.length] = this.value;
}
});
return ids;
};
It's little faster.

Categories