Validate input text in bootstrap modal - javascript

I want to validate a form in a bootstrap modal without using any framework. It's actually a simple modal with only an input text and two buttons "Close" and "Send".
The user should type his/her name in the input box and click send. The form is the sent with the method post.
What I want to do is that, if the user doesn't enter anything in the input box of and clicks on the button "Send", the input box should have a red border circling it instead of the default blue border. Here's the code for my modal:
<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!--form-->
<form class = "form-horizontal" id="myForm" method="post" action="test.php" role="form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">My modal</h4>
</div>
<div class="modal-body">
<p>
Please enter your name:
</p>
<br/>
<div class="form-group">
<div class="col-lg-12">
<label class="control-label" for="firstname">Name</label>
<input type="text" class="form-control required" id="firstname" name="firstname">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="myFormSubmit" class="btn btn-primary">Send</button>
</div>
</form>
</div>
</div>
</div>
I tried using javascript to change the class of the input text to has-errorbut it doesn't produce the red outline. When I click on send it sends the empty value through the post method instead of
Here's my javascript code:
<script type="text/javascript">
$('#myForm').validate({
rules: {
name: {
minlength: 1,
required: true
},
},
highlight: function (element) {
$('#firstname').removeClass('has-success').addClass('has-error');
},
success: function (element) {
$('#firstname').removeClass('has-error').addClass('has-success');
}
});
</script>
I feel like I'm mixing a whole lot of things here. I'm still new to bootstrap and javascript. How can I go about getting the desired red outline?
Thanks.
Edit:
Validate function:
function validate() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
return false;
}
}

You need to change the CSS classes of the input parent element div.form-group, not the input itself:
The HTML after the submit button click should look like this:
<div class="form-group has-error">
<div class="col-lg-12">
<label class="control-label" for="firstname">Name</label>
<input type="text" class="form-control required" id="firstname" name="firstname">
</div>
</div>
To achieve this, alter your JavaScript code to this:
<script type="text/javascript">
$('#myForm').on('submit', function(e) {
var firstName = $('#firstname');
// Check if there is an entered value
if(!firstName.val()) {
// Add errors highlight
firstName.closest('.form-group').removeClass('has-success').addClass('has-error');
// Stop submission of the form
e.preventDefault();
} else {
// Remove the errors highlight
firstName.closest('.form-group').removeClass('has-error').addClass('has-success');
}
});
</script>

div in boot strap...
<div class="form-group">
<div class="row">
<label class="col-xs-2 col-sm-2 control-label">city:</label>
<div class="col-xs-3 col-sm-3 formGroups"
id="city_form1">
<form:input name="city" class="form-control"
placeholder="City" data-toggle="tooltip"
data-placement="bottom" title="City" maxlength="15" />
<small class="help-block col-sm-offset-0 col-sm-9"
style="display: none;">city must require</small>
</div>
</div>
</div>
as you see there is .help-block is display: none now you write javascript function and check validation and if validation now pass make it display: block ... that's way you can do
enjoy with boot strap :)

its very easy
just apply class .has-error to div by javascript function
<div class="form-group has-error">
<div class="row">
<label class="col-xs-2 col-sm-2 control-label">city:</label>
<div class="col-xs-3 col-sm-3 formGroups"
id="city_form1">
<form:input name="city" class="form-control"
placeholder="City" data-toggle="tooltip"
data-placement="bottom" title="City" maxlength="15" />
</div>
</div>
</div>

Just use required inside the input field like this
<input type="text" class="form-control required" id="firstname" name="firstname" required/>

Related

i want to display two popups, one for error message and other for success message

