Enable Button After Form Auto Populates - javascript

I have a form that auto populates based on records returned from my MySQL database. I have all fields but the search field as read only because the user shouldn't be able to edit them. I would like my submit button disabled until the field "beerID" has been populated, but I can't seem to get it working. Onkeyup doesn't work because the user isn't actually typing in that field. And I can't seem to get onChange to work either. Any ideas?
Here is my JavaScript (enableSubmit is the code for the submit button):
<script>
$(function() {
$('#brewery').val("");
$('#style').val("");
$('#ABV').val("");
$('#IBU').val("");
$('#OG').val("");
$('#FG').val("");
$('#beerID').val("");
$("#beer").autocomplete({
source: "beers.php",
minLength: 2,
select: function(event, ui) {
$('#beerID').val(ui.item.beerID);
$('#brewery').val(ui.item.brewery);
$('#style').val(ui.item.style);
$('#ABV').val(ui.item.ABV);
$('#IBU').val(ui.item.IBU);
$('#OG').val(ui.item.OG);
$('#FG').val(ui.item.FG);
}
});
});
function enableSubmit(){
if(beerID.value.length > 0) {
document.getElementById('newJournalEntry').disabled = false;
} else {
document.getElementById('newJournalEntry').disabled = true;
}
}
</script>
And here is my HTML:
<div data-role="page" id="view" data-url="currentpage">
<div data-role="header" data-position="fixed" data-theme="b" data-content-theme="b">
Menu
<h2>Beer Journal</h2>
</div>
<div class="ui-body ui-body-a">
<form action="journal.php" method="post" data-ajax="false" enctype="multipart/form-data">
<fieldset>
<p class="ui-widget">
<label for="beer"></label>
<input type="search" name="beer" id="beer" placeholder="Start Typing a Beer's Name..." >
<div class="ui-field-contain">
<label for="brewery">Brewery:</label>
<input type="text" id="brewery" name="brewery" readonly>
<label for="style">Style:</label>
<input type="text" id="style" name="style" readonly>
<label for="ABV">ABV(%):</label>
<input type="text" id="ABV" name="ABV" readonly>
<label for="IBU">IBU:</label>
<input type="text" id="IBU" name="IBU" readonly>
<label for="OG">OG:</label>
<input type="text" id="OG" name="OG" readonly>
<label for="FG">FG:</label>
<input type="text" id="FG" name="FG" readonly>
<label for="beerID" onChange="enableSubmit()">BeerID:</label>
<input type="number" id="beerID" name="beerID" readonly>
</div>
</p>
</fieldset>
<fieldset class="ui-grid-a">
<div class="ui-block-a"><input type="submit" name="newJournalEntry" id="newJournalEntry" data-inline="false" data-shadow="false" data-corners="false" value="Create Beer Journal Entry" data-theme="e" disabled></div>
<div class="ui-block-b"><input type="button" onClick="location.href='newentryaddbeer.php'" data-inline="false" data-shadow="false" data-corners="false" value="Start from Scratch" data-theme="f"></div>
</fieldset>
</form>
</div>

As kehrk said, the .change event handler would be a good fit. Something like this is what I'd use:
$(document).on('change', '#beerID', function(){
if($(this).val() == ''){
$('input[type=submit]').attr('disabled', 'disabled');
}
else {
$('input[type=submit]').removeAttr('disabled');
}
});

