check all inputs value in jquery [duplicate] - javascript

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")

Related

find element html with jquery

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"]')

Why this code is not generating any alert message

Here i have written some that is for validation on form in html and javascript
<!DOCTYPE html>
<html>
<body>
<form name="registration">
<input style="font-size:16px;" type="text" name="Name" placeholder="Full Name" onchange="checkName()" required />
</form>
<script>
function checkName()
{
var uname=document.registration.Name.value;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
alert('fg');
}
else
{
alert('Username must have alphabet characters only');
//uname.focus();
}
}
</script>
</body>
</html>
Please describe why it is not working?
The problem is that you're trying to get the value property TWICE. Like such:
var uname=document.registration.Name.value;
if(uname.value.match(letters))
Your uname variable already contains the value, so you don't need to get it again. Change your if statement to this...
if (uname.match(letters))
And it works just fine :)
Using onchange with input type = "text" is quite uncommon
onchange event usually occurs only after you leave (blur) the control.
onchange is mainly associated with change of select element.
For your case it is better to use keydown, keyup and keypress events as well.
HTML
<input style="font-size:16px;" type="text" name="Name" placeholder="Full Name" onkeyup="checkName()" required />
Jsfiddle

Unable to set value attribute for placeholder if value is empty using jquery

Below is a sample HTML code with script tag using jquery:
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var email_def= "Enter email address";
$('input[type="email"]').attr('value', email_def).focus(function() {
if ($(this).val() == email_def) {
$(this).attr('value', '');
}
}).blur(function() {
var val = $(this).val();
if (val == '') {
$(this).attr('value', email_def);
alert(val);
alert(email_def);
}
});
});
</script>
</head>
<body>
<form>
Email: <input type="email"> <input type="submit" id="submit">
</form>
</body>
</html>
Steps to reproduce:
Click in the input box. Placeholder value is cleared. Click outside, placeholder value is now reset back.
Click in the input box. Type some text. Delete the text. Click outside. The placeholder value is not reset back.The alert are triggered. Even the email_def is being shown in alert. Now, the attribute value is not being reset to value of email_def.
My question is why is the line $(this).attr('value', email_def); not being invoked inside the blur function.
Edit: Thanks for the answers. Both, the placeholder of html5 and also replacing with the $(this).val(); line seems to be working correctly
Instead of $(this).attr('value', email_def);, consider $(this).val(email_def);. It will behave as you've specified.
Rafael is correct to suggest using HTML's placeholder instead, unless you have some specific need regarding Internet Explorer.
Use HTML5 Placeholder attribute
A hint to the user of what can be entered in the control . The
placeholder text must not contain carriage returns or line-feeds. This
attribute applies when the value of the type attribute is text,
search, tel, url or email; otherwise it is ignored.
http://jsfiddle.net/xj7v8gd7/
<form action="<some action>">
<input type="email" id="emailForm" size="30" placeholder="Enter email address"><br>
<input type="submit" value="Submit">
</form>
Rafael is correct. However, if you need it to work in browsers old enough that they don't support the placeholder attribute, just switch your value attribute setters to use the overload on val() instead. So:
$(this).val('Enter the email address') //for example
See that demonstrated below (it looked like only the one in the blur method was actually a problem.
$(document).ready(function() {
var email_def = "Enter email address...";
$('input[type="email"]').attr('value', email_def).focus(function() {
//alert('focus');
if ($(this).val() === email_def) {
$(this).val('');
}
}).blur(function() {
if ($(this).val() === '') {
$(this).val(email_def);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
Email:
<input type="email" id="emailForm" size="30" />
<input type="submit" id="submitForm" />
</form>

Accessing HTML DOM elements from javascript using `.childNodes`

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);
}

I Need A Javascript Code That Will Place The Word "Search" In An Empty DIV Value Tag Using The id=

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/

Categories

Resources