I'm new to modals, i want to submit a form and then show success popup if user form is validated else want to show error popup. Also my it should execute php file for sending the email to user in background.
So, far i'm successful in executing the php file in background and show the model when user clicks on submit button.
But i want the popup to show when the form is validated. Also i want to use type="submit" instead of type="button" for form submit.
Here's my code :
<!-- javascript code to execute php file -->
<script type="text/javascript">
function executePhp() {
$.post("sendmail.php");
return false;
}
</script>
<!-- javascript code ends -->
<form class="well" action="" method="">
<div class="form-group col-md-6">
<label for="inputPassword4">Full Name</label>
<input type="text" name="name" class="form-control" id="inputPassword4" placeholder="Enter Full Name">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Phone Number</label>
<input type="number" name="mobile" class="form-control" id="inputEmail4" placeholder="Enter Mobile Number">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Email</label>
<input type="email" name="email" class="form-control" id="inputPassword4" placeholder="Enter Your Email">
</div>
</div>
<button type="button" class="btn btn-primary" onclick="executePhp()" style="margin-left: 3%;"
data-toggle="modal" data-target="#myModal">Check</button>
</form>
<!-- Code for popup -->
<!-- Modal -->
<div class="modal fade mymodal" id="myModal" role="dialog">
<div class="modal-dialog mydialog">
<!-- Modal content-->
<div class="modal-content mycontent">
<div class="modal-header myheader">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Message</h3>
</div>
<div class="modal-body mybody">
<br>
<br>
<h3>Thanks for choosing</h3>
<h4>
Your details will arive by email.
Sit back, we'll get back to you soon.
</h4>
<br>
<br>
</div>
<div class="modal-footer myfooter">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Code for popup end-->
Thank you.
You can use Jquery to achieve this.
In you php you can have two variables before the validation like:
$popup_message = "";
$popup_message_color = "";
Now if the form is validated you can display the modal like this:
$popup_message = "login successfully.";
$popup_message_color = "success";
//Open Modal
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myModal').modal('show');
});
</script>";
In the modal body you can display the message and color.
<div class="modal-body">
<p class="text-<?php echo $popup_message_color; ?>"><?php echo $popup_message; ?></p>
</div>
The same would be done for if validation fails, just change your message and color to $popup_message_color = "danger";
Note If you are validation to another page then the modal should be in that page and you change the close buttons to a link to go back.
Also php script should come after you loaded the jquery.

JQuery Bootstrap Modal auto calculate text field not updating