The reason why change isn't working is because change is only fired on user interaction with a field. Since the value of beerID is being changed by jQuery, a change event isn't fired.
From this SO question, it is suggested that you manually fire the change event yourself:
$('#beerID').change();
Two other issues:
Issue 1:
You are attaching the onchange handler to the label rather than the beerID element itself.
Issue 2:
In your enableSubmit() function, you are referencing a variable beerID that doesn't exist.
Solution:
<script>
$(function() {
$('#brewery').val("");
$('#style').val("");
$('#ABV').val("");
$('#IBU').val("");
$('#OG').val("");
$('#FG').val("");
$('#beerID').val("");
$("#beer").autocomplete({
source: "beers.php",
minLength: 2,
select: function(event, ui) {
$('#beerID').val(ui.item.beerID).change();
$('#brewery').val(ui.item.brewery);
$('#style').val(ui.item.style);
$('#ABV').val(ui.item.ABV);
$('#IBU').val(ui.item.IBU);
$('#OG').val(ui.item.OG);
$('#FG').val(ui.item.FG);
}
});
});
function enableSubmit(){
if($('#beerID').val().length > 0) {
$('#newJournalEntry').parent().removeClass('ui-state-disabled');
} else {
$('#newJournalEntry').parent().addClass('ui-state-disabled');
}
}
</script>
<div data-role="page" id="view" data-url="currentpage">
<div data-role="header" data-position="fixed" data-theme="b" data-content-theme="b">
Menu
<h2>Beer Journal</h2>
</div>
<div class="ui-body ui-body-a">
<form action="journal.php" method="post" data-ajax="false" enctype="multipart/form-data">
<fieldset>
<p class="ui-widget">
<label for="beer"></label>
<input type="search" name="beer" id="beer" placeholder="Start Typing a Beer's Name..." >
<div class="ui-field-contain">
<label for="brewery">Brewery:</label>
<input type="text" id="brewery" name="brewery" readonly>
<label for="style">Style:</label>
<input type="text" id="style" name="style" readonly>
<label for="ABV">ABV(%):</label>
<input type="text" id="ABV" name="ABV" readonly>
<label for="IBU">IBU:</label>
<input type="text" id="IBU" name="IBU" readonly>
<label for="OG">OG:</label>
<input type="text" id="OG" name="OG" readonly>
<label for="FG">FG:</label>
<input type="text" id="FG" name="FG" readonly>
<label for="beerID">BeerID:</label>
<input type="number" onchange="enableSubmit()" id="beerID" name="beerID" readonly>
</div>
</p>
</fieldset>
<fieldset class="ui-grid-a">
<div class="ui-block-a"><input type="submit" name="newJournalEntry" id="newJournalEntry" data-inline="false" data-shadow="false" data-corners="false" value="Create Beer Journal Entry" data-theme="e" disabled></div>
<div class="ui-block-b"><input type="button" onClick="location.href='newentryaddbeer.php'" data-inline="false" data-shadow="false" data-corners="false" value="Start from Scratch" data-theme="f"></div>
</fieldset>
</form>
</div>

There's no reason that the .change event handler shouldn't work.
$(function () {
//this should work...
$("#beerID").change(function () {
$("#newJournalEntry").prop("disabled", false);
});
$('#brewery').val("");
$('#style').val("");
$('#ABV').val("");
$('#IBU').val("");
$('#OG').val("");
$('#FG').val("");
$('#beerID').val("");
$("#beer").autocomplete({
source: "beers.php",
minLength: 2,
select: function (event, ui) {
$('#beerID').val(ui.item.beerID);
$('#brewery').val(ui.item.brewery);
$('#style').val(ui.item.style);
$('#ABV').val(ui.item.ABV);
$('#IBU').val(ui.item.IBU);
$('#OG').val(ui.item.OG);
$('#FG').val(ui.item.FG);
}
});
});
function enableSubmit() {
if (beerID.value.length > 0) {
document.getElementById('newJournalEntry').disabled = false;
} else {
document.getElementById('newJournalEntry').disabled = true;
}
}

I don't see where you set beerID try adding
beerID= $('#beerID');
before the if statement
Then call the enablesubmit function once you have completed the auto fill of the fields.

You can put it here to enable it:
select: function (event, ui) {
$('#beerID').val(ui.item.beerID);
$('#brewery').val(ui.item.brewery);
$('#style').val(ui.item.style);
$('#ABV').val(ui.item.ABV);
$('#IBU').val(ui.item.IBU);
$('#OG').val(ui.item.OG);
$('#FG').val(ui.item.FG);
if($('#beerID').val() !== ''){
$('#newJournalEntry').prop('disabled', false);
}
}

