How to check if at least one input is completed? - javascript

I have this sample:
link
CODE HTML:
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>
CODE JS:
function sendForm() {
var status_form = false;
$(".add-patient input").each(function(){
if($(this).val() == ""){
status_form = true;
}
});
console.log(status_form);
var createdBy = jQuery('#created_by').val();
if( status_form )
{
alert('Fill at least one field');
}else{
alert("now it's ok");
}
}
I want to do a check ... if an input is complete when displaying the message "it; s ok" ... otherwise displaying another message
probably means the code clearly what they want to do.
You can help me with a solution please?
Thanks in advance!

Use .filter to get the length of the input elements having value as ''
Try this:
function sendForm() {
var elem = $(".add-patient input[type='text']");
var count = elem.filter(function() {
return !$(this).val();
}).length;
if (count == elem.length) {
alert('Fill at least one field');
} else {
alert("now it's ok");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="add-patient">
<fieldset style="display: block;">
<label for="new_exam">New exam</label>
<input type="text" name="new_exam" id="new_exam" value="">
</fieldset>
<fieldset style="display: block;">
<label for="x_ray">X ray</label>
<input type="text" name="x_ray" id="x_ray" value="">
</fieldset>
<input type="button" class="btn btn-submit" onclick="sendForm();" value="Create report">
</form>

Related

Javascript document.getElementById function not returning checkbox value to HTML form

I have been searching for an answer everywhere but just can not find what I need.
I have a webpage that has an HTML table on the left column and an HTML form on the right column. When I click on a row in the table on the left I want it to display the values in the form on the right.
I have this working perfectly for the text fields on the form, but not for the two checkboxes. My javascript will return either true or false or checked and unchecked to the document.getElementById within the script itself by using alert(); but I have no idea what it needs to allow the checkboxes to display these values. I thought the document.getElementById would return the values but it seems it does not.
I have tried all kinds of conveluted ways to get this to work but can not seem to get the correct code needed.
I am new to all this so there is most likely something really simple I am missing.
This is the HTML form code:
<div class="column right">
<table>
<tr></tr>
<tr>
<div class="lockinv">
<form autocomplete="off" name="lockform" class="keyassign" action="includes/lockinventory.inc.php"
method="post">
<label id="inventory" for="locknum">Lock Number</label>
<input id="invlocknum" type="text" name="locknum" value="" required>
<label id="inventory" for="locktype">Lock Type</label>
<input id="invlocktype" type="text" name="locktype" value="" required>
<label id="inventory" for="keycode">Key Code</label>
<input id="invkeycode" type="text" name="keycode" value="" required>
<label id="inventory" for="lockengraved">Lock Engraved</label>
<input id="invlockengraved" type="hidden" name="lockengraved" value="0">
<input id="invlockengraved" type="checkbox" name="lockengraved" value="1">
<label id="inventory" for="lockmastered">Lock Mastered</label>
<input id="invlockmastered" type="hidden" name="lockmastered" value="0">
<input id="invlockmastered" type="checkbox" name="lockmastered" value="1">
<label id="inventory" for="locknote">Lock Note</label>
<textarea id="inventorynote" name="locknote" rows="5" cols="60"></textarea>
<div class="wheel">
<?php
if (isset($_GET["error"])) {
if($_GET["error"] == "lockexists") {
echo "<p>Lock Already In Inventory!</p>";
}
else if ($_GET["error"] == "lockexistsfailed") {
echo "<p>Lock Already In Inventory!</p>";
}
}
?>
</div>
<input id="bt6" type="submit" name="submit" value="Save">
<button id="bt6" type="reset" name="button">Cancel</button>
</form>
</div>
</tr>
</table>
</div>
This is my JavaScript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script language="javascript"></script>
<script>
$(function () {
$('#lockTable td').click(function () {
var currentRow = $(this).closest("tr");
var locknum = currentRow.find("td:eq(0)").text();
var locktype = currentRow.find("td:eq(1)").text();
var keycode = currentRow.find("td:eq(2)").text();
var engraved = currentRow.find("td:eq(3)").find(":checkbox");
var mastered = currentRow.find("td:eq(4)").find(":checkbox");
var locknote = currentRow.find("td:eq(5)").text();
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
$grved = "checked";
} else {
$grved = "unchecked";
}
var lockmastered = mastered.prop("checked");
if (lockmastered === true) {
$msted = "checked";
} else {
$msted = "unchecked";
}
document.getElementById('invlocknum').value = locknum;
document.getElementById('invlocktype').value = locktype;
document.getElementById('invkeycode').value = keycode;
document.getElementById("invlockengraved").value = $grved;
document.getElementById('invlockmastered').value = $msted;
document.getElementById('inventorynote').value = locknote;
alert(document.getElementById("invlockengraved").value);
alert(document.getElementById("invlockmastered").value);
});
});
</script>
<p id="invlocknum"></p>
<p id="invlocktype"></p>
<p id="invkeycode"></p>
<p id="invlockengraved"></p>
<p id="invlockmastered"></p>
<p id="invlocknote"></p>
<p id="info"></p>
<p id="result"></p>
I found the answer to my issue. I had to modify my if statement in the Javascript to the following. Works the way I want it to. Thanks to all that helped.
var lockengraved = engraved.prop("checked");
if (lockengraved === true) {
document.getElementById("invlockengraved").checked = lockengraved;
}else if (lockengraved === false) {
document.getElementById("invlockengraved").checked = lockengraved;
}

Form submit to specific url according to data inserted

I have a form that is simply a input with a zip code and a submit button.
I need some help on submitting the form according to the data inserted.
For example if someone inserts a number between 1000-000 and 2999-999 it will be forward to landing1.html, if the input is between 3000-000 to 4000-999 it will forward to landing2.html and so on.
This is a draft of my code my code for better understanding
$(document).ready(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>
Hope someone can help me.
Many thanks!
Like this
We can make it more complex if you have many sets of post codes
$(function() {
$(".postal-code").inputmask("9999-999", {
"placeholder": "0"
});
$(".postal-code").inputmask("9999-999", {
"onincomplete": function() {
alert('Insere um Código Postal válido');
}
});
$(".needs-validation").on("submit",function() {
const cp = this.cp.value;
if (cp >= "1000-000" && cp <= "2999-999") this.action = "landing1.html";
else if (cp >= "3000-000" && cp <= "4000-999") this.action = "landing2.html";
// else this.action = "outofrange.html";
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/5.x/dist/jquery.inputmask.min.js"></script>
<div id="form-cp">
<form method="get" action="" onsubmit="" class="needs-validation">
<input type="text" name="cp" value="" size="8" maxlength="8" minlength="8" class="postal-code form-control-lg" aria-invalid="false" placeholder="0000-000" required>
<button type="submit" class="btn btn-primary">Send Data</button>
</form>
</div>

show/hide div if input is 0 or default

I´m working in a payment gateway where the user Name the Price for my digital books. An input box (to text the price) and a "Pay now" button are displayed. BUT:
If the price is less than 0.50 the payment button disapear and the download button appear
If the user introduce a "," instead a "." a box is displayed (please, enter a valid number)
Here is the form with the input box:
<form id="hikashop_paypal_form" name="hikashop_paypal_form" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="X" />
<input type="hidden" name="item_name_1" value="X" />
<input id="amount_1" name="amount_1" class="amount_1"/></form>
Pay Now button (it should be hiden if 1 is true)
<div id="PayNow" class="PayNow">
<input id="PayNow_button" type="submit" class="btn btn-primary" value="Pay now" name="" />
</div>
Download Now Button (it should be shown if 1 is true)
<div id="downloadNow" class="downloadNow">
Download now
</div>
Info box (It should be shown if 2 is true)
<div id="info" class="info">
Enter a valid number
</div>
And the question is: How can I do it?
I supose the solution passes by using javascript, but I don´t know how exactly... Thanks for you time...
I don´t know how, but it works for me:
Try it here: IBIZA! Book Download
<form id="pplaunch" action="https://www.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input id="issueid" name="issueid" type="hidden" value="ARCHIVE NAME">
<input type="hidden" id="currency" name="currency" value="EUR">
<input type="hidden" name="business" value="YOUR PAYPAL ID" />
<input type="hidden" value="0" name="test_ipn"></input>
<input type="hidden" name="item_name" value="PRODUC NAME">
<input type="hidden" value="1" name="no_shipping"></input>
<input type="hidden" value="0" name="no_note"></input>
<input type="hidden" value="utf-8" name="charset"></input>
<input type="hidden" value="Super" name="first_name"></input>
<input type="hidden" value="http://www.YOURWEBSITE.com/return" name="return"></input>
<input type="hidden" value="http://www.OURWEBSITE.com/cancel" name="cancel_return"></input>
<div class="nameprice" style="float:left;margin-right:15px;>
<span style="font-size:small;">Name your price: </span><input id="amount" name="amount" size="6" maxlength="5" type="text"> <span style="font-size:small;color:#ccc;">From 0.00€</span>
</div>
<div id="pricerror"></div>
<div class="buttonspace">
<button id="buybutton" class="buybutton" type="button">Checkout</button>
<div id="descargaGratisMensaje"></div>
<div style="display: block;" class="pay">
</div>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function newPopup(url, width, height){
popupWindow = window.open(url,'_blank','height='+height+',width='+width+',left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes');
return false;
}
function displaybutton(displayclass){
if(displayclass == 'pay'){
$('.pay').css('display','block');
$('#pplaunch').attr('action', 'https://www.paypal.com/cgi-binwebscr');
$('#buybutton').html('Pagar');
}else{
$('.pay').css('display','none');
$('#pplaunch').attr('action', 'http://www.example.com/archive/'+$('#issueid').val());
$('#buybutton').html('Descargar');
$('#descargaGratisMensaje').html('Un Me Gusta podría ser un buen intercambio');
}
}
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n) && (n.search(/0x/i)<0);
}
function price(n){
// return null if n is not a price, or n rounded to 2 dec. places
if(!isNumber(n)){
// maybe the user entered a comma as a decimal separator
n = n.replace(/,/g,'.');
if(!isNumber(n)){
return null;
}
}
// now we know it is a number, round it up to 2 dec. places
return Math.round(parseFloat(n)*100)/100;
}
function pricecheck(){
var data = $.trim($('#amount').val());
var myprice = price(data);
if(myprice == null){
if(data == ''){
$('#pricerror').html('');
}else{
$('#pricerror').html('Please enter a price.');
}
displaybutton('pay');
return false;
}
if(myprice == 0){
$('#pricerror').html('');
displaybutton('nopay');
}else if(myprice < 0.5){
$('#pricerror').html('The minimum price is '+currencysymbol+'0.50.
Please enter either zero, or at least '+currencysymbol+'0.50.');
displaybutton('pay');
}else{
$('#pricerror').html('');
displaybutton('pay');
}
jQuery('.content').hide();
}
var currencysymbol = '$';
$.getScript('//www.geoplugin.ne/javascript.gp?ref=panelsyndicate.com', function() {
if(geoplugin_continentCode() != 'EU'){return;}
$('#currency').val('EUR');
currencysymbol = '€';
$('.currencysymbol').html(currencysymbol);
});
$(document).ready(function(){
var dialog = $('#modal').dialog({
title: 'IBIZA!'
, autoOpen: false
, closeText: ''
, modal: true
, resizable: false
, width: 500
});
$('#buybutton').click(function() {
$('#pplaunch').submit();
});
$('#pplaunch').submit(function() {
var myprice = price($.trim($('#amount').val()));
if((myprice != 0) && ((myprice == null) || (myprice < 0.5))){
$('#pricerror').html('Please enter your price.');
$('#amount').focus();
return false;
}
});
$('.modaltrigger').click(function() {
var issueid = $(this).attr('href').substr(1);
$('#issueid').val(issueid); // Comic ID
$('#include_a_message_to').html(issues[issueid].include_a_message_to); // Destinee of the message
dialog.dialog('option', 'title', issues[issueid].title); // Title of the comic
$('#issuelangs').html(issues[issueid].langs); // Languages in which the comic is available
dialog.dialog('option', 'position', { my: "center", at: "center", of: window });
dialog.dialog('open');
// prevent the default action, e.g., following a link
pricecheck();
return false;
});
$('#amount').bind('input propertychange', function() {
pricecheck();
});
$('.custommsg').hide();
$('.msgtrigger').click(function() {
var cmsg = $('.custommsg');
if(cmsg.is(':visible')){
cmsg.hide();
$('.sendmsg').show();
}else{
$('.sendmsg').hide();
cmsg.show();
$('.msgtxt').focus();
}
return false;
});
$('.msgtxt').keyup(function(){
if($(this).val().length > maxlength){
$(this).val($(this).val().substr(0, maxlength));
}
var remaining = maxlength - $(this).val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
var maxlength = 200;
var remaining = maxlength - $('.msgtxt').val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
</script>

How to show form fields on keyup

I've been working on this for weeks now and I can't seem to get the hang of this. I'm trying to show the hidden fields only when the previous fields are entered. Here's my example code:
HTML
<form>
<div id="group1">
<label>Field 1:</label>
<input type="text" class="field1" />
<br/>
<label>Field 2:</label>
<input type="text" class="field2" />
<br/>
<label>Field 3:</label>
<input type="text" class="field3" />
<br/>
</div>
<div id="group2">
<label>Field 4:</label>
<input type="text" class="field4" />
<br/>
<label>Field 5:</label>
<input type="text" class="field5" />
<br/>
<label>Field 6:</label>
<input type="text" class="field6" />
<br/>
</div>
<div id="group3">
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 9:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>
</form>
CSS
#group2 {
visibility: hidden;
}
#group3 {
visibility: hidden;
}
Script
$(document).ready(function () {
$('#group1').find('input[type="text"]').keyup(function () {
CheckSubmit();
});
function CheckSubmit() {
var x = true;
$('#group1').find('input[type="text"]').keyup(function () {
if ($(this).val().length === 0) {
x = false;
return;
}
});
if (x) {
$('#group2').css('visibility', 'visible');
$('#group3').css('visibility', 'visible');
} else {
$('#group2').css('visibility', 'hidden');
$('#group3').css('visibility', 'hidden');
}
CheckSubmit();
});
I'm not sure what I'm doing wrong here. Can someone please assist?
I changed your code a bit. I stored the relevant selectors in variables, so you don't need to do a lot of re-querying every time something changes.
Here's the updated code:
JavaScript
var inputs = $('#group1').find('input[type="text"]');
var hidden = $('#group2, #group3');
inputs.keyup(function() {
var test = true;
inputs.each(function(key, value) {
if (!$(this).val().length) {
test = false;
return false;
}
});
hidden.css('visibility', ( test ? 'visible' : 'hidden' ) );
});
Demo
Try before buy
You can make this more dynamic by checking the inputs in the current div and if they all have a value, then show the next div (if there is one).
If they clear a value, then hide all the later divs.
$(document).ready(function() {
// you can restrict this to inputs in a specific div or just any input
$('#group1 input').on('keyup', function () {
var parentDiv = $(this).closest('div')
var hasValues = parentDiv.find('input').filter(function() {
return this.value == '';
}).length == 0;
if(hasValues) {
//parentDiv.next().css('visibility', 'visible'); // show just the next section
parentDiv.nextAll().css('visibility', 'visible'); // show all later sections
} else {
parentDiv.nextAll().css('visibility', 'hidden');
}
});
});
DEMO
I made a quick pen with a solution. It may not be the prettiest but it get's it done. Basically on every keyup event I check #group1's children for their value length and if they all have a length that's more than 0 I change a flag in an array. If all 3 flags are true I show #group2.
Here's the pen
$('#group2').hide();
$('#group3').hide();
$('#group1').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group1 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group2').show();
}
});
$('#group2').keyup(function() {
var flags = {
0: false,
1: false,
2: false
}
$('#group2 > input').each(function(i, ele) {
if(ele.value.length !== 0)
{
flags[i] = true;
}
});
if(flags[0] && flags[1] && flags[2])
{
$('#group3').show();
}
});
Hope it helps :D
If I understand your question well, you want to show the fields in #group2/-3 if all the fields in the previous fields have a value. Using a few data-*-attributes (see MDN), you can create a handler like this (if you prefer: jsFiddle, containing a more complete example):
$('[data-nextgroup] [type=text]').on('keyup', function (e){
var fieldgroup = $(this.getAttribute('data-group'))
,fields = fieldgroup.find('[type=text]')
,canshow = fields.length ===
fields.filter( function (i,el) { return el.value.length; } ).length;
void( canshow && $(fieldgroup.attr('data-nextgroup')).fadeIn() );
});
[data-hidden] {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="group1" data-nextgroup="#group2">
<label>Field 1:</label>
<input type="text" class="field1" data-group="#group1"/>
<br/>
<label>Field 2:</label>
<input type="text" class="field2" data-group="#group1"/>
<br/>
<label>Field 3:</label>
<input type="text" class="field3" data-group="#group1"/>
<br/>
</div>
<div id="group2" data-nextgroup="#group3" data-hidden>
<label>Field 4:</label>
<input type="text" class="field4" data-group="#group2"/>
<br/>
<label>Field 5:</label>
<input type="text" class="field5" data-group="#group2"/>
<br/>
<label>Field 6:</label>
<input type="text" class="field6" data-group="#group2"/>
<br/>
</div>
<div id="group3" data-groups data-hidden>
<label>Field 7:</label>
<input type="text" class="field7" />
<br/>
<label>Field 8:</label>
<input type="text" class="field8" />
<br/>
<label>Field 8:</label>
<input type="text" class="field9" />
<br/>
<input type="submit" value="Submit">
</div>

Disable submit if inputs empty jquery

Disclaimer: I know there are quite a few questions out there with this topic and it has been highly addressed, though I need assistance in my particular case.
I am trying to check if the input values are empty on keyup then disable the submit button.
My HTML snippet:
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" />
</div>
</form>
</div>
I have used the example answer from here with some modifications:
(function() {
$('.field input').keyup(function() {
var empty = false;
$('.field input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', true);
} else {
$('.actions input').attr('disabled', false);
}
});
})()
Any help would be greatly appreciated!
I would suggest disabling the button by default. I would also look at the length of the .val(), not check for an empty string. Lastly, I think document.ready() is much more readable than your existing code: Here is the full code:
HTML
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>​
JS/jQuery
$(document).ready(function() {
$('.field input').on('keyup', function() {
let empty = false;
$('.field input').each(function() {
empty = $(this).val().length == 0;
});
if (empty)
$('.actions input').attr('disabled', 'disabled');
else
$('.actions input').attr('disabled', false);
});
});
Here's a working fiddle.
I use this in my project and it succes.
$(document).ready(function() {
$('.field').keyup(function() {
var empty = false;
$('.field').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$('.actions[type="submit"]').attr('disabled', 'disabled');
} else {
$('.actions[type="submit"]').removeAttr('disabled');
}
});
});

Categories