I have a bootstrap html page that contains already 2 auto update text field functions for its needs. Along with that I added another fields in a modal to complete the page and requires another auto calculation to be populated on a certain text field.
Base form for first and 2nd instance of auto update
<form role="form" id="myForm" action="cashier.php?submit=yes" method="post" data-toggle="validator">
<div class="form-group">
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Item</label>
<select onchange="GenPrice(this)" id="items" name="items" class="form-control" required>
<option value="" selected disabled>Select Item</option>
<?php
//some sql function for fetch
echo '<option value="'.$row['sup_eaprice'].'|'.$row['sup_name'].'" required>'.$row['sup_name'].'</option>';
}
}
?>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//FIRST INSTANCE AUTO UPDATING TEXT FIELD
<label for="exampleInputEmail1">Price (ea)</label>
<input type="text" class="form-control" id="eaprice" placeholder="No Item Selected" required disabled>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Quantity</label>
<input type="text" class="form-control calculate" onchange="GenTot(this)" name="quantity" id="quantity" placeholder="How many?" pattern="^[0-9]*[1-9][0-9]*$" maxlength="3" data-minlength="1" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//2ND INSTANCE AUTO UPDATING TEXTFIELD
<label for="exampleInputEmail1">Total</label>
<input type="text" class="form-control" id="ztotal" name="ztotal" readonly>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group" align="right">
<button id="submit" type="submit" class="btn btn-primary" name="addcart">Add Cart</button>
</div>
</div>
</form>
Modal window 3rd instance
<!--create confirmation modal window-->
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<b>Final Check</b>
</div>
<div class="modal-body">
<div class="row">
<form role="form" id="purchformx" action="cashier.php?submit=yes" method="post" data-toggle="validator">
<!-- hidden for purpose of change auto calc -->
<input type="hidden" name="thetotal" class="calchange" id="thetotal" value="<?php echo $overall; ?>">
<div class="col-md-6 col-xs-6">
<div class="form-group">
<label for="exampleInputEmail1">Received</label>
<input type="text" class="form-control calchange" name="received" id="received" placeholder="How much given?" pattern="^[0-9]*[1-9][0-9]*$" maxlength="4" data-minlength="1" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
//3RD INSTANCE AUTO UPDATE NOT WORKING
<label for="exampleInputEmail1">Change</label>
<input type="text" class="form-control" id="thechange" name="thechange" readonly>
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
Submit
</div>
</div>
</div>
</div>
<!--end modal-->
JQUERIES
For first instance (working)
<script type="text/javascript">
function GenPrice(data) {
var xprice = data.value;
var zprice = xprice.split("|");
document.getElementById ("eaprice").value = zprice[0];
document.myForm.eaprice.value = zprice[0];
}
</script>
For second instance (working) based from Calculate total value inline form
<script type="text/javascript">
/* total value calculator */
$(document).ready(function () {
//Calculate both inputs value on the fly
$('.calculate').keyup(function () {
var Tot = parseFloat($('#eaprice').val()) * parseInt($('#quantity').val());
if(isNaN(Tot)) Tot = "";
$('#ztotal').val(Tot);
});
//Clear both inputs first time when user focus on each inputs and clear value 00
$('.calculate').focus(function (event) {
$(this).val("").unbind(event);
});
});
</script>
For third instance (not working) based from auto calculate total value
<script type="text/javascript">
$(document).ready(function(){
$('.calchange').change(function(){
var total = 0;
$('.calchange').each(function(){
if($(this).val() != '')
{
total = parseFloat($(this).val()) - parseFloat($('#thetotal').val());
}
});
$('#thechange').html(total);
});
})(jQuery);
</script>
I'm not sure why the 3rd instance which is inside a modal window doesn't auto update at all given ive just made a separate jquery class for it. Thanks in advance for further suggestions.
$('.calchange').change(function(){
var total = 0;
$('.calchange').each(function(){
if($(this).val() != '') {
total += parseFloat($(this).val());
}
});
var totalFinal = total - parseFloat($('#thetotal').val());
$('#thechange').val(totalFinal);
});

JavaScript - Taking user input and using in calculation to validate value

