Toggling multiple checkboxes - javascript

I can't seem to get jquery to toggle multiple checkboxes. I want to grab all the checkboxes on the page with a certain name and toggle them. Here is what I am currently trying but it just generates the error below and I am not sure why. What am I missing here?
$("input[name=recurringGridCheckbox]").prop("checked", !(this.prop("checked")));
Object doesn't support property or method 'prop'

There's a syntax error in rhe variable you use in the setter; this refers to the DOMElement, not the jQuery object and so does not have the prop() method available.
To fix this you can provide a function to the prop() method which will update the property based on its current state. Try this:
$("input[name=recurringGridCheckbox]").prop("checked", function(i, checked) {
return !checked;
});

.prop is a jquery method, so you must use it with a jquery object:
$("input[name='recurringGridCheckbox']").prop("checked", !$(this).prop("checked") );
Also, in specific cases the attribute value needs to be enclosed in quotes, so it may be good practice to always do that.

Related

Copy value from one text field to another when button clicked

I am trying to get one field to copy over to another field when a div is clicked on, and the code that I have currently is not working. It's showing '0' in field1, even though field2 is set to 1 by default.
$(document).on('click', '#button', function() {
$('#textfield1').val === "document.getElementById('#textfield2').value";
Try with:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val())
});
You're using an odd mix of JS and jQuery here.
Your main issue is that val() is a method, not a property. Therefore your code should look something like this:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val());
});
I'd strongly suggest you familiarise yourself with the jQuery documentation, specifically val() in this case.
It's showing '0' in field1, even though field2 is set to 1 by default.
You were assigning a string to $('#textfield1').val method which is why your code was not having any effect on textfield1's value.
Make it
$(document).on('click', '#button', function() {
$('#textfield1').val( $('#textfield2').val()); //use jquery val method
}
Generally speaking, JQuery offers only functions, and not properties (as #Craicerjack stated), hence remove that === and pass the new value as an argument, as follows:
$('#textfield1').val("yourText");
Also, you're passing a CSS selector rather than just an element ID to the Document.prototype.getElementById() function. Remove that # qualifier!
Moreover, you shoudln't be using a stringified JavaScript expression as a value, otherwise you'll get that exact JS expression as the input value. Rather, don't put those quotes around the expression, so that the interpreter will be evaluating it. Below is some working code.
$('#textfield1').val(document.getElementById('textfield2').value);
However, as #Rory McCrossan pointed out, you're using an odd mix of plain DOM and JQuery, and that makes no sense. It would be more consistent to also read the value of the other text field using JQuery, as follows:
$('#textfield1').val($('#textfield2').val());
Alternatively, you may do not need JQuery and opt for the standard DOM interfaces like in the example below:
document.getElementById('textfield1').value = document.getElementById('textfield2').value;

How to set a default value in selectize.js?

I'm trying to find a way to set a default value in selectize.js.
I know that in jQuery you can use:
$(".country").val("US");
But this doesnt work with Selectize. I already read the API documentation and I tried using:
$(".country").selectize().setValue("US");
But it doesnt work either.
I'm a newbie so I'm probably missing something here but can't figure out what. Any ideas?
Per the documentation, API functions are called on the selectize property that the selectize() call adds to the original select or input element; this property points to the underlying selectize instance.
Since it's a property of the element, you use the [0] syntax to the element from jQuery:
// initialize the selectize control
var $select = $('.country').selectize();
$select[0].selectize.setValue("US");
maybe items can be used..
$('select').selectize({
items : [""], // initializing selected value to nothing
plugins: ['remove_button','restore_on_backspace']
});

When I'm trying to append data-id; I got an error

Check this out:
here's a simple code that works fine
html
<select></select>
<button id="btn1">click me</button>
js
$('#btn1').on('click',function(){
var select = $('select');
select.append($('<option>').val('v2').text('text2'));
});
When I'm trying to append data-id I got an error. Any help?
select.append($('<option>').val('v2').text('text2').data-id('id1'));
http://jsfiddle.net/omarmakled/QQ44U/
You can do this 2 ways
select.append($('<option>').val('v2').text('text2').attr('data-id','id1'));
or
select.append($('<option>').val('v2').text('text2').data('id', 'id1'));
http://api.jquery.com/data/
http://api.jquery.com/attr/
First, data-id string is illegal identifier in JS (as it contains hyphen), therefore even if it were available as a jQuery object method, you should have called it like that...
someObj['data-id'](someId);
Apparently, that's too messy for such a simple operation. In fact, there's no such method defined in jQuery.prototype - which instead expects you to employ either attr() (to set any attribute explicitly), or data() (dataset API specific one).
As a sidenote, you don't have to make that many calls: this...
select.append($('<option>', {
value: 'v2',
text: 'text2',
'data-id': 'id1'
}));
... is both more readable AND efficient. Note the quotation marks around 'data-id': object properties can be non-quoted only if they are proper JS identifiers.
JSFiddle.
The correct method to use is data():
select.append($('<option>').val('v2').text('text2').data('id','id1'));
Or if you want an actual attribute you can use attr():
select.append($('<option>').val('v2').text('text2').attr('data-id','id1'));

How do I set the value of an input-element via jQuery, when I only know it's "name"-attribute

I need to reset some text-boxes which only have an unique name (not an unique id).
I tried it with jQuery, but my code seems to do nothing:
$('input[name=customergroupname]').value="";
Try this:
$('input[name="customergroupname"]').val("");
Getting and setting value of form elements wrapped in a jQuery object is being done with use jQuery val function:
$('input[name="customergroupname"]').val("");
.value can only be used for DOM elements, like this:
$('input[name="customergroupname"]').eq(0).value ="";
$(...) // This is a jQuery object.
$(...)[n] // This is a DOM object in the nth place in the set.
$(...).eq(n) // This is a DOM object in the nth place in the set.
Working demo http://jsfiddle.net/vN74v/2/
Code
$('#hullk').click(function(){ // in example when you click the button
$('input[name="customergroupname"]').val("");
});
​
According to DOM level 2 specifications, you can access:
document.forms["foo"].elements["customergroupname"].value = '';
If formName and fieldName are constants rather than variables you can use literal syntax:
document.forms.foo.elements.customergroupname.value = '';
try:
$('input[name="customergroupname"]').value="";
I've wrapped customergroupname in quotes.
Very true, I mixed the quotes up. Edited now.

Jquery Replace with return value of Javascript function

OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
$('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I
take each of the source values and
pass it to a Javascript function
then replace that source value within the table with the result of the function calculation.
So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.
Firstly, you will need an element selector, e.g.
$('table')
Will select all <table> elements in your html. So,
$('mytag')
will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
//function code goes here
});
(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
$(this).text()
});
Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
...
MyFunction($(this).text());
...
The text() function has an overloaded implementation which allows you to set the text if you pass a value:
$(this).text(someval);
So, we can factor this into our code
...
$(this).text(MyFunction($(this).text()));
...
Making our final code block:
$('mytag').each(function(){
$(this).text(MyFunction($(this).text()));
});
$('mytag').each(function (index,tag) {
$(tag).text( myFunc($(tag).text()) );
});
$("mytag").each(function() {
$(this).html("Very Late");
});
$('mytag').each(function() {
$(this).text(someFunction($(this).text()));
});
But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;
...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Categories

Resources