Validate a form element without/before submitting the form with JavaScript - javascript

I have an HTML form that has its elements displayed in various Bootstrap modals. The first modal has a text box input that and a "Next" button to open the next modal. When the "next" button is pressed. I want to check if the text box is empty, and trigger a validation message. The form does not get submitted until the very end. Everything I've tried has not worked so far.
Javascript/jQuery code
$("#add_assistant_next").click(function () {
var textInput = document.getElementById('add_assistant_user');
var text = textInput.value;
if (text === "") {
textInput.setCustomValidity('Please fill out this field.');
textInput.checkValidity();
var form = $('#form_add_assistant');
form.find(':submit').click();
} else {
textInput.setCustomValidity('');
}
});
HTML
<form name="add_assistant" method="post" id="form_add_assistant">
<div class="modal-body">
<div class="step">
<span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
</div>
<div class="pl-3 pt-1">
<div>
<input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
<button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
</div>
<input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
</div>
</div>
... form continues in other modals

Your JS code is probably fighting with Bootstrap for control of that button. To get around that, and have your validation, you could try modifying your code to have a middle step / temporary button to help with validation first before actually submitting. So something like this:
Javascript/jQuery code
$("#my_temp_button").click(function () {
var textInput = document.getElementById('add_assistant_user');
var text = textInput.value;
// Might also want to handle null and undefined cases?
if (text === "" || text === undefined || text === null) {
// I'm assuming if it's empty, it doesn't pass validation,
// so we just display this warning and wait for the user to fix it:
textInput.setCustomValidity('Please fill out this field.');
} else {
// it's not empty so validate:
if (textInput.checkValidity()) {
// it passed validation, so ok to submit.
// call the real button:
$('#add_assistant_next').click();
// do you need this?
var form = $('#form_add_assistant');
form.find(':submit').click();
} else {
// it failed validation, so display another error?
textInput.setCustomValidity('Try again.');
}
}
});
HTML:
<form name="add_assistant" method="post" id="form_add_assistant">
<div class="modal-body">
<div class="step">
<span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
</div>
<div class="pl-3 pt-1">
<div>
<input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
<!-- Feel free to change the id name. This is the button the user sees. It's only purpose is to give your function above full control to it and prevent Bootstrap from touching it and jumping to the next modal without having the user fix the validation failure first: -->
<button type="button" id="my_temp_button" class="btn btn-outline-secondary btn">Look up user</button>
<!-- Hide the real button from the user: -->
<div style="display:none">
<button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
</div>
</div>
<input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
</div>
</div>
...

Have you tried adding a trap for the submit event itself?
$('#form_add_assistant').submit(function(evt){
//do your validation here
if (validation fails){
return false; // OR, alternatively, `evt.preventDefault()`
}
//form submission will continue if not returned false
});
References:
https://api.jquery.com/submit/
How to conduct manual form validation via jQuery .submit()

Related

How Can I Get Values from Dialog in HTML and JavaScript, and Display it in PHP page