Related

Ajax form submit does not stay on page

I've got this script that validates my form guestform (from bootstrap) then uses ajax to submit and it works fine and loads on the same page. However, when I added some code that when the radio button "true" is clicked it reveals a hidden part of the form (I was very proud of myself for that) this breaks my ajax submit and it goes to another page and spits out the results from my php file. How can I integrate the on clicks better?
$(document).ready(function() {
var forms = document.querySelectorAll('.needs-validation')
Array.prototype.slice.call(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
$("#btnsub").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: $('#guestForm').attr('action'),
data: $('#guestForm').serialize(),
success: function(response) {
$('#output').text(response);
}
});
});
form.classList.add('was-validated')
}, false)
});
//breaks ajax submit
$('#true').click(function(event) {
document.getElementById("guests").style.display = "block";
});
$('#false').click(function(event) {
document.getElementById("guests").style.display = "none";
});
//breaks ajax submit code
});
<form method="POST" action="insert.php" id="guestForm" class="needs-validation" novalidate>
<div class="col-6">
<label for="party" class="form-label">Your Name</label>
<input type="text" class="form-control" id="party" name="party" minlength="4" maxlength="50" aria-describedby=inputGroup-sizing-default " required>
<div class="invalid-feedback ">Please Enter your full name.</div>
</div>
<div class="form-label ">Will you be joining us ?"</div>
<div class="form-check">
<input type="radio" class="form-check-input" id="true" name="att" required />
<label class="form-check-label" for="true">Joyfully accepts</label>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" id="false" name="att" required />
<label class="form-check-label" for="false">Regretfully declines</label>
<div class="invalid-feedback">Please choose a response.</div>
</div>
<div class="col-6" id="guests" name="guests" style="display: none">
<p>If you are bringing a +1, please enter their name here.</p><br>
<label for="guest1" class="form-label">Guest Name</label>
<input type="text" class="form-control" id="guest1" name="guest1" placeholder="Optional" minlength="4" maxlength="50">
<div class="invalid-feedback">Please Enter their full name.</div>
</div>
<button type="submit" class="btn btn-primary" id="btnsub" name="btnsub">Submit</button>
<div id="output"></div>
</form>

Change submit onclick based on a checkbox

I have a form that is being used as a basic contact form. I have added a checkbox that adds some fields if selected. How can I change the onclick action of the submit button based on if this box is checked or not. Here is what I have currently.
<form class="homeContact">
<label for="chkJob">
Interested in a career? Check to apply
<input type="checkbox" id="chkJob" />
</label>
<div id="dvApply" style="display: none">
Download Application
Download the application. Fill it out and upload below:
<input type="file" name="fileToUpload" id="fileToUpload">
</div>
<div id="popErr"></div>
<input type="hidden" name="nospam">
<div class="field">
<div class="label-form">
<input type="text" placeholder="Name *" value="" name="name" id="popName">
<span class="form-icon fa fa-user"></span>
</div>
</div>
<div class="field">
<div class="label-form">
<input type="text" placeholder="Email *" value="" name="email" id="popEmail">
<span class="form-icon fa fa-envelope"></span>
</div>
</div>
<div class="field">
<div class="label-form">
<input type="text" placeholder="Phone *" value="" name="phone" id="popTel">
<span class="form-icon fa fa-phone"></span>
</div>
</div>
<div id="submit_button">
<input type="button" class="button submit" id="contact-submit" onclick="submitForm()" value="Request Information">
</div>
</form>
<script>
jQuery(document).ready(function($) {
$("#chkJob").click(function () {
if ($(this).is(":checked")) {
$("#dvApply").show();
} else {
$("#dvApply").hide();
}
});
});
</script>
You can implement this login into your submitForm function:
function submitForm()
{
if ($('#chkJob').is(":checked")) {
$("#dvApply").show();
} else {
$("#dvApply").hide();
}
}
But if you want dvApply to be toggled every time checkbox button is clicked without waiting for submit button to be clicked you can do something like:
jQuery(document).ready(function($) {
$('#chkJob').change(function() {
$('#dvApply').toggle();
});
});

