I have been searching for the solution for this for a while so I hope I can get some help now. I am attempting to figure out whether a programmatically added checkbox is checked using jquery. The HTML code of the checkbox is below:
<td>
<input type="checkbox" name='ismanual' id='ismanual' class="checkbox">
</td>
And I am doing it using the following jquery code:
var ismanual = document.getElementById("ismanual").val();
I have attempted using #ismanual as the selector, but that didn't help. Any idea where I have gone wrong?
If you're using document.getElementById("ismanual") you should use .checked instead of .val()...
var ismanual = document.getElementById("ismanual").checked;
For jQuery use...
var ismanual = $("#ismanual").is(':checked')
Where you have gone wrong: if you want to use val(), you need to use it on a jQuery object. getElementById() gives you a DOM element but not a jQuery object. To get a jQuery object you need to find the element using a jQuery selector like this:
jQuery('#ismanual')
You can then use jQuery's :checked selector and the .is() function on that object:
var isManual = jQuery('#ismanual').is(':checked');
.val() is a jQuery function. It will not work with DOM style element selection.
To get value using .getElementById(), you must use .checked like,
var ismanual = document.getElementById("ismanual").checked;
.val() will work when you are selecting the element using jQuery like,
$("#ismanual").val();
Related
I have the following link inside my web page:
Attachments and Documents
Now I want to select this link based on its text "Attachments and Documents", and set a target attribute for it.
So I tried the following:
var tgb = $('a:contains("Attachments and Documents")')[0];
tgb.attr('target', '_blank');
But I got the following exception :
TypeError: tgb.attr is not a function
As soon as you use index ([0]), tab is no more a jQuery object. To get the jQuery function attr() you have to wrap tgb with $:
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
// to demonstrate result
console.log(tgb)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
attr() is a jQuery function. You need to target your variable using jQuery methods
$(tgb)
Hope this helps :)
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
console.log(tgb);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
var tgb = $('a:contains("Attachments and Documents")');
tgb.attr('target', '_blank');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
The issue with your logic was the [0] that you were putting on the tgb. [0] on a jQuery object breaks the element out of the jQuery object and returns the native Element. There are various reasons why you would want to do this, such as if you wanted to access element properties and you don't want to go through the jQuery prop() or attr() method.
However in your case, you are trying to use the attr() method off of tgb. However, attr() is a jQuery method. Since you broke the element out of the jQuery object, this will not work.
Rather than turning the tgb back into a jQuery object, simply take off the [0]. This fixes your issue, and removes the need to create another jQuery object which, give the snippet you provided, is unnecessary work.
Optionally, if you do want it to be a native Element you could just set the attribute directly.
var tgb = $(...)[0];
tgb.setAttribute('href', newValue);
//or
tgb.href = newValue;
I wanted to put an id in my element's parent element. Below is my code:
<div>
<div id="child"></div>
<div>
Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:
div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";
Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?
For achieve what you want, you can use the jquery attr:
$("#child" ).parent().attr('id', 'newID');
Or you can use the prop:
$("#child" ).parent().prop('id', 'newID');
And you can check the difference between the two here: difference between prop() and attr()
Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.
Try .attr instead:
$("#child").parent().attr({id: "div_resizable"});
To set a property on the first element inside a jQuery result object:
div_resizable = $( "#child" ).parent()[0];
// ^^^
div_resizable.id = "div_resizable";
This picks the first Element from the result so that you can directly access the property.
Or:
$('#child').parent().prop('id', 'div_resizable');
Use the .prop() helper method to accomplish the same thing.
I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;
on my site is a form which has multiple checkboxes with the same name:
<span class="selection"><input type="checkbox" name="product" value="Hard Enamel" />Hard Enamel</span>
<span class="selection"><input type="checkbox" name="product" value="Soft Enamel" />Soft Enamel</span>
<span class="selection"><input type="checkbox" name="product" value="Metal Relief" />Metal Relief</span>
<span class="selection"><input type="checkbox" name="product" value="Printed With Epoxy" />Printed With Epoxy</span>
In my Javascript, I assign these to a variable and have an onclick function using JQuery. With this I can still run JQuery functions no problem, e.g. products.css("display","none") works.
But when trying to select a particular checkbox within products it hits back with an error.
Here is my JS:
var products = $("input[name=product]").click(function(){selectProduct()});
products.get(0).css("display","none");
The above doesn't work, and I get the error badges_calc.js:9TypeError: 'undefined' is not a function (evaluating 'products.get(0).css("display","none")')
How can I fix this? I'm rather beginner.
Cheers
get() returns DOM element try use eq instead. DOM element does not have css method it is the jquery Object that has it. eq(0) will give you the first element in the collection as a jquery object.
products.eq(0).css("display","none");
And if you are really looking to hide the span along with the check box then use:
products.eq(0).closest('span').css("display","none");
otherwise it will leave the span with the text there itself, by just hiding the checkbox.
.get() returns a raw DOM object.
You want .eq(0), which returns a jQuery object with only one element.
Try this:
var products = $("input[name=product]");
products.click(function(){selectProduct()});
products.eq(0).css("display","none");
When you use .get() you will get a raw DOM element and cannot use jQuery's methods, so you cannot use .css()
Use closest or parent to hide the selected input's parent.
var products = $("input[name=product]").click(function(){selectProduct(this)});
var items = [];
function selectProduct(self){
$(self).closest('span').hide('slow');
items.push($(self).val());
console.log(items);
}
I want to replace the old class of html element with the new one using jQuery. Here is what I'm doing:
var elem = $('.my_selector')[0];
elem.css('class', 'my_new_class');
But I get the error saying "Uncaught type error: Object#<HtmlDivElement> has no method css.
How do I fix it?
The problem is that you are trying to call jQuery method css() (even not relevant here) from DOM element, which is derived with [0]. You can use toggleClass() to do the job:
$(".my_selector:first").toggleClass("my_selector my_new_class");
$('.my_selector')[0] is returning you a DOM element, not a jQuery Object. You'll also want to use the addClass method rather than css. To get the first element, you can use the :first pseudoselector.
So this should be what you are looking for:
$('.my_selector:first').removeClass('my_selector').addClass('my_new_class');
EDIT You can use either removeClass/addClass or toggleClass. Either are fine. Explicitly adding the new class may be safer if you have a case where an element can have both classes at the same time since toggleClass will remove both classes.
var elem = $('.my_selector')[0];
This will return the DOM element, not a jQuery object. Simply change it to this...
var elem = $('.my_selector');
To get just the first element that matches the selector, use this...
var elem = $('.my_selector').first();
Also, you have...
elem.css('class', 'my_new_class');
This is incorrect and should be changed to this...
elem.attr('class', 'my_new_class');
Try this ,
var elem = $(".my_selector");
elem.class("newclass");
otherwise you can do,
var elem = $(".my_selector");
elem.removeClass("my_selector");
elem.addClass("newclass");
$(".my_selector").removeClass('currentClass').addClass('newClass');
As said, you need the jquery object of the first element. A good method could be this:
$('.my_selector').first().css('class', 'my_new_class');
Moreover the method signature is .css( propertyName, value ) so its intented to set a css property not to change a class. To do that you need to remove old class and add new one with .removeClass and .addClass respectively.
$($('.my_selector')[0]).css('class', 'my_new_class');
document.getElementsByClassName('my_selector')[0].className = 'my_new_class';