I have a HTML form that contains dialog, and the dialog contains inputs
When user complete dialog inputs and click send, the values appear in the same page of form in divusing JavaScript.
Then, when user complete other fields in form and click submit, user goes to another php page than contains entered values of all fields.
I want to get the values of dialog to php page
My form code:
<form id="form" action="message.php" method="POST" >
<div class="container" id="executive-bodies-information">
<!-- details-of-partners Dialog -->
<dialog id="details-of-partners">
<h2>بيانات الشركاء ، الملاك المستفيدون النهائيون ، المالكين المستفيدين</h2>
<label for="details-of-partners-name">الاسم</label>
<input type="text" id="details-of-partners-name"
name="details-of-partners-name" placeholder="الاسم" >
<label for="details-of-partners-date-of-expiry">تاريخ الانتهاء</label>
<input type="date" id="details-of-partners-date-of-expiry"
name="details-of-partners-date-of-expiry" placeholder="تاريخ الانتهاء">
<button button type="button" id="details-of-partners-send" >إرسال</button>
<button button type="button" id="details-of-partners-cancel"
onclick="closeDialog('details-of-partners')">إلغاء</button>
</dialog>
<!-- END details-of-partners Dialog -->
<div>
<button class="btn-add" type="button" onclick="showDialog('details-of-partners')">+ جديد</button>
<div id="details-of-partners-container"></div>
</div>
</div>
<label for="preferred-language">اللغة المفضلة</label>
<select name="preferred-language" id="preferred-language" required>
<option value="" disabled selected>اختر</option>
<option value="english">الانجليزية</option>
<option value="arabic">العربية</option>
</select>
<div class="center">
<button type="submit" id="submit"><h1>إرسـال</h1></button>
</div>
</form>
This button is clicked to show dialog:
This is the dialog:
Here is the result of dialog, while user enter new dialog with new values, a div is added with these new valaues in form page:
My JavaScript code to enable values to display in form page:
<script>
function showDialog(id) {
var dialog= document.getElementById(id);
dialog.show();
}
function closeDialog(id){
var dialog= document.getElementById(id);
dialog.close()
}
document.getElementById("details-of-partners-send").addEventListener('click', function(){
var name= document.getElementById("details-of-partners-name").value;
var date_of_expiry= document.getElementById("details-of-partners-date-of-expiry").value;
document.getElementById("details-of-partners-container").innerHTML+=
`
<div class="border" >
<div class="details-box">
<span>الاسم:  </span>
<span>${ name}</span>
</div>
<div class="details-box">
<span>تاريخ الانتهاء:  </span>
<span> ${date_of_expiry}</span>
</div>
</div>
`;
closeDialog("details-of-partners");
})
</script>
An example of another code in message.php where I collect all values of form and echo values in it:
<span for="preferred-language">اللغة المفضلة: </span>
<span><?php
if(isset($_POST['preferred-language'])){
$lang= $_POST['preferred-language'];
if($lang=="english"){
echo "الانجليزية";
}else{
echo "العربية";
}
}
?> </span>
It will look like this:
And this is What I need, collect value from dialog using Javascript, then appears these values of div in php page
Sorry for taking long time to explain it in details
i suggest adding a hidden input where you can store the values from the dialogue so they can be submitted with the form, and since there can be multiple dialogues, you need an increment variable.
Before submit button : <input type="hidden" name="increment" id="increment" />
Outside of the onclick event: var incrm = 1
document.getElementById("details-of-partners-container").innerHTML+=
...
<input type="hidden" name="name${incrm}" value="${name}" /> //close .innerHTML
document.getElementById("increment").value = incrm;
incrm++;

jQuery input element with id selection using id selector