Javascript hide/show questions depending on user input values

I am trying to hide and/or show form elements when a user selects certain values.
For example, if the user selects "yes" to the consent question, I need it to show a few questions, However, if they change their response to the consent question, I need it to hide those questions.
Here is what I have come up with so far...
$(document).ready(function () {
var input = document.getElementById('consent');
var consent_responses = [{ "0": hideConsent },{ "1": showConsent }];
input.addEventListner('click', function () {
var consent_response;
if (consent_responses[this.value]) {
content_response = consent_responses[this.Function()]
}
else {
content_response = consent_responses[this.Function]
}
});
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
function hideConsent(){
$("#date").hide(),
$("#referrer").hide(),
$("#f_name").hide(),
$("#phone_num").hide(),
$("#leave_msg").hide(),
$("#email").hide(),
}; });
Fiddle here: http://jsfiddle.net/7jX47/1/
You could do it like this: JSFiddle
Basically I only fixed a few typos (did you actually try your code before you posted here?) and added event listeners to the radio buttons with
document.getElementById(...).addEventListener(...)
I also gave your radio buttons unique IDs.
This can be simplified:
var input = document.getElementById('consent');
// Let's use the value as key, and the functions as values
var consent_responses = {
"0" : hideConsent,
"1" : showConsent
};
input.addEventListener("click", function () {
// Get the appropriate function given the value, and invoke it
consent_responses[this.value]();
});
function hideConsent() {
// ...
}
function showConsent() {
// ...
}
It's better to envelop your questions (that needs to be hidden) by a div with a class ".hidden" or style "display: none;". And simplify your code by simply asking that div to show() or hide() when needed.
Like so:
<form id="screening">
<div class="col-md-12 col-sm-12 col-xs-12 nopad" id="create">
<div class="form-group text-center">
<b>Do you agree to answer the screening questions?</b><br />
<div class="radio" id="consent">
<label>
<input type="radio" name="consent" id="consent" value="1">
Yes, I consent
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="consent" id="consent" value="0">
No, I do not consent
</label>
</div>
</div>
<!-- simplify by using this -->
<div id="questions" style="display: none;">
<div class="form-group" id="date">
<label for="date">What is today's date?</label>
<input type="date" class="form-control" id="date" name="date" />
</div>
<div class="form-group" id="referrer">
<label for="referrer">How did you hear about us/our studies?</label>
<select class="form-control" name="referrer" id="referrer">
<option></option>
<option value="1">Flyers</option>
<option value="2">Print Media</option>
<option value="3">A friend</option>
<option value="4">Online (e.g., Craigslist)</option>
<option value="5">Other</option>
</select>
</div>
<div class="form-group" id="other_explain">
<label for="other_explain">Please specify other source.</label>
<textarea class="form-control" rows="3" id="other_explain" name="other_explain"></textarea>
</div>
<div class="form-group" id="f_name">
<label for="f_name">What is your first name?</label>
<input type="text" class="form-control" id="f_name" name="f_name" />
</div>
<div class="form-group" id="phone_num">
<label for="phone_num">What is a phone number at which you can be contacted? </label>
<input type="tel" class="form-control" id="phone_num" name="phone_num" />
</div>
<div class="form-group" id="leave_msg">
<label for="leave_msg">If we call and you are not available, may we leave a message?</label><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="1">
Yes
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="0">
No
</label>
</div>
</div>
<div class="form-group" id="email">
<label for="email">What is an e-mail at which you can be contacted?</label>
<input type="email" class="form-control" id="email" name="email" />
</div>
</div>
</div>
</form>
and in your javascript instead of using this:
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
you use:
function showConsent(){
$("#questions").show(),
};

