I have textboxes that I want to show the error prompt beside it onkeyup event, but with no luck, it doesn't work. I have this as my reference: I want to show error message beside my textbox rather than alert in onkeyup event
$(function() {
$("#name").next('span').hide();
$("#name").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (name == "") {
span.text("Please enter your name").show();
return;
}
span.text('').hide();
});
$("#age").next('span').hide();
$("#age").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (age == "") {
span.text("Please enter your age").show();
return;
}
span.text('').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<hr>
<span></span>
<input type="text" id="age" name="age" />
<span></span>
You are using wrong variable names to check the values of the name field and age field.
Also, the span for the name field is after the hr it should be right next to the input field.
Check the snippet below, see the comments added;
Notice the Regex .replace(/\s/g,'') for removing all whitespace in the if condition.
$(function() {
$("#name").next('span').hide();
$("#name").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (input.replace(/\s/g,'') == "") { // wrong variable, name is undefined, should be input, also the regex is for removing all whitespaces;
span.text("Please enter your name").show();
return;
}
span.text('').hide();
});
$("#age").next('span').hide();
$("#age").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (input.replace(/\s/g,'') == "") { // same here
span.text("Please enter your age").show();
return;
}
span.text('').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<span></span> <!-- span should be here, before the hr line break -->
<hr>
<input type="text" id="age" name="age" />
<span></span>
Related
I wrote the below code for changing the text of div that called active yes, based on value of each input with type hidden.
i want to change the text of this div if input with id enable to "Enable List" and if input with classname delete has value changes the div text to "Deleted list" and if both of them was null show "list".
my code does not work correctly.
what is my problem?
here is my snippet :
$(document).ready(function() {
tmpval = $('#enable').val();
if (tmpval == '') {
$('.activeyes').text('list');
} else {
$('.activeyes').text('Enable List');
}
tmpval2 = $('#delete').val();
if (tmpval2 == '') {
$('.activeyes').text('List');
} else {
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
You are overwriting effect of the first check by the second check; you need to check the 2 inputs value together. Still, it is unclear what will happen if both are non-empty.
$(document).ready(function() {
tmpval = $('#enable').val();
tmpval2 = $('#delete').val();
if (tmpval == '' && tmpval2 == '') {
$('.activeyes').text('list');
} else if( tmpval!='' ){
$('.activeyes').text('Enable List');
} else if( tmpval2!='' ){
$('.activeyes').text('Deleted List');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
what is my problem?
You need to check the value of input when it changes its value, so capture the change event.
$(document).ready(function() {
$('#enable, #delete').change(function() {
var $this = $(this);
var id = $this.attr("id");
var value = $this.val();
if (value.length == 0)
{
$('.activeyes').text('list');
}
else
{
id == "enable" ? $('.activeyes').text('Enable List') : $('.activeyes').text('Deleted List');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" value="aa" id="enable" />
<input type="text" value="" id="delete" />
<h1 class="activeyes"> List</h1>
I have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>
I have a very simple form. Full Name/Email. What I want to do is check with jquery to make sure that they entered AT LEAST 5 characters in the name field. And if they did not, then I don't want the form to be submitted, instead I want to print some HTML below the form showing a warning/error message. How can I accomplish this?
Also Can I add words manually to the script to make sure they were not entered in the name field? And if they were to make sure it prints errors again... For example, if they entered the word "bobby" or "stephanie" I don't want the form to be submitted if those EXACT words are entered. It is only like 5 or 6 words I want blocked, so I can enter them manually no problem in the script without bloating anything.
Thank you so much in advance.
Here is my HTML
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1">
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email">
</div>
And this is the added HTML I want printed if the jquery check is false
<div id="error">
<span class="error_message">Please enter your full name</span>
</div>
Let's assume your form has an id of myForm.
var words = ["bobby", "stephanie"];
jQuery('#myForm').on('submit', function(evt) {
var form = $(this);
var full_name = form.find('#full_name');
var name_length = full_name.val().length;
if( name_length < 5 ) {
jQuery('#error').show();
evt.preventDefault();
}
if( jQuery.inArray(full_name.val(), words) ) {
evt.preventDefault();
}
});
Here is my answer: there are two if statements that we can construct:
Test if length of input exceeds 5 characters, and
Test if the input matches a list of banned words (stored in an array for convenience and verbosity)
It is a little complicated with the second conditional statement, since we want an exact match (therefore, using 'bobby' will raise a flag, but not 'bobby123'. This involves the use of word boundaries, \b.
You can view the code in action in this fiddle: http://jsfiddle.net/teddyrised/kmMcC/
$('form').submit(function(e) {
var errorFlag = 0,
bannedWords = [
'bobby',
'stephanie'
],
bannedObj = new RegExp('\\b'+bannedWords.join('|')+'\\b', 'i');
if($('#full_name').val().length <= 5) {
errorFlag = 1;
}
if(bannedObj.test($('#full_name').val())) {
errorFlag = 1;
}
// Act on error flag, prevent form submission when one or more error flags are raised
if(errorFlag) e.preventDefault();
});
Assuming you put this all in a form element, and add an input type='submit' element to it, I would suggest setting the form's onsubmit attribute to "return Validate();", and add the below validation function.
First you'll want to hide the message on ready using: $('error').hide();
function Validate(){
var minLength = 5;
var blockedNames = ["bobby","stephanie"];
var fName = $('#full_name').val();
if(fName.length < minLength){
$('#error').show();
$('#full_name').focus();
return false;
}
for(var i = 0;i < blockedNames.length;i++){
if(fName == blockedNames[i]){
$('#error').show();
$('#full_name').focus();
return false;
}
}
return true;
}
JSFIDDLE DEMO: http://jsfiddle.net/softvar/hv6yB/2/
UPDATE:
HTML
<form onsubmit="return check()">
<div id="div1">
<label id="name-label" for="full_name">Name</label>
<input id="full_name" type="text" name="name" tabindex="1" autofocus="1" />
</div>
<div id="div2">
<label id="email-label" for="email_address">Email</label>
<input id="email_address" type="email" tabindex="2" name="email" />
</div>
<input type="submit" value="Submit"/>
</form>
<div id="error" >
<span class="error_message">Please enter your full name</span>
</div>
CSS
#error {
color:red;
display: none;
border: 1px solid #D9534F;
background: #FDF7F7;
width: 80%;
height: 25px;
padding: 5px;
}
JS
function check() {
var bannedWords = ['bobby','stephen'];
var name= $('#full_name').val();
if(name){
if(name.length>5){
for(var i=0;i<bannedWords.length;i++) {
if(bannedWords[i] ==name){
$('#error').text('Its a banned word');
$('#error').css('display','inline-block');
return false;
}
}
alert('form is going to be submitted');
return true;
}
else{
$('#error').text('Name is shorter');
$('#error').css('display','inline-block');
return false;
}
}
$('#error').text('Name cant be blank');
$('#error').css('display','inline-block');
return false;
}
Here's my javascript:
$("#cname, #cemail, #curl, #ccomment").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("");
}
}).blur(function() {
if( !this.value.length ) {
$(this).val(this.defaultValue);
}
});
$.validator.addMethod("noName", function(value, element) {
return value != element.defaultValue;
}, "Please enter your name.");
$.validator.addMethod("noComment", function(value, element) {
return value != element.defaultValue;
}, "Please enter your comment.");
$("#commentForm").validate();
The actual form:
<form id="commentForm" action="">
<p>
<input id="cname" name="name" size="25" class="required noName" value="Name">
</p>
<p>
<input id="cemail" name="email" size="25" class="email" value="Email">
</p>
<p>
<input id="curl" name="url" size="25" class="url" value="URL">
</p>
<p>
<textarea id="ccomment" name="comment" rows="5" cols="35" class="required noComment">Comment</textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</form>
And here's a test: http://dl.dropbox.com/u/4017788/Labs/form-validation.html
If you click the submit button, you get error messages on Email and URL fields while they are optional. How can I prevent it?
Simple approach: add an igonre class to Email and URL fields and removeClass / addClass on focus / blur. Test:
http://dl.dropbox.com/u/4017788/Labs/form_validation.html
see validate options for more information.
Alternatively you can completely get rid of the class attribute and then:
on focus >> this.className = 'url'
on blur >> this.className = ''
without changing the validate call.
You can't use the classes 'url' and 'email' for those two form fields, because the plugin is going to try and validate them because they are 'reserved' classes in the plugin . I would suggest trying doing something like this for both the email and url fields.
I haven't tried this, but it suggests that you can custom, but not required field.
You could use the HTML5 placeholder element all the same, but test for placeholder support and then polyfill for it if not available, for example
//test
function placeholderIsSupported() {
var test = document.createElement('input');
return ('placeholder' in test);
}
//polyfill
if(!(placeholderIsSupported())) {
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function () {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function () {
$(this).find('[placeholder]').each(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
However, strictly speaking what you're doing is providing labels rather than example values for the inputs, so it would probably be more correct/standards-y to use elements <label> and position them behind the inputs, and then hide them when the inputs are focused/have non-empty values, eg:
HTML:
<p class="row">
<label for="name">Name</label>
<input id="cname" name="name" size="25" class="required noName" value="">
</p>
CSS:
.row {
position: relative;
}
input,
label {
display: block
}
label {
position: absolute;
/*tweak these until label correctly positioned behind input*/
top: 0;
left: 0;
}
input {
background-color: transparent;
}
input:focus,
input.has-value {
background-color: #fff; //hide the label behind the bg color when focused or non-empty
}
jQuery:
//toggle a class depending on whether an input has content or not
input.on('blur', function(){
var $this = $(this);
if ($this.val === "") {
$this.removeClass('has-value');
}
else {
$this.addClass('has-value');
}
});
This second option is more semantic and more accessible too, given that screen reader support for placeholder is patchy
I have two checkboxes in a group and one text input. If one (or both) of the checkboxes are selected I need to have the text input be required, as well as if the text input has text I need at least one of the checkboxes to be required. Another problem I'm having it that it's using a custom templating engine (PHP backend) and is a pain to configure and get the attributes correct, another issue is it's all referenced by the name attribute and this is why I'm using a HTML5 data-group for the checkbox options which I think it working.
Any help in getting this to work, combining functions (if this makes it easier/simpler).
BTW it's running 1.3.2 jQuery
Example: (not working)
http://jsfiddle.net/NYn8e/1/
Any suggestions?
JS:
function checkboxSelectedRequiredAdditionalFields(elem) {
var passedElement = $('input:checkbox[name=' + elem + ']');
passedElement.click(function() {
$('input[name=number]').attr('required', true).append('<span class="required">*</span>');
alert('text is required now?');
});
}
function numberEnteredRequiredAdditionalFields(elem) {
var passedElement = $('input[name=' + elem + ']');
if (passedElement.val().length > 0) {
var boxes = $('input[data-group=cbOptions]').click(function() {
boxes.not(this).attr('required', false);
alert('checkbox is selected so other checkbox is not required');
});
$('input[data-group=cbOptions]').each(function() {
$(this).attr('required', true).next().append('<span class="required">*</span>');
alert('checkbox is required now?');
});
}
}
HTML
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox1');" data-group="cbOptions">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" onclick="checkboxSelectedRequiredAdditionalFields('checkbox2');" data-group="cbOptions">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" onclick="numberEnteredRequiredAdditionalFields('number');">
</b>
</form>
You should separate the JavaScript from the HTML. Fiddle: http://jsfiddle.net/NYn8e/6/. If possible, remove <b> from the HTML source, and extend the style sheet with the right CSS property: font-weight: bold;.
<form>
<label>
<input type="checkbox" name="checkbox1" value="t" data-required="checkbox">
Checkbox Option 1
</label>
<label>
<input type="checkbox" name="checkbox2" value="t" data-required="checkbox">
Checkbox Option 2
</label>
Number <b>
<input type="text" name="number" value="" size="" maxlength="9" data-required="number">
</b>
</form>
JavaScript:
function required(){
//Any checked checkbox? checked == 0 = no, otherwise: yes
var checked = $('input[data-required=checkbox]:checked').length;
var $checkboxes = $('input[data-required=checkbox]');
var $num = $('input[name=number]');
var length = $num.val().length;
//Remove previously added span, if existent.
$num.next('span.required').remove();
$checkboxes.next('span.required').remove();
if(!length && checked){
$num.after('<span class="required">*</span>');
alert("Number required!");
} else if(length && !checked){
$checkboxes.after('<span class="required">*</span>');
alert("Check at least one checkbox.");
}
}
$(document).ready(function(){
$("[data-required]").change(required);
});
=) Would this one help you?
<form id='myForm'>
<input type='checkbox' name='checkbox1' value='t' id='checkbox1' onchange='alertUser()' />
<input type='checkbox' name='checkbox2' value='t' id='checkbox2' onchange='alertUser()' />
<input type='text' name='number' id='number' onchange='alertUser()'/>
</form>
<script type='text/javascrip>
function alertUser() {
var checked1 = $('#checkbox1').attr('checked');
var checked2 = $('#checkbox2').attr('checked');
var number = $('#number').val();
if ((checked1 == true || checked2 == true) && number == '') {
alert('Number is required!');
} else if (number != '' && (checked1 != true && checked2 != true)) {
alert('One of the checkbox need to be checked!');
}
});
</script>
This should hopefully give you an idea on how to accomplish the task. http://jsfiddle.net/NYn8e/8/
var $textbox = $('input[name=number]').hide();
$('input[type=checkbox]').change(function() {
var $this = $(this); //store jquery object
//get the other checkbox
var $other= ($this.attr('name') === 'checkbox1') ? $('input[name=checkbox2]') : $('input[name=checkbox1]');
if (!$other.is(':checked') && !$this.is(':checked')) {
$textbox.val('').hide();
} else{
$textbox.show();
}
});