I have a modal that allows users to 'refuel' by filling out a form where they can input the amount of fuel to add, however the maximum fuel amount is 180 litres, so if the existing fuel is 170 litres (the existing fuel value will be retrieved from a database), and the user tries to add 20 litres, it should produce an error. I've got some code already, but it's not producing the error. If anyone could point out the issue it would be greatly appreciated.
$(document).ready(function() {
$('#fuel').blur(function() {
if (!ValidateFuel()) {
e.preventDefault();
}
});
$('#auth_form8').on('submit', function(e) {
if (!ValidateFuel()) {
e.preventDefault();
}
});
});
function ValidateFuel() {
var IsValid = false;
var fuel_to_add = $('#fuel').val();
var current_fuel = '100'; // this value will be retrieved from database
var fuel_once_added = Number(current_fuel) + Number(fuel_to_add);
if (fuel_once_added > 180) {
$('#alertInvalidFuel').show();
IsValid = false;
} else {
$('#alertInvalidFuel').hide();
IsValid = true;
}
return IsValid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-success" role="button" data-target="#confirm-refuelG-EEGU" data-toggle="modal"><em class='fa fa-plus'></em></a>
<div id="confirm-refuelG-EEGU" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Fuel G-EEGU</h4>
</div>
<div class="modal-body">
<form name="auth_form8" id="auth_form8" method="post" action="action_refuel.php">
<p>This action cannot be undone.</p>
<hr>
<input class="form-control" id="aircraft_id" name="aircraft_id" value='1' type="hidden">
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">
Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
<div style="display:none;" class="alert alert-danger" id="alertInvalidFuel">
<p>Fuel will exceed 180 litres.</p>
</div>
<hr>
<div class="form-group has-feedback" name="auth_code8" id="auth_code8">
<label for="auth_code8" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input8" autocomplete="new-password" name="refuel_auth_code" type="password" required>
<span class="form-control-feedback glyphicon" id="iconBad8"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-success">Add Fuel</button>
</div>
</form>
</div>
</div>
</div>
JSFiddle Demo
The problem is here:
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
Your div has id="fuel" and so does the input. Remove the id from the div or make it unique. Also, there is no name attribute for div elements, you should remove that as well.

Show/Hide div using bootstrap checkbox - require inputs to be entered only if checkbox is checked

Ok, I've been having a really weird problem using a checkbox which collapses a hidden div using bootstrap.
if I have data-toggle="collapse" in the checkbox input attribute section, the Div Collapses but requires that every single one of the inputs inside it be filled out.
If data-toggle="collapse" is not there, the hidden div doesn't collapse, and if the checkbox is checked it requires the inputs to be entered and if it's left unchecked I can submit the form without the inputs being entered. (desired action, but the div doesn't hide or show when the checkbox is checked)
How do I hide/show the div when the checkbox is unchecked/checked AND only require the inputs if the box is checked?
I'm using this as the HTML:
<div class="col-md-1">
<input type="checkbox" onclick="ChangeShip()" href="#moreabout" data-toggle="collapse" aria-expanded="false" aria-controls="moreabout" class="form-control" id="chShipAdd" name="chShipAdd" value="no">
</div>
<label for="chShipAdd" class="col-md-3 control-label">Shipping Information?</label>
<div id="shipadddiv" style="visibility: hidden;">
<div class="collapse" id="moreabout" >
<div class="form-group">
<div class="col-md-12">
<br>
<input id="sStreet" name="sStreet" type="text" placeholder="Street Name (required)" class="form-control shipClass" required>
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<input id="sCity" name="sCity" type="text" placeholder="City (required)" required class="form-control shipClass">
</div>
<div class="col-md-4">
<input id="sState" name="sState" type="text" placeholder="State (required)" required class="form-control shipClass">
</div>
<div class="hidden-lg hidden-md"> </div>
<div class="col-md-4">
<input id="sZipcode" name="sZipcode" type="text" placeholder="Zip (required)" required class="form-control shipClass">
</div>
</div>
</div>
</div>
and the javascript:
function ChangeShip() {
if (!(document.getElementById('chShipAdd').checked)) {
document.getElementById('shipadddiv').style.visibility="hidden";
$(".shipClass").prop("disabled",true);
}
else {
document.getElementById('shipadddiv').style.visibility="visible";
$(".shipClass").prop("disabled",false);
}
}
Any solution that WORKS will be acceptable. I've bashed my brain all day trying to do this simple action. I've tried .prop .attribute .setAttribute .removeAttribute, and much much more.
Any Advice?
You can use jquery to solve this quickly. You can wrap your inputs for change ship and give it and id. And let jquery do the rest.
var form = $('#myForm'),
checkbox = $('#changeShip'),
chShipBlock = $('#changeShipInputs');
chShipBlock.hide();
checkbox.on('click', function() {
if($(this).is(':checked')) {
chShipBlock.show();
chShipBlock.find('input').attr('required', true);
} else {
chShipBlock.hide();
chShipBlock.find('input').attr('required', false);
}
});
See this jsfiddle for your problem. This should help you.
your click event will toggle the display and the disabled, but when the form is loaded you will have hidden content that is not disabled.
simply call the function on document.ready
function ChangeShip() {
var show = $('#chShipAdd').prop('checked');
$('#shipadddiv').toggle(show);
$("#shipadddiv .shipClass").prop("disabled", !show);
}
$(ChangeShip); // call on document.ready
or simply add the disabled attribute to those elements so that the initial form state is valid
If the [required] attribute is still triggered on a [disabled] element you could juggle the attribute value
function ChangeShip() {
var show = $('#chShipAdd').prop('checked');
$('#shipadddiv').toggle(show);
$("#shipadddiv .shipClass").each(function(){
if (!('_required' in this))
this._required = this.required;
this.disabled = !show;
this.required = (show) ? this._required : false;
});
}
Try to do this :
HTML :
<div class="col-md-1">
<input type="checkbox" onclick="ChangeShip()" href="#moreabout" data-toggle="collapse" aria-expanded="false" aria-controls="moreabout" class="form-control" id="chShipAdd" name="chShipAdd" value="no">
</div>
<label for="chShipAdd" class="col-md-3 control-label">Shipping Information?</label>
<div id="shipadddiv" style="visibility: hidden;">
<div class="collapse" id="moreabout" >
<div class="form-group">
<div class="col-md-12">
<br>
<input id="sStreet" name="sStreet" type="text" placeholder="Street Name (required)" class="form-control shipClass" required>
</div>
</div>
<div class="form-group">
<div class="col-md-4">
<input id="sCity" name="sCity" type="text" placeholder="City (required)" required class="form-control shipClass">
</div>
<div class="col-md-4">
<input id="sState" name="sState" type="text" placeholder="State (required)" required class="form-control shipClass">
</div>
<div class="hidden-lg hidden-md"> </div>
<div class="col-md-4">
<input id="sZipcode" name="sZipcode" type="text" placeholder="Zip (required)" required class="form-control shipClass">
</div>
</div>
</div>
</div>
JQUERY :
$('#chShipAdd').change(function() {
if ($('#chShipAdd').prop('checked')) {
$('#shipadddiv').show();
} else {
$('#shipadddiv').hide();
}
});

Form doesnot post data edited from jQuery

i'm having a very simple app which includes a form and 2 buttons.'
Description
When the user clicks the first button the site checks if he has a discount coupon and if he has then it calculates the discount ammount based on the coupon. Thats pretty simple. If the user doesn't enter a code the the precess continues normaly.
The problem
With the data i'm posting i'm also posting the coupon field. If the user has entered a valid coupon then i disable the coupon input with jQuery and withit i also disable the ammount field. That causes a problem which makes the fields edited with jQuery "unpostable".
For example if you dont enter a coupon code then the field stays unlocked and jQuery never edits it.
The code
<form class="form-horizontal row-fluid" action="<?= base_url() . 'transactions/new' ?>" method="POST" id="form" name="form">
<div class="control-group">
<div class="alert js_hidden" id="psc_val_warning">
Παρακαλούμε εισάγεται το ποσό που αντιστοιχεί στα PINS
</div>
<label class="control-label" for="basicinput">Συνολικό ποσό</label>
<div class="controls">
<div class="input-append">
<input type="number" name="psc_val" class="span8" id="psc_val" required><span class="add-on">€</span>
</div>
</div>
</div>
<div class="control-group">
<div class="alert alert-error js_hidden" id="coupon_error">
Το κουπόνι δεν είναι έγκυρο!
</div>
<div class="alert alert-success js_hidden" id="coupon_success">
Το κουπόνι εξαργυρώθηκε με επιτυχία!
</div>
<label class="control-label" for="basicinput">Κουπόνι</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">#</span><input class="span8" id="coupon_code" type="text" name="coupon_code" maxlength="11">
</div>
</div>
</div>
<hr>
<div class="control-group">
<label class="control-label" for="basicinput">Σημειώσεις</label>
<div class="controls">
<textarea class="span8" rows="5" name="notes"></textarea>
</div>
</div>
<hr>
<center>
<button class="btn btn-large btn-success js_hidden" id="proceed_btn" onclick="submit_form()">Proceed</button>
</center>
</form>
<center>
<a class="btn btn-large btn-info" onclick="validate()" id="check_btn">Check</a>
</center>
The JS part
function display_proceed_btn() {
$("#psc_val").prop('disabled', true);
$('#check_btn').fadeOut( "slow", function() {
$('#proceed_btn').fadeIn( "slow", function() {
});
});
}
function submit_form() {
$('#form ').submit();
}
there is the other part which takes the coupon and uses the API to see the discount value but it does pretty much the same thing $("#coupon_code").prop('disabled', true);
Add the coupon code to a hidden field once you disable the input field.
Remember to actually recalculate the final amount on the server and not trusting any user editable field ;-)

Categories