Cannot make simple jQuery work - javascript

I'm learning jQuery, but I can't make this example work. I know it's quite simple but I don't know what I'm missing. I'm trying to add the class "invalid" in a textfield.
<script src="../jquery/jquery-1.8.2.js"></script>
<script src="../jquery/jquery.ui.effect.js"></script>
<script>
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
</main>

There is a syntax error in your Javascript. The corrected Javascript:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
});
Fiddle here: https://jsfiddle.net/s9x1Ldfm/
However I would add the return does not make a lot of sense. It returns false sometimes and void others. What exactly are you trying to do with that?

So, the problem in your code is that you are missing some closing ')' and '}'. The following will make it correct:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
} // end of for
return false;
} // end of if
}); // end of click
});
You can try to debug your javascript by using the debugger in the browser, by clicking F12. In the Element/Console section, you can see the error messages you have in your code. It will give you some hints regarding the error you have. Also, if you do not have any syntax problem, you are able to use
debugger;
In your code and when you run it in your browser with the debugger mode (F12), you can debug step by step into your code and look at the values of the variables and see how your program is behaving.
But, if in your code you just want to see if the input text is empty or not by the time the user click the button, you can try the following snippet:
<script>
$(function() {
$('#create_task').on('click', function() {
event.preventDefault(); // prevents submission
if ($('.validate').val().length > 0) {
$('.invalid').hide();
} else {
$('.invalid').show();
}// end of if
}); // end of click
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<div class="invalid" style="display:none">Invalid input</div>
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button id="create_task" class="btn" type="submit" name="createTask">Create Task</button>
</form>
</main>
Pay attention how I changed the name of button to id to detect the button without extra validation. I hope it helps.

Use event.preventDefault() to prevent the form submission.
Check out his fiddle.
Here is the snippet.
$('button.btn').click(function(event) {
event.preventDefault();
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
.invalid {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>

Your code has number of issues. First of all, if you want to capture form submission use .submit function and not click on button. Otherwise, you can remove the form tag and capture the click on button element.
Additionally, you can loop through jQuery object using .each. Using for is definitely faster as it is a native JavaScript functionality. I have made a proof of concept on this jsfiddle.
See this code.
$(function () {
$('button.btn').on('click', function () {
if ('create_task' == $(this).val()) {
$('.validate').each(function (i, e) {
if ("" == $(e).val()) {
$('.validate').addClass('invalid');
} else {
$('.validate').removeClass('invalid');
}
})
}
})
});
.invalid
{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</main>

You have a syntax error as you haven't closed the $(function(){ in your script.
Moreover move your return false to an outer block (so that you'll prevent the default submit behaviour of the button) AND, use submit (which is same as using .submit() method) event as such:
$(function() {
$('button.btn').on('submit', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
return false;
});
});
NOTE: If you wanted, you could change the type='submit' to type='button' while triggering the click event, thus ridding you of returning false in your JavaScript code.

Related

How can I disable submit form button until form is filled using jquery?

I've managed to disable the submit button but it is not re-enabling after there is text in the input field. How can I fix this?
<form>
<div class="col-lg-10 mb-3">
<div class="input-group mycustom">
<input type="text" class="form-control rounded-0" id="validationDefaultUsername" placeholder="Enter Your Name" aria-describedby="inputGroupPrepend2" required>
<div class="input-group-prepend">
<input type="submit" id="register" value="Submit" disabled="disabled" class="btn btn-secondary btn-sm rounded-0" id="inputGroupPrepend2" />
</div>
</div>
</div>
</form>
High Scores
Jquery:
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
You have multiple id's attributes in your submit button hence why you are having trouble with your code. One id is inputGroupPrepend2 and other is register - you can not have both in input
To disable the button use .prop() method and set to true if you want to disable and false when you want to enable it.
$('#register').prop('disabled', true); //disable
I have simplified your code and is working as expected.
$(function() {
$('input[type=text]').each(function(index, element) {
$(element).keyup(function() {
if ($(this).val() == '') {
$('#register').prop('disabled', true); //disable
} else {
$('#register').prop('disabled', false); //enable
}
});
})
});
Live Working Demo:
$(function() {
$('input[type=text]').each(function(index, element) {
$(element).keyup(function() {
if ($(this).val() == '') {
$('#register').prop('disabled', true); //disable
} else {
$('#register').prop('disabled', false); //enable
}
});
})
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<form>
<div class="col-lg-10 mb-3">
<div class="input-group mycustom">
<input type="text" class="form-control rounded-0" id="validationDefaultUsername" placeholder="Enter Your Name" aria-describedby="register" required>
<div class="input-group-prepend">
<input type="submit" value="Submit" disabled="disabled" class="btn btn-secondary btn-smrounded-0" id="register" />
</div>
</div>
</div>
</form>
High Scores
The > combinator selects nodes that are direct children of the first element.
Child combinator
Your keyup wasn't firing at all as well as $('form > input').each(function() { as that did not select input at al...
(function() {
$('form * input').keyup(function() {
console.log(true);
var empty = false;
$('form * input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="col-lg-10 mb-3">
<div class="input-group mycustom">
<input type="text" class="form-control rounded-0" id="validationDefaultUsername" placeholder="Enter Your Name" aria-describedby="inputGroupPrepend2" required>
<div class="input-group-prepend">
<input type="submit" id="register" value="Submit" disabled="disabled" class="btn btn-secondary btn-sm rounded-0" id="inputGroupPrepend2" />
</div>
</div>
</div>
</form>
High Scores
(function() {
$(document).on('keyup', 'input[type=text]', function(){
var empty = false;
$('input[type=text]').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
})
})()
You could update the bottom bit of code to this.
if (empty) {
if ($('#register').is(':disabled')) {
$('#register').removeAttr('disabled');
}
else {
$('#register').attr('disabled', 'disabled');
}
};

Validating user input with try and catch with jQuery

I want to validate whatever the values of the inputs are using try and catch. Every time the user gives a wrong value I want a a message to appear next to the input box that filled wrong.
The problem is that the every time it executes, the wrong message appears in both input boxes and I don't want to put many conditions. I just want to make it as simple as possible. I don't have a clue what conditions I should use.
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i]);
} //for loop
function fn(exp, str) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
alert(e);
$("#empty1").fadeIn(3000);
$("#empty1").html(e);
$("#empty1").fadeOut(3000);
$("#empty2").fadeIn(3000);
$("#empty2").html(e);
$("#empty2").fadeOut(3000);
} //try and catch
} //function
}); //button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
Name<input id="name"><span id="empty1"></span></br>
</br>
Last Name<input id="lName"><span id="empty2"></span></br>
</br>
<button id='btn'>Click</button>
</body>
</html>
For form validations, its better using Jquery validation plugin. It is very simple and needs Jquery library included in it. Try this https://jqueryvalidation.org/. Please refer this js fiddle also https://jsfiddle.net/jfc62uof/6/
<form action="javascript:void(0)" id="myform" role="form" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label><b>Password</b></label>
<input type="password" class="form-control" placeholder="Password" name="psw" id="psw">
</div>
<div class="form-group">
<label><b>Repeat Password</b></label>
<input type="password" class="form-control" placeholder="Repeat Password" name="rpsw">
<span id='message'></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="save">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<script>
$("#myform").validate({
rules: {
psw: {
required: true
},
rpsw: {
equalTo: "#psw"
}
}
});
</script>
Since you want it according to what has been asked of you to do,
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i],i+1);
} //for loop
function fn(exp, str, no) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
//alert(e);
if($('#err').length==0)
$("#empty"+no).val('').addClass('error').after('<p style="display:inline;" id="err">'+e+'</p>');
} //try and catch
} //function
}); //button
});
where error class can have css like
.error{
border: 2px solid red;
background-color: #f7b9d9;
}

