Disable HTML Button when characters are less than 3 - javascript

I'm currently working with a news website and I want to make a search function that disables the search button until the input has three characters.
Here's my current code
<div style="margin-left: 300px; margin-top: 25px; margin-bottom: 20px;">
<form action="searchnews.php?p=0" method="POST">
<input type="text" id="searchterm" name="searchterm" placeholder="Buscar Término...">
<input type="submit" id="search" value="Buscar Noticia" class="search" disabled="disabled" />
</div>
And I added this JS file:
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})()
I want to make it stop disabling the button until the third character is in, not when the first one is, I've tried everything and nothing works. Any ideas? I'd really appreciate it.

Why dont you try the .length?
if ($(this).val().length <= 3) {
empty = true;
}

In the answer by #Dim_Ch, .lenght isn't a function.
You may use this
if ($(this).val().length <= 3) {
empty = true;
}

Try the following. It worked. It'll also reduce the function length.
(function() {
$('input#searchterm').keyup(function() {
var enable = false;
if ($(this).val().length >= 3) {
enable = true;
}
if (enable) {
$('#search').removeAttr('disabled');
} else{
$('#search').attr('disabled','disabled');
}
});
})()
Edit: I'll reduce it further:
(function() {
$('input#searchterm').keyup(function() {
$('#search').attr('disabled', $(this).val().length < 3? true : false);
});
})()

(function() {
$('form > input').keyup(function() {
var empty = false;
$(this).each(function() {
console.log($(this).val().length);
if ($(this).val().length >= 3) {
empty = true;
}
});
if (!empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})()

Related

Css change on value change in input field. jQuery

var footerEmail = $('footer#footer input.email');
var footerEmailLength = footerEmail.val().length;
var footerEmailCaptcha = $("footer#footer .captcha-hide");
footerEmail.focus( function() {
footerEmailCaptcha.css("display","block");
});
footerEmail.blur( function() {
if(footerEmailLength > 0) {
footerEmailCaptcha.css("display","block");
}
else if (footerEmailLength == 0) {
footerEmailCaptcha.css("display","none");
}
});
.captcha-hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<footer id="footer">
<input class='email'>
<div class="captcha-hide">Testing</div>
</footer>
I want to make sure that onblur works when I enter something inside the text (input) field.
First if condition inside the blur function is not working since it is taking the value as '0' which will be initially. When I enter something and click outside of the input field then the css should be display:block
Please guide me how I can proceed further. I am new to jQuery/Javascript. Googling around to learn stuff.
you have to give the var footerEmailLength = footerEmail.val().length; inside blur function.
The blur function should be like this:
footerEmail.blur( function() {
var footerEmailLength = footerEmail.val().length;
if(footerEmailLength > 0) {
footerEmailCaptcha.css("display","block");
}
else if (footerEmailLength == 0) {
footerEmailCaptcha.css("display","none");
}
And if you use class as selector then change the footerEmail.val().length
to footerEmail[0].val().length.
The running code
var footerEmail = $('.email');
var footerEmailCaptcha = $(".captcha-hide");
footerEmail.focus( function() {
footerEmailCaptcha.css("display","block");
});
footerEmail.blur( function() {
var footerEmailLength = footerEmail[0].val().length;
if(footerEmailLength > 0) {
footerEmailCaptcha.css("display","block");
}
else if (footerEmailLength == 0) {
footerEmailCaptcha.css("display","none");
}
});
.captcha-hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<footer id="footer">
<input class='email'>
<div class="captcha-hide">Testing</div>
</footer>

Check whether the required field is not empty

I want to check whether the required field is empty or not.
I used the code below.
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "")
alert("Empty Fields!!");
}
});
But it was alert more than one time.
JSFiddle:
http://jsfiddle.net/hbk2a5qo/3/
Why not directly use required attribute in HTML:
<input id="name"type="text" data-label="required" required/>
You need to use a flag
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault()
AlertSave();
});
});
function AlertSave() {
//use the flag to set the valid status in the loop
var valid = true;
//iterate over only the required elements
$(':input[data-label="required"]').each(function () {
if ($(this).val() === "") {
valid = false;
return false;
}
});
if (valid) {
//do your save
} else {
alert("Empty Fields!!");
}
}
Demo: Fiddle
As you have used $(":input").each() so it will go through all fields. But you can use flag to show alert only once.
function AlertSave() {
var alertShown=false;
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "" && !alertShown)
{
alertShown=true;
alert("Empty Fields!!");
}
}
});
}
You Updated Fiddle
By using required attribute (which is recommended), this will return all the required input fields that has no value:
var inputsWithMissingValues = $('input[required]').filter(function(i, input) {
return !input.value.length;
});
So, if the length of that is more than zero, then you have required fields with missing value.

bootstrap popover not firing

