this.is(":checked") not working - javascript

I'm using the following code to loop through all the checkboxes in my form. The boxes are gerenated dynamicaly from a php script so I won't know the names or the number of check boxes.
I need to find out which checkboxes have been ticked so I only pass those ones to the php script that handles the form.
$("#panelform input:checkbox").each(function () {
if(this.is(":checked")){
fields = fields+"&"+this.name+"="+this.value;
}
});
When the script gets to the this.is(":checked") it errors but being jquery my console doesn't show me any error messages just stops.
if I alert or console.log "this" after the first line I get the form field so I know that that much works.

try with
if($(this).is(":checked")){
since this is just a reference to the node in the DOM (and you need instead to use the jQuery wrapper to chain the method is().

Try this:
if( this.checked)
this is the plain DOM node, checked is its property to tell you if it's checked or not. Creating a whole new jQuery object just to see if a property is set is redundant.

In that contect, this refers to the DOM element, not the jQuery object - and DOM elements have no method is(). You can wrap it in a jQuery object if you want to use is method:
if($(this).is(":checked")){
or use the DOM Element's checked property:
if(this.checked){

$(this).is(':checked')
if you want to serialize your form try this
$('your-form-selector').serializeArray()

Related

How to get the text written in text input

I'm trying to grab the txt I wrote inside the my <input type="text"> but it is returning undefined , I tried many ways such as .text() or .html() or e.target.value , all of them returned undefined including this innerHTML too
$('input[type=text]').keyup(function(e){
if(e.which == 13){
alert($('input[type=text]').innerHTML);
}
});
You are mixing jQuery with Vanilla and they aren't the same. First of all, this was not going to work either way because form elements have values, not HTML. However, lets say you had tried this: alert($('input[type=text]').value);
value is a property of an html input element, but does not exist in a jQuery object. The jQuery object represents the form element, but wraps it in an extra set of properties and methods. If you truly wanted to mix them you could reference the form element from the jQuery object like:
alert($('input[type=text]')[0].value);
But it's better for legibility and consistency to stay with one or the other, which in jQuery would be
alert($('input[type=text]').val());
but as you're inside a jQuery event handler for that element, you can get it with
alert($(this).val());

accessing html element after it gets loaded using jquery

I want to execute some code in javascript after one html element is loaded. The html element is generated by javascript code dynamically.
When I try to access the element I want to access I get undefined. I am accessing it in $(document).ready event
like this
alert($("#imgP").attr("src"));
$("#imgP").removeAttr("src");
$("#imgP").attr("src", "../../../../images/p.png");
How can I wait until the element is fully loaded so I can access it, is there any jquery event I use?
Try this:
$('body').on("load", "#imgP", function() {
alert($("#imgP").attr("src"));
$("#imgP").removeAttr("src");
$("#imgP").attr("src", "../../../../images/p.png");
});
have you tried onload function in html element?
ex :
<img onload="function()"/>
Always check the sequence of your method calls. I was trying to access the element even before it was created. Issue solved. Hope someone will find it helpful
If more than one object with same name exist, jquery simply operate on first object. So always give the context, which will tell jquery to find the object in particular div only. If no object find, jquery will not tell you or alert you still the you operate on its property or value.
So replace with $("#imgP") to $("impP", $("#yourparentdiv")) or you can check with $(#imgP)[0] (it is bad habbit, only for understand).
You can check via debugger before alert or count of object in $("#impP").length .
http://api.jquery.com/length/
http://api.jquery.com/jquery.each/
You can check .each via
$("#impP").each(function( key, value ) {
alert( key + ": " + value );
});

Does jQuery.submit() narrow down the scope of DOM elements?

Let's imagine that we have such code:
$('form[name = "someName"]').submit(function() {
var formInputValue = $('#inputId').val();
});
What will happen if there is another element with the same id on the same page as this form? Does jQuery.submit() function narrow down the scope of DOM elements available when we are inside function()? If not, how to simply get values of inputs being inside particular form?
If you use ID's, jQuery will stop at the first element matching that ID on the DOM. You should perhaps look at using jQuery's closest function or simply do:
$(this).serialize();
which will serialize your form.
Anyway, ID's should always be unique: https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really
If Submit on Form id and your page have two form with same id. it work on first form Submit.
If you want same function for more then one form you can use this code
$('form').submit(function() {
alert($(this).serialize());
return false;
});
Fiddle
If you need to access the data entered inside the form, consider calling .serialize() or .serializeArray()
Using the code you provided I guess jQuery will return the value of the first element found or an array with all values.
See the docs for further explanation:
https://api.jquery.com/serializeArray/
https://api.jquery.com/serialize/

Modify dynamically added elements on load using jQuery

I am converting old jQuery version 1.2.6 code that we use with our portal (Liferay). Previously we used the livequery plugin to add events to dynamically added DOM objects. This is now a feature built-in to jQuery (the on() function). I have that figured out.
However, there was also a feature in livequery that allowed us to modify these dynamically loaded objects on load (i.e. not tied to certain events):
$(".myTextBox").livequery(function() { $(this).val("initial value"); });
I do not control the code when the ajax portlets get loaded in our portal, so I can't modify the content when created.
I've tried a few things to no avail. Here is the one that I thought would work, but doesn't. I added jQuery to my portlet so that it loads at the bottom of the portlet HTML and I added jQuery to the file.
<footer-portlet-javascript>myscript.js</footer-portlet-javascript>
...
$(document).ready(function() {
$(".myTextBox").val("initial value");
});
This doesn't work. If I write an alert($(".myTextBox")) it shows an object, but alert($(".myTextBox").val()) is undefined.
Any ideas of how I can get working?
From what I read, you want to wire up events to items that have not been necessarily added to the DOM yet at the time you're wire-up function fires. I also read that you are upgrading to a more recent version of jquery.
If you're using jquery 1.7+, the .on() method should provide this capability for you. If you're using something between 1.2.6 and 1.7, you'll need to use the .live() method to achieve this behavior.
$(".myTextBox").live('click', function(e){
console.log(this.value);
});
Optionally, you may want to mix in some AUI to do your wiring-up on the Liferay 'allPortletsReady' published event. Here is some code we've used to wire-up items once all portlets are finished loading:
//This is the AUI version of on document ready
// and is just used to form a 'sandbox'(clojure)
// around our code so the AUI object A is not modified
AUI().ready(function(A){
//This essentially subscribes the provided function
// to the Liferay custom event 'allPortletsReady'
// so that when it's fired, the provided function
// will be called.
Liferay.on('allPortletsReady', function(){
//Do your initialization here
myCustomPortletManager.init();
//OR
A.one("#mySelector").on('click', function(e){
//do your work here
});
//Etc.
//NOTE: jQuery ($) is valid inside this sandbox for our
//instance.
});
}):
Well you can setInterval to iterate checking new element.
setInterval(function(){
var $ele = $('.myTextBox:not(.loaded)'); // find new element that not loaded
if($ele.size() > 0){
$ele.each(function(){
// do stuff with elements
$(this).val("initial value");
}).addClass('loaded'); // flag this element is loaded
}
}, 200); // set delay as you wish
by the way, I'm not recommended this.
First, you probably want to use an ID instead of a class in this case to ensure you are referring specifically to a single element.
Where your alert is will determine whether this code is executed before or after. This would explain that you return an object, but no value. Put it after the value assignment, either on the page or temporally.
The following works just fine (http://jsfiddle.net/4WHyE/1/):
<input id="myid"/>
$('#myid').val('some value')
alert($('#myid').val())
If you must use class, then it depends on whether you want to set each class element individually or all to the same value. If you wish them all to have the same value, simply replace id with class in the above example:
<input class="myclass"/>
$('.myclass').val('myvalue')
If you wish to set unique values, you can simply iterate through them (http://jsfiddle.net/4WHyE/2/):
$('.myclass').each(function(index){
$(this).val('value' + index)
});

Unexpected error using an indexed element id

I'm new to javascript and jquery, and stumbled upon an issue while writing a script.
My script is generated by php code which reads lines from a file, parses it and prints them out using arrays. js then validates form input, and outputs useful messages to the user.
I have successfully used js and jquery on $('#id').blur on various elements. However when I tried doing it on my indexed element, I came across this problem.
Code:
$('#NS_IN[0]').blur(function() {
alert("Called");
CopyNStoMain();
});
I noticed that this function would never get executed. I tried looking at the variables in console.
typeof($('#NS_IN[0]')) is an object; but typeof($('#NS_IN[0]').val()) is Undefined.
In my html code, I have:
<input type="text" id="NS_IN[0]" value="" name="NS[0]">
What am I doing wrong? If the id NS_IN[0] is defined and $(NS_IN[0]) refers to an object, shouldnt $(NS_IN[0]).val() exist and hold the value of the input box?
You need to escape the jquery selector characters.
$('#NS_IN\\[0\\]').blur(function() {
alert("Called");
CopyNStoMain();
});
You already have the answer here...I don't know how to tag your question as a duplicate.
//get
bla = $('#txt_name').val();
//set
$('#txt_name').val('bla');
In jQuery, the [] works in a different way, like:
div[id^="player_"]
So, one of the solutions, is to select the items which ID starts with something:
$("input[id^=NS_IN]").val();
It works when you use a different selector, as jquery uses the [] as an attribute selector itself. So use e.g. (see fiddle: http://jsfiddle.net/rePQm/1/ ):
$('input').click(function() { alert("clicked " + this.id); });
an element selector that selects all input elements and adds the click handler to all of them. See the selectors section of the jquery documentation at http://api.jquery.com/category/selectors/ for more possible selectors .

Categories

Resources