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>
Related
i'm trying to store a user input from a form and then use that variable on a different page.
It seems like it should be very simple but im getting absolutely nothing back and i cant work out why.
Code on page 1:
<div class="container-fluid d-flex justify-content-center" id="mySearchBar">
<div class="row d-flex justify-content-center ">
<h3 class="heading text-center pt-5">Search the Title Below and Find The Site It's Hosted On!</h3>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search this blog" id="searchbar" name="searchbar ">
<script> localStorage.setItem('loan', document.getElementById("searchbar").value );</script>
<div class="input-group-append">
<button class="btn btn-secondary" id='searchButton' type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
Then on page two i have the following:
<script>
var loan = localStorage.getItem('searchbar');
console.log(loan);
</script>
Any help would be appreciated!
In order to fetch a value entered by the user you must do so after they enter the value. You need to use an event listener to fetch and store the value. For your use-case it would be best to wrap your inputs in a <form> and listen for the form submit. That way you capture the submit button's click and/or the input's enter key press.
You are using bootstrap-4 so I will assume you have jQuery imported as well.
<form class="container-fluid d-flex justify-content-center" id="mySearchBar">
<div class="row d-flex justify-content-center ">
<h3 class="heading text-center pt-5">Search the Title Below and Find The Site It's Hosted On!</h3>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search this blog" id="searchbar" name="searchbar">
<div class="input-group-append">
<button class="btn btn-secondary" id='searchButton' type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</form>
<script>
// use a constant key string on both pages
const searchbar_local_storage_key = 'my_unique_key_for_searchbar_value'
// on page where you need to fetch stored value
$(document).ready(function() {
let stored_value = localStorage.getItem(searchbar_local_storage_key)
console.log('searchbar localStorage value at document.ready:')
console.log(stored_value)
})
// on page where you need store/overwrite the value
$(document).ready(function() {
let $searchbar = $('#searchbar')
console.log('searchbar input value at document.ready:')
console.log($searchbar.val())
$('#mySearchBar').on('submit', function(event) {
console.log('searchbar form submitted')
// stop form submission if needed
event.preventDefault()
// get the current value
let term = $searchbar.val()
console.log('searchbar input value at form.submit:')
console.log($searchbar.val())
// store values
localStorage.setItem(searchbar_local_storage_key, $searchbar.val());
console.log('new searchbar value in localStorage:')
console.log(localStorage.getItem(searchbar_local_storage_key))
})
})
</script>
See it in action here https://jsfiddle.net/chan_omega/qt510oms/
Enter a value, submit, view the output in the console and then reload the page (to simulate being on a different page). You will see the same value loaded from localStorage.
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()
I've written some jQuery to validate my Bootstrap forms, however I'm having a few issues.
Firstly, I want a red outline to appear if the user clicks off the input field without typing anything in: JSFiddle example here. In this example I'm using the Bootstrap Validator plugin, however I want to imitate this effect without using the plugin.
Second, and linked to the issue I just mentioned, the green outline only appears once the user clicks the submit button, thus the user only sees it for half a second or so before they are redirected, making it a little pointless. Again, this would be solved by having an error/success outline appear once the user clicks off the input. If anyone could help me out it would be greatly appreciated.
This is the code I have so far:
HTML:
<form id="auth_form" action="action.php" method="post">
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<label for="auth_code" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input" name="auth_code_input" type="password">
<span class="form-control-feedback glyphicon" id="iconBad"></span>
</div>
<div class="form-group">
<div>
<button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#auth_form').on('submit', function(e) {
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
e.preventDefault();
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
})
})
JSFiddle
Try this updated fiddle: jsfiddle.net/xqwsobmo/20/
Need to add input blur event and validate input
$(document).ready(function() {
$('#auth_code_input').blur(function(){
if(!ValidateInput()){
e.preventDefault();
}
});
$('#auth_form').on('submit', function(e) {
if(!ValidateInput()){
e.preventDefault();
}
})
});
function ValidateInput(){
var IsValid=false;
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid=false;
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid=true;
}
return IsValid;
}
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.
I'm using Bootstrap v3.3.5 in my website.
In one scenario I'm displaying a form in Bootstrap modal dialog. User fills in the data and submits the form. After submitting the form the form looks as it is until the response is received from the server.
So, what I want to do is display a blue colored horizontal progress bar exactly resembling the blue colored horizontal progress bar which gmail uses when it loads the inbox mail list after login. This progress bar should be dynamic like gmail's progress bar(i.e. progressive in nature and not like revolving circle loader image).
It should be displayed at the top of form with the message "Please wait...your event is being generated." I've added a comment in my code telling where it should be displayed exactly.
Following is my Bootstrap modal's HTML code:
<form method="post" action="{$site_url}add_event.php" id="formAddEvent" >
<!-- The gmail look alike loader should display here only upon successfull submission of a form. -->
<div class="form-group" id="addEventErrorMsg" style="display:none; color:#FF0000;">
</div>
<div class="form-group">
<input type="text" name="txt_event_title" id="txt_event_title" autocomplete="off" class="form-control custom-height" placeholder="Event Title" style="height:30px;" />
</div>
<div class="form-group">
<textarea type="text" name="txt_event_description" id="txt_event_description" autocomplete="off" class="form-control custom-height" placeholder="Description (optional)" style="height:60px;" ></textarea>
</div>
<table border="0" cellspacing="10">
<tr>
<th><span class="event-title1" style="margin-bottom:5px;">Start Date:</span></th>
<th><span class="event-title1" style="margin-bottom:5px;">End Date:</span></th>
</tr>
<tr>
<td>
<div style="margin-right:15px;" class="form-inline form-group event-selection">
<div class="form-group has-feedback">
<div class='input-append date form_datetime' data-date="2013-02-21T15:25:00Z">
<input type='text' id='event_start_date' name="event_start_date" style="width:225px; display:inline; height:30px;" class="form-control" autocomplete="off" />
<span aria-hidden="true" class="glyphicon glyphicon-calendar form-control-feedback"></span>
</div>
</div>
</div>
</td>
<td>
<div class="form-inline form-group event-selection">
<div class="form-group has-feedback">
<div class='input-append date form_datetime' data-date="2013-02-21T15:25:00Z">
<input type='text' id='event_end_date' name="event_end_date" style="width:225px; display:inline;height:30px;" class="form-control" autocomplete="off" />
<span aria-hidden="true" class="glyphicon glyphicon-calendar form-control-feedback"></span>
</div>
</div>
</div>
</td>
</tr>
</table>
<div class="form-group has-feedback">
<input type="text" name="txt_event_location" id="txt_event_location" autocomplete="off" class="controls form-control custom-height" placeholder="Event Location" style="height:30px;" />
<span class="glyphicon glyphicon-map-marker form-control-feedback" aria-hidden="true"></span>
</div>
<div style="clear:both;"> </div>
<div id="map"></div>
<div class="form-group">
<input type="text" name="txt_event_room" id="txt_event_room" autocomplete="off" class="form-control custom-height" placeholder="Room No." style="height:30px;" />
</div>
<div class="form-group">
<div id="custom-templates">
<input class="typeahead form-control custom-height" id="selected_groupname" name="selected_groupname" type="text" placeholder="Invite Group" value="{foreach from=$user_group_list1 item=grouplist key=key} {if $groupId==$grouplist.page_id} {$grouplist.title} {/if} {/foreach}">
<input type="hidden" name="selected_groupid" id="selected_groupid" value="" />
</div>
</div>
<div class="modal-footer text-center">
<button class="btn btn-primary" id="btn_add_event" type="button">Add Event</button>
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
</div>
</form>
The function which gets called for form submission upon clicking on button with id btn_add_event is as follows:
$(document).ready(function() {
$("#btn_add_event").click(function() {
var strSeriaze = $( "#formAddEvent" ).serialize();
url = $( "#formAddEvent" ).attr('action');
$("#btn_add_event").attr('disabled', 'disabled');
$("#addEventErrorMsg").html('');
$.ajax({
url : url,
type : "POST",
data : {postData:strSeriaze},
beforeSend: function() {
$('#loader-icon').show();
},
complete : function() {
$('#loader-icon').hide();
},
success : function(data) {
// $("#events-result").append(data);
$('#loader-icon').hide();
if(data == true) {
$("#myModal-add-event").modal('hide');
$("#myModal-add-event").hide();
//window.location = site_url + "event_index.php";
window.location.href = site_url + "event_index.php";
return false;
} else {
$("#btn_add_event").attr('disabled', false);
$("#addEventErrorMsg").show();
$("#addEventErrorMsg").html(data);
}
},
error: function() {}
});
})
});
Please help me. Thanks.
My question is different than any other question. I don't know how to work the progress bar percentage or progress with the response time. I'm not getting solution for it from anywhere. Please remove the tag of duplicate from my question.
My question is different than any other question. I don't know how to
work the progress bar percentage or progress with the response time.
I'm not getting solution for it from anywhere. Please remove the tag
of duplicate from my question.
No it's not different, and therefore it is duplicate of
show progressbar while loading pages using jquery ajax in single page website
The only difference is that in your bounty notice you said
This question had a bounty worth +50 reputation from user2839497.
The question is widely applicable to a large audience. A detailed
canonical answer is required to address all the concerns.
I want a canonical answer for this question. I want a working demo of
a code which must be integrated with the code I posted in the
question. I need the entire working code demo(jsfiddle) for the same.
I don't want any reference links for tutorials or anything else. I
just want to work the exactly same google styled blue colored progress
bar working in my website's ajax function call. Anyhow you make my
code working with the necessary other code. Thanks. Waiting keenly for
the perfect answer folks. Have a nice day.
and as SO is not a code factory to its users disposal, the dupe is an excellent way to solve your question.
This community answer is intended to be deleted when the question is closed as a duplicate.
Edit after post review
This code snippet shows the essential part for a progress bar.
HTML
<div class="progress-bar"></div>
Script
function set_pbar(p) {
$('.progress-bar').css({ width:(p * 100)+'%'});
}
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
//Sending in progress, divided with 2 make bar 50% wide after sending
set_pbar(evt.loaded / evt.total / 2);
}
}, false);
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
//Receiving in progress, dividing with 2 and adding 0.5 make bar start at 50%
set_pbar(0.5 + (evt.loaded / evt.total / 2));
}
}, false);
return xhr;
},
url: "/echo/json/",
type: 'POST',
data: {json: JSON.stringify(new Array(100000))},
success: function(data){
//Loaded...
}
});