I have this code:
HTML
<input type="text"
data-placement="bottom"
data-trigger="manual"
data-content=""
name="momlastname" id="momlastname"
ng-model="momlastname"
maxlength="70" />
JavaScript
$('#momlastname').keyup(function (f) {
console.log($(this).val().length);
if ($(this).val().length == 2) {
$('#momlastname').popover({
trigger:'manual',
content:function(){
return 'Start.';
}
});
$('#momlastname').popover('show');
$('#momlastname').addClass('error');
}
else {
$('#momlastname').popover('hide');
}
});
When I take out the else part, it works but I need the else part too so that the popover is hidden when the field length is less than 2 or greater than 2.
JSFIDDLE https://jsfiddle.net/seadonk/xksfj23e/
To hide the popup when field length != 2 and show it otherwise, the following code works. See JSFIDDLE above.
$('#momlastname').keyup(function (f) {
console.log($(this).val().length);
if ($(this).val().length == 2) {
$('#momlastname').popover({
trigger:'manual',
content:function(){
return 'Start.';
}
});
$('#momlastname').popover('show');
$('#momlastname').addClass('error');
}
else {
$('#momlastname').popover('hide');
}
});

Prevent submit by disabling button until one value is selected

How can I (I guess a solution is to ) disable my submit button until at least one value is selected or typed?
<form name="forma" method="POST" action="used-results.php" id="apliforma">
lots of textboxes and dropdown menus
<a onclick="forma.submit();" class="btn btn-primary">Search</a>
</form>
You have add a listener to change event and check for values
$(document).ready(function (){
validate();
// In case of validating specific fields
$('#name, #email').change(validate);
});
function validate(e){
if ( $('#name').val().length > 0 && $('#email').val().length > 0 ) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
}
Please check this one which has the dropdown too
JSFIDDLE
$(document).ready(function (){
validate();
$('input,select').change(validate);
});
function validate(e){
var validation = true;
$('input , select').each(function(){
if($(this).val()=="")
{
validation = false;
}
});
if ( validation ) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', true);
}
}
Yes, this can be done like this.
function ready(){
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('change', function (e) {
document.getElementById('submit').disabled = e.target.value === "" }, false);
}
}
document.addEventListener( "DOMContentLoaded", ready, false )
You'll have to add the following tags to your submit button id='submit' disabled='disabled'.
Cheers.

Adding keyup events to dynamically generated elements using jquery

I have a button which creates text boxes dynamically and there is another button 'Clear'.
If there is no text in any of the text field then the clear button is disabled or else it will be enabled. It works for the text box that is created when the dom is loaded but for the dynamically created textboxes it does not work.
Here is the HTML
<input type="button" value="Click Me" class="a" />
<input type="button" value="Clear" class="a" id="clearBasicSearch" />
<div id="basicSearchFields">
<input type="text" />
</div>
Javascript
$(".a").click(function () {
$("#basicSearchFields").append("<input type='text' class='b' />");
});
/*$(".b").live("keyup", function () {
//alert('you pressed ' + $(this).val());
$(this).val($(this).val().toUpperCase());
});*/
var toValidate = $("#basicSearchFields input[type='text']");
$("#clearBasicSearch").removeClass('hidden').removeClass('button').attr('disabled', true);
toValidate.live('keyup', function () {
console.log("hi");
var valid = false; //default is false
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});
JSfiddle link - http://jsfiddle.net/TpExS/
Please help me out!!
Try this
$(document).on('keyup', "#basicSearchFields input[type='text']",function () {
console.log("hi");
var valid = false; //default is false
var toValidate = $("#basicSearchFields input[type='text']");
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
});
$(document).on('keyup', "input#basicSearchFields",function () {
// do something here
}
Here is another possible solution http://jsfiddle.net/TpExS/2/
Note: JQuery 2.0.2 used
Javascript
$(document).ready(function(){
var fields = $('input[class=b]');
for(var i = 0; i < fields.length; i++){
$(fields[i]).on('keyup', validateFields);
}
});
$(".a").click(function () {
var newField = $('<input/>').attr('type', 'text').attr('class', 'b');
$(newField).on('keyup', validateFields);
$("#basicSearchFields").append(newField);
});
function validateFields(){
if($(this).val().length){
$('#clearBasicSearch').attr('disabled', false);
return;
}
$('#clearBasicSearch').attr('disabled', true);
var fields = $('input[class=b]');
for(var i = 0; i < fields.length; i++){
if($(fields[i]).val().length){
$('#clearBasicSearch').attr('disabled', false);
return;
}
}
}
Try
$("#basicSearchFields").delegate("input[type='text']", 'keyup', function () {
validate();
});
function validate(){
console.log("hi");
var valid = false; //default is false
var toValidate = $("#basicSearchFields input[type='text']");
toValidate.each(function () {
if ($(this).val().length > 0) {
valid = true; //non-empty element found
return false; //break
}
});
$("#clearBasicSearch").attr('disabled', !valid).toggleClass('button', valid);
}
Demo: Fiddle
Simple, Updates your global "toValidate" variable when you add more elementson the click.
$(".a").click(function () {
$("#basicSearchFields").append("<input type='text' class='b' />");
toValidate = $("#basicSearchFields input:text");
});
Why? The time you set toValidate, it will return an array at that moment, you should updates it in each time there are new elements, or check for all of then inside the live event.

Categories

Resources