Textbox values are cleared after function ends (Issue): JQuery - javascript

I have below code to set fullName value, logic works but after it sets the value all the textbox values are cleared. I need overcome this issue.
<script>
$(document).ready(function() {
$('#check').click(function() {
if ( $('#city').val() == '' )
{
alert('Empty!!!');
}
else
{
$('#fullName').val("hi");
}
});
});
</script>
<form name="form1" method="post" action="">
City: <input type="text" name="city" id="city"><br>
Last name: <input type="text" name="LastName" value="Mouse"><br>
Full name: <input type="text" name="fullName" id="fullName"><br>
Phone number: <input type="text" name="Last" value="Mouse"><br>
<button id="check">Check</button>
</form>

By default a button within a form but with no type is a submit button. My guess is you are actually submitting the form when you click the button, and the inputs are 'cleared' because a new page is loading.
Try adding type="button" to your button.
<button id="check" type="button">Check</button>

Use PreventDefault() to cancel postback, becouse your button does not have type so HTML put the default behavior like submit, try:
$('#check').click(function(e) {
e.preventDefault();
if ( $('#city').val() == '' )
{
alert('Empty!!!');
}
else
{
$('#fullName').val("hi");
}
});
LIVE DEMO

Related

Why's my form action still being triggered when validating the form despite using e.preventDefault()?

I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>

Cold calling blur() function in JavaScript

I have a line
document.getElementById("firstName").addEventListener("blur", validateField);
and :
validateField = (event) =>
{
const el = event.target;
}
Now I want to call the validateField() function with the respective element in the form.addEventListener('submit', function(event) line.
document.getElementById("firstName").blur(); // This is not getting called.
But cold-calling blur() isn't working.
What I am trying to do is to populate the bootstrap is-invalid message when the form is called and still invalid.
el.classList.add('is-invalid');
el.nextElementSibling.innerHTML = "This field is required";
Trying to avoid jQuery as I may switch this over to bootstrap version 5.
I do think technically, submitting form unfocuses, unless the user presses the enter key to submit. An alternate approach is maybe, you can try to focus on something else than blurring a particular thing!
The following code works for me.
document.getElementById("frm").addEventListener('submit', function(event) {
event.preventDefault();
document.getElementById("firstName").blur();
});
<form action="" id="frm">
<input type="text" id="firstName" />
<input type="submit" value="Press Enter" />
</form>
But for the alternate solution:
document.getElementById("frm").addEventListener('submit', function(event) {
event.preventDefault();
document.getElementById("frm").focus();
});
#frm:focus {
outline: none;
box-shadow: none;
}
<form action="" id="frm" tabindex="0">
<input type="text" id="firstName" />
<input type="submit" value="Press Enter" />
</form>

Run onclick event only if Input was entered

