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 .
Related
Firstly, I do know that it is against best practice for multiple elements to have the same ID in a single page. However in this case I need for there to be two selects with the same id.
I have seen some success using this method:
$('#undo_redo_to option').length;
$('#undo_redo_to:eq(0) option').length;
*$('#undo_redo_to:eq(1) option').length;*
However, the code enclosed in *'s does not give me the proper length.
Please see the following pen, where I have created my selects and did my debugging.
LINK TO CODE
Thanks!
The problem is that jQuery uses the native JS functions first, so when you do a $('#this_id') you are effectively calling document.getElementById('this_id'). it's not just against best practice, it actually won't work... you could loop through your selects and check the id:
$('select option').each(function(){
if($(this).closest('select').attr('id')=='my_id'){
//do something
}
});
Assuming you've inherited the HTML and cannot change the ids to classes:
Note that eq() is a jQuery selector. If you change it to nth-child(2), you'll be using a CSS selector. That gives you what you need:
$('#undo_redo_to:nth-child(2) option').length;
http://codepen.io/anon/pen/WwERGW?editors=1011
You can do it with native javascript, like this:
document.querySelectorAll("[id=undo_redo_to]")
You can do it with jquery like this:
$("[id=undo_redo_to]")
This is the property selector, as the #-type selector will stop searching when the first element having that id was found.
So you can do this using plain javascript or jquery, but don't do it, because id should be unique and if it is not unique, then the HTML is invalid and it is bad for SEO.
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 );
});
I have an online order form which works great! the only thing thats wrong is that i cant seem to find a way to send the input data from the text fields with Naam:, Adres: etc. (which is at the bottom of the code) i found out that i could use this code : $("#txt_name").val(); but it does not work properly. And i don't really know in which function i have to pace de code. Can someone help me? i'm not very experienced with jquery.
working website
javascript without the html
In your code you have the following
$(".txt_name").val();
You are using . as a class selector, you should use
$("#txt_name").val();
With # as an id selector
The first one gives you an array because you are selecting multiple elements and the second one gives you an element. I testet it in the browser console and it returns the value of the #txt_name Naam, but the first one returns undefined since .txt_name does not exist.
The same applies to the other fields, give them and id and you can get their values the same way.
$("#txt_name").val() should return a string which you can store in a variable of pass to a function.
if you want it to return something usefull "#txt_name" must be an input element or an element with a value attribute.
lets say you have a test inpu tag with the id="txt_name" if a user writes something that elements value attribue will be that text, even if you dont see it on the tag itself.
so $("#txt_name").val() will return the value of the value attribute of the htmlElement.
If I use jquery to select all my text inputs:
var inputs = $('#form input[type="text"]');
They are wrapped in jQuery. I can do whatever I want with them.
inputs.css('height', '1000px');
//muhahaha!
As a group they abide. But I seem to be missing something. I know I can see each one individually as if it was an array of objects.
console.log(inputs[0]);
// <input type="text" />
But the above output is just the html; when I do that it's no longer a jQuery object :(
inputs[0].css('font-size', '100px');
// Uncaught TypeError: Object #<HTMLInputElement> has no method 'css'
How do I continue to use jquery's methods on the individual without having to wrap each element again, or is this not possible for some strange, dark, inexplicable reason?
Didn't even know where to begin searching this one, and my jQuery journey has not lead me to the answer thus far. Thanks!
Have a look at this page: jQuery Filtering
inputs.eq(0).css('font-size', '100px');
Should do the trick in this case
see this function .eq() in Jquery-API
When access the Dom-Node-Collection in JQuery via Array-Index, you get the RAW Dom-Elements, if you select the index with the given method above, you'll get feature-enhanced jQuery-Wrapped-Elements.
See docs.
The only way to avoid wrapping each element again($(inputs[0]).css('font-size', '100px'))
would be using pure JavaScript. Example: inputs[0].style.fontSize = "100px";
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()