I am Having problems getting data from localStorage back to the form for update using jquery?

I'm creating a mobile app that stores employee data and retrieves it for updates. I can't find the method to call/populate from localStorage using jQuery.
Would be glad if someone could look at my codes and tell me what I am doing wrong or mixing up.
Thanks.
Expected behavior
On-click of the edit button, the UI should go to the edit-form page and populate the edit-form fields with data from localStorage.
Actual behavior
Clicking edit goes to the edit-form page. The fields are not populated.
HTML
<hr style="height:3px; background-color:#ccc; border:0; margin-top:12px; margin-bottom:12px;">
<form id="edit_employee_form" action="" >
<div class="ui-field-contain Employee No" data-controltype="textinput">
<input name="employeeno" id="employeeno" data-clear-btn="true" value="" type="text" data-mini="true" >
</div>
<div class="ui-field-contain Parties" data-controltype="textinput" contenteditable="true">
<input name="employeename" id="employeename" data-clear-btn="true"
value="" type="text" data-mini="true" required/>
</div>
<div class="ui-field-contain State" data-controltype="textinput">
<input name="stateoforigine" id="stateoforigine" data-clear-btn="true"
value="" type="text" data-mini="true">
</div>
<div class="ui-field-contain Phone Employee" data-controltype="textinput">
<input name="employeephone" id="employeephone" data-clear-btn="true"
value="" type="text" data-mini="true">
</div>
<div class="ui-field-contain Date Of Birth" data-controltype="dateinput">
<input data-name="dateofbirth" data-inline="true" type="text" id="dateofbirth" data-clear-btn="true" value="" type="date" data-mini="true">
<div class="ui-field-contain id" data-controltype="textinput">
<input name="id" input type="hidden" id="id" data-clear-btn="true" placeholder="case id" value="" type="text" data-mini="true" >
</div>
</div>
<div class="ui-block-a">
<input id="update" href="#employee_list_view_page" type="submit" data-inline="true" data-theme="b" value="Update"
data-mini="true" class="ui-btn ui-corner-all ui-btn ui-shadow ui-btn Save">
</div>
<div class="ui-block-b">
<div class="ui-block-b">
<input id="cancel" type="reset" value="Reset" class="ui-btn ui-corner-all ui-btn ui-shadow ui-btn">
</div>
</form>
<div data-theme="a" data-role="footer" data-position="fixed">
<h2 class="ui-title">
Employees Catalog
</h2>
</div>
</div>
</div>
</body>
</html>`
Code for populating data from localStorage on edit-button click:
//Edit Case Function
function Edit() {
employees[i] = JSON.stringify({
id: employees.length + 1,
employeeno: $('#employeeno').val(),
employeename: $('#employeename').val(),
stateoforigine: $('#stateoforigine').val(),
employeephone: $('#employeephone').val(),
dateofbirth: $('#dateofbirth').val(),
}); //Alter the selected item in the form
localStorage.setItem("employees", JSON.stringify(employees));
return true;
}
for (var i in employees) {
var empData = JSON.parse(localStorage.getItem(employees[i]));
};
//register Edit button
$('.edit_button').live('click', function (e) {
alert('Iwas clicked');
e.stopPropagation();
var empData = JSON.parse(localStorage.getItem('employees'));
$('#employeeno').val('employeeno');
$('#employeename').val('employeename');
$("#stateoforigine").val('stateoforigine');
$('#employeephone').val('employeephone');
$('#dateofbirth').val('dateofbirth');
$('#id').val(id);
$("#id").attr("readonly", "readonly");
$('#employeeno').focus();
$.mobile.changePage('#edit_employee_page');
return false;
});
Sample localStorage file:
[{"id":1,"employeeno":"DEF/234/20014","employeename":"Bill Foreman","stateoforigine":"Califonia","employeephone":"09543765432","dateofbirth":"12/11/1965"}]
The key is employees.
if ur json is...
[{"id":1,"employeeno":"DEF/234/20014","employeename":"Bill Foreman","stateoforigine":"Califonia","employeephone":"09543765432","dateofbirth":"12/11/1965"}]
then..
$.each(data, function(a, b) {
$('#employeeno').val(b.employeeno);
$('#employeename').val(b.employeename);
$("#stateoforigine").val(b.stateoforigine);
$('#employeephone').val(b.employeephone);
$('#dateofbirth').val(b.dateofbirth);
$('#id').val(b.id);
});

How to close fancybox and reset input form values

Hello I have a contact us form using fancybox, and I want to reset/clear the form input values when fancybox closes (either when user clicks outside the popup or using the "close" popup button)
the element which holds the fancybox content is 'inline' so my guess was:
...
$("#fancybox-overlay").fancybox({
'afterClosed': function() {
$('#inline').hide(250, function() {
$('#name input').val('');
$('#phone input').val('');
$('#email input').val('');
$('#subject input').val('');
$('#msgcontent textarea').val('');
$('#security_code input').val('');
$('#name input').removeClass('error');
$('#phone input').removeClass('error');
$('#email input').removeClass('error');
$('#subject input').removeClass('error');
$('#msgcontent textarea').removeClass('error');
$('#security_code input').removeClass('error');
$('#security_code_error').html('');
});
}
});
But the result is as below:
before :
and after:
Any help to make the form values reset/cleared during a "close" action from clicking outside the popup, will be very much appreciated. Thanks.
UPDATE:
The html requested by #Spokey is:
<div id="inline" style="z-index:999999;">
<h2 class="popupheader">...Contact Us: Send us a Message</h2>
<div style="margin:2% 8%;background:#fff;border-radius:5px;width:auto;box-shadow: 3px 3px 10px #bbb;">
<p style="display:inline-block;padding:10px;">
...
</p>
<p style="display:inline-block;padding:10px;float:right;">
...
</p>
</div>
<form id="contact" name="contact" action="#" method="post">
<label for="name">Your Name</label>
<input type="text" id="name" name="name" class="txt" style="margin-left: 3px">
<br>
<label for="phone">Your Phone No.</label>
<input type="text" id="phone" name="phone" class="txt" >
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="subject">Subject</label>
<input type="text" id="subject" name="subject" class="txt" size="45">
<br>
<label for="msgcontent">Enter a Message</label>
<textarea id="msgcontent" name="msgcontent" class="txtarea" style="margin-left: 3px"></textarea>
<br>
<label for="security_code" style="width:auto;">Verify you are human</label>
<img border="0" id="captcha" src="../../image.php" alt=""> <a href="JavaScript: new_captcha();">
<img border="0" alt="" src="../../images/refresh.png" align="bottom"></a>
<input name="security_code" id="security_code" class="txt" style="width:150px;vertical-align: top;margin: 0px;" size="20" type="text" >
<span id="security_code_error" name="security_code_error" style="background:#fefefe;color:red;"></span><? /*<div class="field_error error_pos"><?php if($error['security_code'] != "") echo $error['security_code']; ?></div> */ ?>
<br />
<hr style="color:#f2f2f2;border:1px solid #f2f2f2;width:auto;">
<button id="send" name="send">Send Message</button>
</form>
</div>
And you can do it a lot more easier and cleaner. E.g. if you want to clear all input fields just do it that way without repetitive and spaghetti code:
document.getElementById("yourFormId").reset();
You don't need to hide #inline, as the plugin will hide it itself
$("#fancybox-overlay").fancybox({
'afterClose': function() {
$('#inline input, #inline textarea').val('');
$('#inline').children().removeClass('error');
$('#security_code_error').empty();
}
});
NOTE changed 'afterClosed' for fancybox2
to 'afterClose' (typo error)

Categories

Resources