I want to make a submit button which, once clicked on, will run a function I have made: disable() but I want to make it so it only runs the onclick event if the input above had text.
<form id="name">
<p7>Please enter a name for your plan: </p7> <input required>
<input type="submit" onclick="disable()">
</form>
So if the user typed the required input after the tags, and clicked on submit, it will run disable)
But if the user just clicks on submit without typing anything in the required input, disable() doesn't run
Thanks in advance
You can validate the input value at the beginning of the disable function, like so:
function disable() {
var myInput = document.getElementById("myInput");
if (!myInput.value.length) {
alert('empty');
return;
}
alert('fine');
}
<form id="name">
<p7>Please enter a name for your plan: </p7>
<input required id="myInput">
<input type="submit" onclick="disable()">
</form>
If you're want to use HTML5 validation, don't use click event of the button, use submit event of the form, as follows:
function disable(e) {
e.preventDefault() // Not needed, but for the snippet, for the form win't disappear
console.log('Inside disable().');
}
$('#name').submit(disable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7> <input id="input" required>
<input type="submit">
</form>
I you want to validate it inside JS, use code like the following, that determinates if there is a value inside the input field:
function disable() {
if (!$('#input').val()) {
return;
}
console.log('Inside disable().');
}
$('#button').click(disable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7> <input id="input" required>
<input type="button" id="button" value="Click Me!">
</form>
You could also disable the button itself as you don't need it when there is no input present.
You need to add disable function on input box field.
Added onkeyup event on inputbox to track changes.
disable()
function disable(){
if($("#input").val()!=""){
$("input[type=submit]").attr("disabled", false);
//your own code here!!
}
else{
$("input[type=submit]").attr("disabled", true);
return; //do nothing and return back.
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form id="name">
<p7>Please enter a name for your plan: </p7>
<input onkeyup="disable()" value="" id="input" required>
<input onclick="disable()" id="submit" type="submit">
</form>

How to check if textbox is empty and display a popup message if it is using jquery?

I'm trying to check if the textbox is empty for my form. However, whenever I try to hit submit instead of an alert box message, telling me Firstname is empty I get "Please fill out filled".
('#submit').click(function() {
if ($('#firstname').val() == '') {
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" required placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Firstly I'm assuming that the missing $ is just a typo in the question, as you state that you see the validation message appear.
The reason you're seeing the 'Please fill out this field' notification is because you've used the required attribute on the field. If you want to validate the form manually then remove that attribute. You will also need to hook to the submit event of the form, not the click of the button and prevent the form submission if the validation fails, something like this:
$('#elem').submit(function(e) {
if ($('#firstname').val().trim() == '') {
e.preventDefault();
alert('Firstname is empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="elem" autocomplete="on">
First Name:
<br>
<input type="text" name="firstname" id="firstname" placeholder="Enter the first name" pattern="[A-Za-z\-]+" maxlength="25"><br>
<input type="submit" id="submit" value="Submit" />
</form>
Personally I'd suggest you use the required attribute as it saves all of the above needless JS code - unless you need more complex logic than just checking all required fields have been given values.
Because you have the required property set.It is giving you Please fill out field validation as the error message.It is the validation that HTML5 is performing.
For this please make one function like :
function Checktext()
{
if ($('#firstname').val() == '') {
alert('Firstname is empty');
return false;
}
else
{
return true;
}
}
now call this function on submit button click like :
<input type="submit" id="submit" value="Submit" onclick="return check();" />

JQuery: How to check the value of a form field

I have a simple form, with one issue.
In explorer, if nothing is inserted, the placeholder is passed as input of the field.
Here is JSbin: http://jsbin.com/EvohEkO/1/
I would like to make a simple comparision, when form is submitted, to check if the value of the field is equal to "First name", and if yes make the value empty ""
Just this i need.
Someone can help me please?
<form onsubmit="return checkform()">
<input name="test" placeholder="placeholdertext" id="test" />
<input type="submit" value="submitbutton"/>
</form>
in js
you should import jquery latest version this is the link: http://code.jquery.com/jquery-1.10.2.min.js
function checkform(){
var fieldvalue = $.trim($('#test').val());
if(!fieldvalue || fieldvalue=="placeholdertext"){
alert('there is no input');
return false;
}else{
alert('enjoy your form!');
return true;
}
}
This is somewhat easier..
$(document).ready(function(){
$("#form").submit(function(){
$('#form input:text, textarea').each(function() {
if($(this).val()==$(this).attr('placeholder'))
$(this).val(" ");
});
});
});
Just put your field value in hidden type input like this :-
<input id="hdnfield" name="hdnfield" value="<Your Field Value>" />
To check the value of a form field use the val() function on the input element
var input_value = jQuery('Input Element Selector').val();
As I looked to your form, the elements do not have any id attribute, I recommend that you add one to each of them, also change the submit input to button the you have more control on the javascript. so your form will look like :
<form id="form" action="form.php" method="post">
<input id="fname" type="text" placeholder="First name" name="fname"><br>
<label for="fname" id="fnamelabel"></label>
<input id="lname"type="text" placeholder="Last name" name="lname"><br>
<textarea id="message" placeholder="Contact us!" cols="30" rows="5" name="message"></textarea><br>
<br>
<input type="button" value="Submit">
</form>
so your jQuery will look like:
jQuery(document).ready(function(){
jQuery('input[type="button"]').click(function(){
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
var message = jQuery('#message').val();
...... Do whatever you need & then change the input values
...... if all validation has passed the use jQuery('#form').submit(); to submit the form otherwise reset the form:
jQuery('#fname').val("");
jQuery('#lname').val("");
jQuery('#message').val("");
});
});
here is a working version:
jsfiddle working link
You can do it like the following!
<form>
<input type="text" id="first_name" name="first_name"/>
<input type="submit" id="submit" value="submit"/>
</form>
<script type="type/javascript"/>
jQuery.noConflict();
(function ($) {
$(function () {
$("#submit").click(function () {
if ($("#first_name").val() == "first name") {
$(this).val("");
}
});
});
})(jQuery);
</script>

Categories