jQuery Counter Not Working - javascript

JavaScript/jQuery newbie here!
I have the following form here (using bootstrap's disabled class, heads up):
EDIT: the class 'disabled' is a thing in bootstrap, and does properly disable and enable the button if it is there or not.
<form action="" method="post">
<input type="text" id="bio">
<p class="bio-counter"></p>
<input type="text" id="username">
<p class="user-counter"></p>
<input type="submit" class="btn">
</form>
And the following script (I have included jQuery in my head tag correctly):
var main = function() {
$('.bio-counter').text('500');
$('.user-counter').text('0');
var postLengthUser = $('#username').val().length;
var postLengthBio = $('#bio').val().length;
$('#username').keyup(function() {
$('.user-counter').text(postLengthUser);
});
$('#bio').keyup(function() {
var charactersLeftBio = 500 - postLengthBio;
$('.bio-counter').text(charactersLeftBio);
});
if(postLengthUser > 6 && postLengthUser < 21) {
if(postLengthBio >= 0 && postLengthBio < 501) {
$('.btn').removeClass('disabled');
} else {
$('.btn').addClass('disabled');
}
} else {
$('.btn').addClass('disabled');
}
}
$(document).ready(main);
I am running into the following problems:
The 'btn' is not losing it's disabled state, even when I type enough information in the inputs.
The counters are not updating.
What am I doing wrong?

<script>
var main = function () {
var postLengthUser = 0;
var postLengthBio = 0;
$('.bio-counter').text(500);
$('.user-counter').text(0);
var validate = function () {
if (postLengthUser > 6 && postLengthUser < 21) {
if (postLengthBio >= 0 && postLengthBio < 501) {
$('.btn').removeClass('disabled');
} else {
$('.btn').addClass('disabled');
}
} else {
$('.btn').addClass('disabled');
}
}
$('#username').keyup(function () {
postLengthUser = $('#username').val().length;
$('.user-counter').text(postLengthUser);
validate();
});
$('#bio').keyup(function () {
postLengthBio = $('#bio').val().length;
var charactersLeftBio = 500 - postLengthBio;
$('.bio-counter').text(charactersLeftBio);
validate();
});
validate();
}
$(document).ready(main);
</script>
You're validating the disabled condition only at page load, it should be run at each keyup event - i moved it to validate function.
postLengthUser and postLengthBio were updated only at page load too. They should be updated on each key up event too.

Try using:
$('.btn').prop('disabled', true);
and
$('.btn').prop('disabled', false);
instead.

Related

Trigger the counter function on page load

I am using keyup function to calculate the number of words and characters. The function is working fine but when the page loads, initially it does not calculate the default values within the textarea and when any key is pressed then it works fine. I need to trigger the function on page load and calculate the default string This is default text. Here is my code below:
<p> Words <span id="count1">0</span></p>
<p>Characters <span id="count2">0</span></p>
<textarea rows="5" id="mycounter">This is default text</textarea>
<script>
$(document).ready(function () {
$("#mycounter").on("keyup", function () {
var wcounts = 0;
var ccounts = 0;
if ((this.value.match(/\S+/g)) != null) {
wcounts = this.value.match(/\S+/g).length;
}
if ((this.value.match(/\S+/g)) != null) {
ccounts = this.value.length;
}
$('#count1').text(wcounts);
$('#count2').text(ccounts);
});
});
Thanks in advance.
You can use trigger to do it
$(document).ready(function () {
$("#mycounter").on("keyup", function () {
var wcounts = 0;
var ccounts = 0;
if ((this.value.match(/\S+/g)) != null) {
wcounts = this.value.match(/\S+/g).length;
}
if ((this.value.match(/\S+/g)) != null) {
ccounts = this.value.length;
}
$('#count1').text(wcounts);
$('#count2').text(ccounts);
});
$("#mycounter").trigger('keyup');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> Words <span id="count1">0</span></p>
<p>Characters <span id="count2">0</span></p>
<textarea rows="5" id="mycounter">This is default text</textarea>

Error with <input> triggerWord and Javascript

I want to load the page http://example.com by typing trigger in the <input> text box. I made some modifications over time, and at some point it seemed to work but now it doesn't.
How can I make this work? What are some errors that I am missing?
window.onload = function() {
var input = document.getElementById("idname").focus();
}
$(function() {
var triggerWords = ['trigger'];
$('#indexinput').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
You are registering on keyup two times, following code will work. Dont need to register it with javascript if you are mentioning it inline HTML.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
<script>
window.onload = function() {
var input = document.getElementById("idname").focus();
}
function myFunction(event) {
var triggerWords = ['trigger'];
for (let i = 0; i < triggerWords.length; i++) {
if (event.target.value == triggerWords[i]) {
window.open("http://example.com/", "_self");
break;
}
}
}
</script>
You have the wrong id in the query selector. It says
$('#indexinput') but must be $('#idname').
Consider using the following snippet:
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
console.log('open new page');
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>
Note that the window.open doesn't work in code-snippets, therefore I added the console.log part.
I also removed this unnecessary part:
window.onload = function() {
var input = document.getElementById("idname").focus();
}
There is no need of myFunction and id was incorrect
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() === triggerWords[i]) {
window.open("https://google.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>

JQuery Validated Form Not Submitting

I have a form that I am using on my site and it is validated with some simple JQuery validation. Problem is it's not submitting or doing anything really when I change the values. Here is my code:
<form id="radForm" method="post" action="events.php?type=rad">
<div class="searchBoxLeft searchBoxRad"></div>
<div class="searchBoxMiddle">
<input id="radSearch" type="text" class="searchBoxInput searchBoxShort" value="<?php echo $yourradius; ?>" />
<label class="searchBoxLabel">Mile Radius of Your Address</label>
</div>
<div id="radButton" class="searchBoxRight"></div>
<div class="clearLeft"></div>
</form>
<script>
$(document).ready(function()
{
var radsearchok = 0;
//Rad search
$('#radSearch').blur(function()
{
var radsearch=$("#radSearch").val();
if(radsearch < 2){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else if(radsearch > 50){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else{
$('#radSearch').addClass("searchSuccess");
radsearchok = 1;
}
});
// Submit button action
$('#radButton').click(function()
{
if(radsearchok == 1)
{
$("#radForm").submit();
}
else
{
$('#radSearch').addClass("searchError");
}
return false;
});
//End
});
</script>
Can anyone see what is wrong with this?
You need to go back and set the .val() property again of your form, otherwise it will take the original value of .val() not radsearch;
Not sure if you actually want to update .val() though or just attach a property. Some options:
Right before the closing brace of .blur --> }); add"
$("#radSearch").val(radsearch);
Or:
Add a hidden input to your form with a new ID like:
<input type='hidden' name='radsearchHidden' />
and then do the same before the end of .blur:
$("#radsearchHidden").val(radsearch);
I made some changes to your code (http://jsfiddle.net/zdeZ2/2/) which I'll describe below:
<div id="radButton" class="searchBoxRight"></div> I assume you have something in there=> <input id="radButton" class="searchBoxRight" type="button" value="rad button">
I rewrote your validator with blur as follows. As suggested it coroses the radSearch value to an integer before comparisions The changes remove the searchError and searchSuccess classes before validating. I also made some optimizations for you.
//Rad search
$('#radSearch').blur(function () {
//remove classes from previous validating
var $this = $(this).removeClass("searchError").removeClass("searchSuccess");
var radsearch = $this.val() | 0; //radsearch is an integer
if (radsearch < 2 || radsearch > 50) {
$this.addClass("searchError");
radsearchok = 0;
} else {
$this.addClass("searchSuccess");
radsearchok = 1;
}
});
Can be equivalently written as:
//Rad search
$('#radSearch').blur(function () {
var $this = $(this);
var radsearch = $("#radSearch").val() | 0; //radsearch is an integer
var valid = radsearch < 2 || radsearch > 50;
$this.toggleClass("searchError", !valid)
.toggleClass("searchSuccess", valid);
radsearchchok = valid ? 1 : 0;
});

Validating HTML input elements inside a DIV (visible wizard step) which is inside a FORM?

I have decided to create a wizard form in HTML 5 (actually using ASP.NET MVC here). I have the following HTML form:
#using (Html.BeginForm())
{
<div class="wizard-step">
<input type="text" name="firstname" placeholder="first name" />
</div>
<div class="wizard-step">
<input type="text" name="lastname" placeholder="last name" />
</div>
<div class="wizard-step">
<input type="text" name="suffix" placeholder="suffix" />
</div>
<button class="back-button" type="button">
Back</button>
<button class="next-button" type="button">
Next</button>
}
Then I have this js script:
<script type="text/javascript">
$(document).ready(function () {
var $steps = $(".wizard-step");
var index = 0;
var count = $steps.length;
$steps.each(function () {
$(this).hide();
});
$(".back-button").attr("disabled", "disabled");
var $currentStep = $steps.first();
$currentStep.show();
$currentStep.addClass("current-step");
$(".back-button").click(function () {
$currentStep.hide();
$currentStep.removeClass("current-step");
$currentStep = $currentStep.prev();
$currentStep.addClass("current-step");
$currentStep.show();
index--;
$(".next-button").removeAttr("disabled");
if (index == 0) {
$(this).attr("disabled", "disabled");
}
else {
$(this).removeAttr("disabled");
}
});
$(".next-button").click(function () {
var $inputFields = $(".current-step :input");
var hasError = false;
$inputFields.each(function () {
if (!validator.element(this)) {
hasError = true;
}
});
if (hasError)
return false;
index++;
$(".back-button").removeAttr("disabled");
if (index == count - 1) {
$(this).attr("disabled", "disabled");
}
else {
$(this).removeAttr("disabled");
}
$currentStep.hide();
$currentStep.removeClass("current-step");
$currentStep = $currentStep.next();
$currentStep.addClass("current-step");
$currentStep.show();
});
});
</script>
Basically, what I want is upon clicking the Next button, it will validate the input elements found inside the current visible DIV, not the entire FORM. Is it possible to do this using HTML5? If not, maybe jQuery?
If you have others in mind, please do share it here. Many many thanks!
after some playing with the jquery i happened to find the solution despite of lack of samples and tutorials in validation. inside the $(".next-button").click() block, i made these changes:
old:
var hasError = false;
$inputFields.each(function () {
if (!validator.element(this)) {
hasError = true;
}
});
if (hasError)
return false;
new:
var isValid = false;
$inputFields.each(function () {
isValid = $(this).valid();
});
if (!isValid)
return false;
======================
i could also add this right under the $(document).ready() line to use/add jquery validation rules:
$("#myForm").validate({
rules: {
lastname: "required"
}
});

input box not working in firefox

I am trying to have a basic filter when someone puts a word into a input box and list items hide on click, this is working fine in chrome but in firefox it is not working at all.
html:
<form ACTION="#" id="navsform" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search...">
<input type="submit" class="my-button" value="Search" onclick="query_searchvar()"></form>
javascript:
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
if (found == true )
{
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
Any help much appreciated. Thank you.
Hi, I managed to get this working with a combo of all your comments and some jquery resources:
HTML:
<form id="myform" action="#" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search..." />
<input class="my-button" type="submit" value="Search" />
</form>
$('#myform').submit(function() {
var searchquery = String($('#myform input[name=query]').val()).toLowerCase();
if (searchquery == '') {
alert('No Text Entered');
}
var queryarray = searchquery.split(/,|\s+/);
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
var searcharray = searchtags.split(',');
var found = false;
for (var i = 0; i < searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray) > -1) {
found = true;
break;
}
if (found == true) {
$(this).show('normal');
}
else {
$(this).hide('normal');
}
});
return false;
});
document.navsform.query.value ???
onclick="query_searchvar()" ???
event.preventDefault ??? -- lack crossbrowser
Why Use click rather than submit?
missing return false?
why use it?
You're already using jQuery, it would be better to work 100% with Jquery?
<form ACTION="#" id="navsform" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search...">
<input type="submit" class="my-button" value="Search"></form>
Javascript:
$(document).ready(function(){
$("#navsform").submit(function(event){
event = event||window.event; //Cross
var searchquery=String($("#navsform input[name=query]").val()).toLowerCase();
if(searchquery == ''){
alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function(){
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++){
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
}
if (found == true ){
$(this).show("normal");
} else {
$(this).hide("normal");
}
});
});
return false;//prevents sending the form, remove if necessary.
});
There are a few things, you should change:
Pass in the event object to the handler function.
Attach the eventhandler to the form submit event, not the button. This way the return key will work.
Then you should use a tool like Firebug, Dragonfly or similar. It helps a lot. As mentioned in the comments, you could have found your error.
See Guilherme Nascimento's answer for an example. (But ignore the tone..)

Categories

Resources