Issue on Checking Multi Inputs Calculation Using each()

Can you please take a look at this Demo and let me know why I am not able to do the calculation check using the each iterator?
As you can see I tried to use :
if (!parseInt($(this).val()) === ((parseInt($(this).closest('div').find('.upper').text())) - parseInt($(this).closest('div').find('.lower').text()))) {}
Which it didnt work then I used this :
if (!parseInt($(this).val()) === ((parseInt($(this).prev('.upper').text())) - parseInt($(this).prev('.lower').text()))) {
but still not validating the input?
I'm not sure if that what you want to achieve, take a look at following example :
$('#test').on('click', function (e) {
$("input").each(function () {
if ($(this).val().length === 0)
{
$(this).addClass('input-error');
} else {
var upper = parseInt($(this).prev().prev().text());
var lower = parseInt($(this).prev().text());
var current_value = parseInt($(this).val());
if (current_value != (upper-lower)){
$(this).addClass('input-error');
}else{
$(this).removeClass('input-error');
}
}
});
});
.input-error {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="upper">5</div>
<div class="lower">2</div>
<input type="text" id="txt1">
<hr />
<div class="upper">7</div>
<div class="lower">3</div>
<input type="text" id="txt2">
<hr />
<div class="upper">200</div>
<div class="lower">66</div>
<input type="text" id="txt3">
<hr />
<br />
<button type='button' id="test">Test</button>

How to make form submission work?

When I press the register button, it doesn't submit. How can i make this work?
< script >
$(function() {
//adds the 'invalid' class if textfield is empty
$('button.btn').on('click', function(event) {
event.preventdefault();
if ('Register User' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
});
< /script>
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="Register User" name="createTask">Register</button>
</form>
I have also tried using "return false" instead of preventdefault(), still fails to submit successfully.
First of all, you need event.preventDefault() (capital D).
preventDefault stops the action the event is about to perform, which in this case would be the form submission. That's fine, because you want to validate the input, but it means you have to then trigger the form submission yourself if you want it to go through. The simplest way to do that given your current code is to check the number of .invalid fields and submit if there are none, like so:
$(function () {
//adds the 'invalid' class if textfield is empty
$('button.btn').on('click', function (event) {
event.preventDefault();
if ('Register User' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
// Submit if there are no errors
if ($('.invalid').length == 0) {
$('form').submit();
}
}
});
});

Issue on Targeting .prev() closest() Class of a Text Box

Can you please take a look at This Demo and let me know why I am not able to target the first .fa class before the text box #name ?
I am trying this:
$(this).prev().closest(".fa").addClass("err");
at this code
<div class="row">
<div class="col-md-3">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user err-test">Name</i>
</div>
<input type="text" class="form-control form-input-gray" id="name" placeholder="Enter Your Name" />
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default btn-block" id="btn-contact-rquest">Contact</button>
<br />
<div id="result"></div>
<script>
$(function () {
function txtInput(elem) {
var inputData = $.trim(elem.val());
if (inputData == "") {
$(this).prev().closest(".fa").addClass("err");
}
else{
return inputData;
}
}
$("#btn-contact-rquest").on("click", function (e) {
if (txtInput($('#name'))) {
$("#result").html("No Error");
} else {
$("#result").html("Error");
}
});
});
</script>
but cant target the .fa can you please let me know how to fix this?
Thanks,
From .closest() docs,For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree but in your case .fa is not ancestors of $('#name').
Instead of
$(this).prev().closest(".fa").addClass("err");
Try
elem.prev().children(".fa").addClass("err");
Working Demo
Try this: FIDDLE
$(elem).parent().find(".fa:eq(0)").addClass("err");
I think you miss reading the html.
Because before the input field, that is a div with class of input-group-addon.
Hence, your selector is incorrect.
I changed your JS to :
$(function () {
function txtInput(elem) {
var inputData = $(elem).val();
if (inputData != "") {
return inputData;
}
else{
$(".input-group").addClass("err");
}
}
$("#btn-contact-rquest").on("click", function (e) {
if (txtInput($('#name'))) {
$("#result").html("No Error");
} else {
$("#result").html("Error");
}
});
});
http://jsfiddle.net/fjm63j56/3/

Categories