I'm wondering about the .childNodes property, I have the code below, and for some reason I get 18 children, while 6 are HTMLInputElements as expected, and the rest are undefined. What is this about? Is there an efficient way to iterate over the input elements?
<html>
<head>
<script>
window.onload = function(e){
form = document.getElementById('myForm');
alert(form.childNodes.length);
for(i=0; i<form.childNodes.length; i++){
alert(form[i]);
}
}
</script>
</head>
<body>
<form id='myForm' action="haha" method="post">
Name: <input type="text" id="fnameAdd" name="name" /><br />
Phone1: <input type="text" id="phone1Add" name="phone1" /><br />
Phone2: <input type="text" id="phone2Add" name="phone2" /><br />
E-Mail: <input type="text" id="emailAdd" name="email" /><br />
Address: <input type="text" id="addressAdd" name="address" /><br />
<input type="submit" value="Save" />
</body>
</html>
Text nodes, even if they consist only of whitespace, will also be included in the output, as will the br elements.
Use .children instead if you want all the elements, including br. This will give you element nodes only. I think older IE incorrectly includes comment nodes, but you have none in your code, so no issue.
Or you could do...
form.getElementsByTagName('input')
...assuming you only wanted the input elements.
And besides that: you forgot to close your form element.
childNodes also returns text nodes; this is probably the source of your confusion.
To iterate through all the childNodes, but only pay attention to the INPUTs, simply check the node's tagName property. If the node is a text node it won't have a tagName, and if the node does have a tagName you can check whether tagName == "input".
Use form.elements to get all form fields, or form.getElementsByTagName('INPUT') to get INPUT elements inside the form.
form.elements is the quick way to access every element of a form-
window.onload = function(e){
var s='', form = document.getElementById('myForm'),
L=form.elements.length;
s=L+'\n';
for(var i=0;i<L; i++){
s+= (form[i].name || form[i].id)+'='+form[i].value+'\n';
}
alert(s);
}
Related
How do I identify empty textboxes using jQuery? I would like to do it using selectors if it is at all possible. Also, I must select on id since in the real code where I want to use this I don't want to select all text inputs.
In my following two code examples the first one accurately displays the value typed into the textbox "txt2" by the user. The second example identifies that there is an empty textbox, but if you fill it in it still regards it as empty. Why is this?
Can this be done using just selectors?
This code reports the value in textbox "txt2":
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#cmdSubmit').click(function() {
alert($('[id=txt2]').val());
});
});
</script>
</head>
<body>
<form>
<input type="text" name="txt1" id="txt1" value="123" /><br />
<input type="text" name="txt2" id="txt2" value="" /><br />
<input type="text" name="txt3" id="txt3" value="abc" /><br />
<input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
</form>
</body>
</html>
This code always reports textbox "txt2" as empty:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#cmdSubmit').click(function() {
if($('[id^=txt][value=""]').length > 0) {
if (!confirm("Are you sure you want to submit empty fields?")) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
}
});
});
</script>
</head>
<body>
<form>
<input type="text" name="txt1" id="txt1" value="123" /><br />
<input type="text" name="txt2" id="txt2" value="" /><br />
<input type="text" name="txt3" id="txt3" value="abc" /><br />
<input type="submit" name="cmdSubmit" id='cmdSubmit' value="Send" /><br />
</form>
</body>
</html>
Another way
$('input:text').filter(function() { return $(this).val() == ""; });
or
$('input:text').filter(function() { return this.value == ""; });
or
// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK!
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to #AaronLS
$('input:text[value=""]');
Working Demo
code from the demo
jQuery
$(function() {
$('#button').click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
var string = "The blank textbox ids are - \n";
emptyTextBoxes.each(function() {
string += "\n" + this.id;
});
alert(string);
});
});
You could also do it by defining your own selector:
$.extend($.expr[':'],{
textboxEmpty: function(el){
return $(el).val() === "";
}
});
And then access them like this:
alert($(':text:textboxEmpty').length); //alerts the number of text boxes in your selection
$(":text[value='']").doStuff();
?
By the way, your call of:
$('input[id=cmdSubmit]')...
can be greatly simplified and speeded up with:
$('#cmdSubmit')...
As mentioned in the top ranked post, the following works with the Sizzle engine.
$('input:text[value=""]');
In the comments, it was noted that removing the :text portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.
So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll will only return elements that have value="" in the HTML. Caveat emptor.
$("input[type=text][value=]")
After trying a lots of version I found this the most logical.
Note that text is case-sensitive.
There are a lot of answers here suggesting something like [value=""] but I don't think that actually works . . . or at least, the usage is not consistent. I'm trying to do something similar, selecting all inputs with ids beginning with a certain string that also have no entered value. I tried this:
$("input[id^='something'][value='']")
but it doesn't work. Nor does reversing them. See this fiddle. The only ways I found to correctly select all inputs with ids beginning with a string and without an entered value were
$("input[id^='something']").not("[value!='']")
and
$("input[id^='something']:not([value!=''])")
but obviously, the double negatives make that really confusing. Probably, Russ Cam's first answer (with a filtering function) is the most clear method.
Building on #James Wiseman's answer, I am using this:
$.extend($.expr[':'],{
blank: function(el){
return $(el).val().match(/^\s*$/);
}
});
This will catch inputs which contain only whitespace in addition to those which are 'truly' empty.
Example: http://jsfiddle.net/e9btdbyn/
I'd recommend:
$('input:text:not([value])')
This will select empty text inputs with an id that starts with "txt":
$(':text[value=""][id^=txt]')
Since creating an JQuery object for every comparison is not efficient, just use:
$.expr[":"].blank = function(element) {
return element.value == "";
};
Then you can do:
$(":input:blank")
how to find element html with Jquery .
in this example element html is "input"
jsfiddle
$("#her").click(function() {
var $t = $('#mee');
console.log($t.filter());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mee">
<input type="submit" value="click ici" id="her">
$(this).prev().prop('nodeName');
I believe this was the JSFiddle link - http://jsfiddle.net/sr2o412y/
<input type="text" id="mee">
<input type="submit" value="click ici" id="her" >
If you want to select a element using jquery you can use (#)id attribute or (.) class attribute or (input) html tagname.
In this case if you want to take the data from text element which has id => "#mee" on click if id => "#her". You can use the below code
$('#her').on('click', function(){
var textvalue = $('#mee').val();
console.log(textvalue);
});
Provide readable id and class names to identify elements properly.
Your selectors looks fine to me. In short, you can use any valid CSS selector, so both $('#her') and $('#mee') should be working in your example, as you have HTML elements with those ids:
$('#her').click(function() {
var $t = $('#mee');
console.log($t.val());
});
<input type="text" id="mee" />
<input type="submit" id="her" value="SUBMIT" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you want to select an element based on its type (tag) instead, then just remove the #. For example, to select any input element on the page you would just do:
$('input')
Or, to get just the first one:
$('input').first()
Or also:
$('input').eq(0)
You can also select elements based on type plus attribute to select specific inputs:
$('input[type="text"]')
this corresponds to a specific div.
I would like to insert a piece of code after its grandparent using this code but it doesn't seem to work: this.parentNode[0].parentNode[0].insertAfter(newrespondform);
I can provide more code if needed but after trying to debug I'm pretty ure the problem lie in here.
How could I write it so that it works? I cannot add an ID to the grandparent to select it that way.
Thanks for your aid :)
EDIT - here is the entire code that gets loaded on page load:
function comrespond(){
function addresform(){
var resid = this.getAttribute('id'),
grandParent = this.parentNode.parentNode,
newrespondform = '<div class="commentresponse"><span></span><span><p class="author">Leave a reply:</p><form id="commentform" action="http://split.snippetspace.com/wp-comments-post.php" method="post" onsubmit="addcomment(); return false;"><input id="author" aria-required="true" name="author" type="text" placeholder="Your name"/><input id="email" aria-required="true" name="email" type="text" placeholder="Email address" /><textarea id="comment" aria-required="true" name="comment" rows="8"></textarea><input id="submit" name="submit" type="submit" value="Post Comment" /><input id="comment_post_ID" name="comment_post_ID" type="hidden" value="'+resid+'" /></form></span></div>';
grandParent.parentNode.insertBefore(newrespondform, grandParent.nextSibling);
}
var responsebtn = document.getElementsByClassName('comment-reply-link');
for(var i = 0; i < responsebtn.length; i++){
bindEvt(responsebtn[i], "click", addresform);
};}
the HTML:
<div>
<span></span>
<span>
<p class="author">Christopher</p>
<div class="comment-reply-link" id="106"></div>
<p>test comment 2 to see if it increments!</p>
</span>
</div>
There are several problems in your code.
First, property parentNode contains a single node only, not a set of nodes, hence you don't need to apply [0] to get the first node. Next, there is no insertAfter method in native JavaScript. Instead you may use a trick with insertBefore. So the solution might look like that:
var grandParent = this.parentNode.parentNode;
grandParent.parentNode.insertBefore(newrespondform, grandParent.nextSibling);
parentNodeis not an array, so just getting rid of the [0] should do it I think.
this.parentNode.parentNode.insertAfter(newrespondform);
I have no access to the html, I need JavaScript code that will add the word "Search" to the value="" that is blank for the input with id "ReportQuery".
How should I code it?
Here is the code below:
<div>
<input name="data[Report][query]" type="text" class="input_firm" value="" onChange="this.form.submit();" onClick="if( this.value == 'Search' ) { this.select(); }" id="ReportQuery" />
<input type="submit" value="Search" />
</div>
if its a div
$('div#idDiv').text('search');
if its an input (because you comment .value :S)
$('input#idDiv').val('search');
See this article, it comes with many examples and details:
http://www.javascript-coder.com/javascript-form/javascript-form-value.phtml
BTW, this is about the "direct" JS way, no jQuery involved, e.g.
oFormObject = document.forms['myform_id'];
oFormObject.elements["element_name"].value = 'Some Value';
$('#ReportQuery').val('Search');
http://jsfiddle.net/L9YS4/
A good place to start for learning jQuery:
http://jqfundamentals.com/
I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.