I am using JQuery 3.6 and I'm trying to create a simple email registration snippet on a page.
I am surprised that when I type an email in the input, and click the button, the alert box shows a blank. I get the same result when I use Code Inspector. The element is identified and selected correctly, but for some reason, I can't seem to extract the email value entered in the input box.
Here is my markup and minimal Javascript:
<div class="g-mb-30">
<div class="input-group border-0 rounded">
<input id="newsletter-subscription-email" class="form-control border-0 g-pa-12" type="email" title="Subscribe to our newsletter!" placeholder="Email address">
<div class="input-group-append p-0">
<button id="newsletter-subscribe" class="btn btn-primary" type="submit" role="button">Subscribe</button>
</div>
</div>
</div>
<script type="text/javascript">
function isValidEmail(some_email){
/* impl detail */
}
$().ready(function(){
$('#newsletter-subscribe').on('click', function(e){
let email = $('#newsletter-subscription-email').val().trim().toLowerCase();
alert(email); // displays blank if even I type an email address
if (email.length && isValidEmail(email)) {
e.preventDefault();
// some logic ...
}
}
});
</script>
Why is the address not being correctly retrieved - since the selector CSS is correct - and how do I fix this to correctly retrieve the entered email?
I faced the same thing with you months ago.
At last, I found that there were two controls with the same ID, jquery always choose the first one with the ID
your code is perfect, please check is there are more than one input with that ID attr
Probably the $()ready(function(){ and also a missing }); in the js.
$(function() {
$('#newsletter-subscribe').on('click', function(e){
let email = $('#newsletter-subscription-email').val().trim().toLowerCase();
alert(email); // displays blank if even I type an email address
if (email.length && isValidEmail(email)) {
e.preventDefault();
// some logic ...
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="g-mb-30">
<div class="input-group border-0 rounded">
<input id="newsletter-subscription-email" class="form-control border-0 g-pa-12" type="email" title="Subscribe to our newsletter!" placeholder="Email address">
<div class="input-group-append p-0">
<button id="newsletter-subscribe" class="btn btn-primary" type="submit" role="button">Subscribe</button>
</div>
</div>
</div>

How To Disable Button by Using Javascript

I trying to write a booking appointments for my website. But i have something need to help from you.
this is my HTML for field to input:
<div class="form-group second_box">
<form id="submit" style="display:inline-block" method="post">
<label for="submit" class="control-label">
<?= lang('submit') ?> *</label>
<input type="number" name='otp' id="otp" class="required form-control" placeholder="write your code here" required="required" >
<span id="otp_error" class="field_error"></span>
</div>
this is my HTML button:
<button type="button" id="button-next-3" class="btn button-next btn-primary" onsubmit="submit_otp()"
data-step_index="3"<?= lang('next') ?>
<span class="glyphicon glyphicon-forward"></span>
</button>
and this is my Jacascript from another file:
function submit_otp(){
$('#wizard-frame-3 .has-error').removeClass('has-error');
$('#wizard-frame-3 label.text-danger').removeClass('text-danger');
var otp=jQuery('#otp').val();
jQuery.ajax({
url:'../../../Code_Verification/check_otp.php',
type:'post',
data:'otp='+otp,
success:function(result){
if(result=='yesFalse'){
jQuery('#otp_error').html('Please enter your valid code');
}
if(result=='yesTrue'){
jQuery('#otp').html('Your code is correct');
}
if(result=='not_exist'){
jQuery('#otp_error').html('Please enter valid otp');
}
}
});
}
--> I using php in check_otp.php to connect with my database to comparing the value return. if the input in the second_box equal with the value i saved in the database that's mean the customer can go to next step. if they give input wrong with the value in database that's mean they cannot continue. but i don't know how to give it's logic together.
and this is the next button call in javascript file:
$('.button-next').click(function (){
if ($(this).attr('data-step_index') === '3') {
if (!_validateCustomerForm()) {
return; // Validation failed, do not continue.
}
}
--> thanks all for help.
Since you're using jQuery, you can try
$("#button-next-3").attr("disabled", true);
Use .attr() to set disable attribute
Usage $(selector).attr("disabled", true)
In your case : $("#button-next-3").attr("disabled", true)
function myButton() {
document.getElementById("myBtn").disabled = true;
}
<html>
<body>
<button id="myBtn">My Button</button>
<p>Click the button below to disable the button above.</p>
<button onclick="myButton()">Try it</button>
</body>
</html>

Skip Validation on cancel button in AngularJS

I try to achieve the following functionality. Have editable form inputs in an angular application. For example a user can see his first name being fetched by the server and then clicking an edit button the form text input appears, edit button disappears and in its place the buttons save and cancel appear. I use the angular-bootstrap-show-errors component to show errors.
However when a validation rule is not fulfilled during editing and I click on cancel button the form tries to show the error before going back to the starting state. For example, I press edit and delete all the first name characters, then press cancel, so before disappearing it tries to validate. Below is my view.
<!--First name edits-->
<div class="row">
<form name="firstNameEditForm" role="form" novalidate>
<div class="col-xs-3">
<p class="text-right">First Name:</p>
</div>
<div class="col-xs-6" ng-if="model.beforeFirstNameEdit">
<p class="text-success">
{{accountData.firstname || "Loading..."}}
</p>
</div>
<div class="col-xs-6" ng-if="!model.beforeFirstNameEdit">
<div class="form-group" show-errors>
<input name="firstName" ng-model="accountData.firstname" class="form-control" placeholder="First Name" type="text" required minlength=2 auto-focus />
<small class="help-block" ng-if="firstNameEditForm.firstName.$error.required">At least 2 characters required</small>
<small class="help-block" ng-if="firstNameEditForm.firstName.$error.minlength">At least 2 characters required</small>
</div>
</div>
<div class="col-xs-3" ng-if="model.beforeFirstNameEdit">
<button type="button" class="btn btn-warning btn-xs" ng-click="editFirstName()">Edit</button>
</div>
<div class="col-xs-3" ng-if="!model.beforeFirstNameEdit">
<button type="button" class="btn btn-success btn-xs" ng-click="update(accountData.firstname)">Save</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="cancelFirstNameEdit()">Cancel</button>
</div>
</form>
</div><!--First name edits-->
And the controller
$scope.preFirstNameEditModel = {};
$scope.editFirstName = function() {
// Copy preedited data locally
$scope.model.beforeFirstNameEdit = false;
$scope.preFirstNameEditModel = angular.copy($scope.accountData.firstname);
}
$scope.cancelFirstNameEdit = function(){
$scope.model.beforeFirstNameEdit = true;
$scope.accountData.firstname = angular.copy($scope.preFirstNameEditModel);
};
How can I completely avoid validation when I click on cancel button? I read some answers on similar questions suggesting to change the type of button to type = "button" but still doesn't solve my issue.
The validation of the fields is triggered on focus lost, whichis causing the validation message. You can prevent this behaviour by using ng-show="submitted && firstNameEditForm.firstName.$error.required" and ng-show="submitted && firstNameEditForm.firstName.$error.minlength". This causes the message showing up only when the form is submitted.
Furthermore you have to change the type of the update button to submit.

required attribute on textbox in html doesn't work

I have a popover with a form inside. And It is already out and ready for submission, here is the code for the popover
<div id="popover-head" class="hide">Add new subject</div>
<div id="popover-content" class="hide">
<form class="form-inline" id="pop-form" method="POST" action="../admin/module_add_subject.do">
<div class="form-group">
<!-- This input is what i'm talking about -->
<input type="text" name="subjectName" id="subject-name" required="required" pattern="^[\S\s]{3,25}[A-z]+$" title="Only accept alphabet characters and length is minimum of 3 and max of 25 " placeholder="Subject name.."/>
<button class="btn btn-primary" type="button" id="add-subject" ><i class="icon-white icon-ok"></i></button>
</div>
<p></p>
<p style="color:red" id="error-message"></p>
</form>
</div>
The input above I'm sure the regex is working. When I change the button to submitthe required is working perfectly fine but when I change it back to button then it is not working again.
The reason why my submit button is a type="button" because of this code:
$(document).on('click', '#add-subject', function(e) {
$.post('../admin/module_check_subject.do', { subjectName: $('#subject-name').val() },
function( data ) {
// if data from the database is empty string
if( $.trim( data ).length != 0 ) {
// hide pop-over
$('#popover').popover('hide');
// submit form
$('#pop-form').submit();
} else {
$('#error-message').text('Subject already exist.' );
}
}
})
.fail( function () {
bootbox.alert('Failed to check, please try again later.');
});
});
What I'm doing is on submit i'll check out first in my database if the input text in the textbox exist in the database, then if the text exist the database stop the submission of the form and display error at the p tag
By the form submission algorithm, validation is not performed when a form is submitted using the submit() method. The idea is, more or less, that when you submit a form with a script, your script should also carry out any checks deemed necessary.
Within your script, you can call the checkValidity() method to carry out the normal validation that would be performed if the form were submitted with a submit button. Note that it performs static validation only.

Categories