Dynamically add dropdown and dropdown fields - javascript

EDIT 001:
added:
- event.preventDefault(); and anchors instead of buttons
<div class="edit-area">
<div class="controls">
+
-
</div>
</div>
Now the page +or -won't make the page send the form, but now it does nothing :s
I'm working on a contact form, but I have a few problems/questions.
I want to dynamically add fields when they press a button (+)
And off course they need to be able to delete this when needed... (-)
When I press the + button now, it tries to act like a submit button and sends the form...
Script
<script>
(function($) {
"use strict";
var itemTemplate = $('.example-template').detach(),
editArea = $('.edit-area'),
itemNumber = 1;
$(document).on('click', '.edit-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[project]').attr('project', function() {
return $(this).attr('project') + '_' + itemNumber;
});
++itemNumber;
item.appendTo(editArea);
});
$(document).on('click', '.edit-area .rem', function(event) {
editArea.children('.example-template').last().remove();
});
$(document).on('click', '.edit-area .del', function(event) {
var target = $(event.target),
row = target.closest('.example-template');
row.remove();
});
}(jQuery));
</script>
HTML
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Your name
<input type="text" name="name2" id="name" value="<?php echo $_SESSION['realName']; ?>" placeholder="Your name" readonly/>
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(narrower)">
Order tickets for a project.
</div>
</div>
<div class="example-template">
<div class="row uniform 50%" id="readroot">
<div class="4u 12u(narrower)">
<select name="project" id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option disabled selected>Select a project</option>
<option value="Smile">Project Smile</option>
<option value="Sand">Project Sand</option>
<option value="Schmuck">Project Schmuck</option>
</select>
</div>
<div class="4u 12u(narrower)">
<select id="ddl2" name="date">
<option disabled selected>Select a date</option>
</select>
</div>
<div class="2u 12u(narrower)">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' name="amount" id="currentamount" value="" placeholder="Amount" />
</div>
</div>
<div class="edit-area">
<div class="controls">
<button class="add">+</button>
<button class="rem">-</button>
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice1" value="10" placeholder="" />
</div>
</div>
<div class="row uniform">
<div class="12u">
</div>
</div>
<div class="4u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
Image of the form (id and name are not shown here)

Change your buttons to anchors:
+
-
And then in your javascript, when clicked, be sure to call preventDefault() to stop it from behaving like a standard link.
$(document).on('click', '.edit-area .rem', function(event) {
event.preventDefault();
editArea.children('.example-template').last().remove();
});
$(document).on('click', '.edit-area .del', function(event) {
event.preventDefault();
var target = $(event.target),
row = target.closest('.example-template');
row.remove();
});
I think alternatively, you can add a type to the button so it doesn't default to a submit type (but don't quote me on that):
<button type="button" class="add">+</button>

Related

Dynamic multiselect feature

I am creating the fields dynamically in HTML using this JS, and in multiselect I'm using bootstrap multiselect here is the code https://bootsnipp.com/snippets/Ekd8P when I click on the add more button it creates the form dynamically.
js code for creating a form dynamically :
$(function() {
// Remove button
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="remove"]',
function(e) {
e.preventDefault();
$(this).closest('.form-horizontal').remove();
}
);
// Add button
var i = 1;
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-horizontal:first-child').clone();
new_field_group.find('input').each(function() {
if (this.name == 'tags[0]') {
$(this).tagsinput('destroy');
$(this).tagsinput('removeAll');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="form-group"]');
new_container.find(".bootstrap-tagsinput:first").remove();
} else {
$(this).val('');
}
});
new_field_group.find('select').each(function() {
if (this.name == 'addons[0]') {
$(this).multiselect('rebuild');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="multiselect-native-select"]');
new_container.find(".multiselect-native-select > .multi").remove();
} else {
$(this).val('');
}
});
i += 1;
container.append(new_field_group);
}
);
});
and html code for form elements:
<form action="" method="post" novalidate="novalidate" enctype="multipart/form-data">
{{ csrf_field() }}
<div data-role="dynamic-fields">
<div class="form-horizontal">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Name1" name="Name[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Price" name="Price[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Select Food Type</label>
<div class="col-sm-8">
<select id="select1" class="form-control" name="select[]" required>
#foreach($types as $type)
<option value="{{$loop->iteration}}">{{$type->food_type_name}}</option>
#endforeach
</select>
<p class="help-block" data-toggle="tooltip" data-placement="bottom" title="xyz"><i class="md md-info"></i></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Dish Description</label>
<div class="col-sm-8">
<textarea name="Description[]" id="field-value" class="form-control" rows="1"></textarea>
</div>
</div>
</div>
<div class="col-sm-4 contacts">
<div class="form-group">
<label class="col-sm-3" for="rolename">Add Addons</label>
<div class="col-sm-8">
<select id="dates-field2" class="multiselect-ak form-control" name="addons[0]" id="trigger3" data-role="multiselect" multiple="multiple">
#foreach($addons as $addon)
<option value="{{$addon->addonid}}">{{$addon->addon_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Tags</label>
<div class="col-sm-8">
<input type="text" value="" name="tags[0]" class="form-control" data-role="tagsinput" placeholder="e.g. spicy, healthy" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-4">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="Price2[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-5">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" class="trigger" id="trigger" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields" class="hidden_fields" style="display:none;">
<input type="text" id="hidden_field" name="Price3[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
</div>
<br>
<button class="btn btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove">
Delete Item
</button>
<button class="btn ink-reaction btn-raised btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add">
Add More Items
</button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
<div class="form-group">
<button type="submit" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary" style="margin-top: -62px;margin-left: 160px;">Submit Items</button>
</div>
<!--end .form-group -->
</form>
The issue is that when I click on the add more item it reflects the multiselect dropdown twice as you see in this image.
I want that if I click on the add more item button it restates the multiselect dropdown as in the first state.
see this jsfiddle.net/akshaycic/svv742r7/7 it will clear all your doubt. on click plus button it is not reflect to "none selected" state it will remain in its initial state.
Any leads would be helpful. Thank you in advance.

Multiple two inputs and the inputs generated dynamically by jQuery

I have this form and this is my layout:
I want when the user enters the quantity the total input = qty*price.
My view
<?php $form=array('id'=>'myform');?>
<?php echo form_open('Order/submit',$form);?>
<div class="panel panel-default">
<div class="panel-heading">Customer Details</div>
<div class="panel-body">
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="invoice_number" placeholder="Invoice Number"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="branch" placeholder="Branch"/>
</div>
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term"">
<option value="cash">Cash</option>
<option value="bank">Bank</option>
<option value="other">Other</option>
</select>
</div>
</div><!--customer panel-Body-->
<div class="panel-heading">Invoice Details
</div>
<div class="panel-body">
<div id="education_fields">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option></option>
<?php
foreach($order as $row):
echo"<option data-price='$row->p_price' value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control qty" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control total" name="total[]" value="" placeholder="Total">
<div class="input-group-btn">
<button class="btn btn-success" type="button" onclick="education_fields();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="panel-footer"><small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another product field :)</small>, <small>Press <span class="glyphicon glyphicon-minus gs"></span> to remove the last product :)</small></div>
</div>
<button type="submit" class="btn btn-primary center-block">Checkout</button>
<?php echo form_close();?>
This is my first jQuery and that used to generate a new row by + button
<script>
var room = 0;
function education_fields() {
room++;
var objTo = document.getElementById('education_fields');
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass"+room);
var rdiv = 'removeclass'+room;
var medo='<div class="col-sm-3 nopadding"><div class="form-group"><select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]"><option></option><?php foreach($order as $row){ ?><option data-price="<?php echo$row->p_price;?>" value ="<?php echo $row->p_id; ?>"><?php echo $row->p_name; ?></option><?php } ?></select></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity"></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control price" name="price[]" value="" placeholder="Price"></div></div><div class="col-sm-3 nopadding"><div class="form-group"><div class="input-group"> <input class="form-control" name="total[]" placeholder="Total"/><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_education_fields('+ room +');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div><div class="clear"></div>';
divtest.innerHTML = medo;
objTo.appendChild(divtest);
$('select').selectpicker();
}
function remove_education_fields(rid) {
$('.removeclass'+rid).remove();
}
</script>
and this 2nd jQuery used to get product price from from drop-menu attributes and add that into price input.
<script>
function set_price( slc ) {
var price = slc.find(':selected').attr('data-price');
slc.parent().parent().next().next().find('.price').val(price);
}
$('#education_fields').on('change','select.selectpicker',function(){
set_price( $(this) );
});
</script>
var sample = $('#sample').html();
$('#sample').on('click', '.generate', function() {
$('#sample').append(sample);
});
$('#sample').on('change', 'select.selectpicker', function () {
// keyword this is your current select element
var select = $(this);
// each group of inputs share a common .form element, so use that to
// look up for closest parent .form, then down for input[name="price[]"]
// and set the input's value
select.closest('.form').find('[name^=price]').val(
select.find('option:selected').data('price')
// trigger input's keyup event (*)
).keyup();
});
// (*) note: input[type=text]'s onchange event triggers only after it loses focus; we'll use keyup event instead
// create onkeyup event on the qty and price fields
$('#sample').on('keyup', '[name^=qty], [name^=price]', function() {
// get related form
var form = $(this).closest('.form');
// get its related values
var qty = parseInt(form.find('[name^=qty]').val(), 10),
price = parseInt(form.find('[name^=price]').val(), 10);
// ensure only numbers are given
if (!isNaN(qty) && !isNaN(price)) {
// set the total
form.find('[name^=total]').val(qty * price);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample">
<!-- group all related blocks into a div .form -->
<!-- it makes it easier to reference in your JS -->
<div class="form">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option data-price=200 value=1>tes1</option>
<option data-price=218 value=2>tes2</option>
<option data-price=80 value=3>tes3</option>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control " name="total[]" value="" placeholder="total" readonly>
</div>
</div>
</div>
<button class="generate" type="button">Generate New Form</button>
</div>
Note, that I am lazy instead of doing [name="price[]"], I simply did [name^=price].
Edit changed onchange to keyup.

Second Time Checkbox Not Working

I have created a two javascript.
1.When i click the checkbox the input field is appeared and when i unchecked input field is disappeared.
2.Second is when i click the add more items the all fields are created one more time.
Now the problem is when is created a second and more items the checkbox is not working.
HTML Code:
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12">
<div data-role="dynamic-fields">
<div class="form-inline">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="Name1" placeholder="Food Name" name="Name1" style="width:120%;" required data-rule-minlength="2">
<label class="sr-only" for="field-name">Name</label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="field-value" placeholder="Description" style="width:120%;" required>
<label class="sr-only" for="field-value">Description</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<select id="select1" name="select1" style="width:130%;" class="form-control" required>
<option value=""></option>
<option value="1">Food Type 1</option>
<option value="2">Food Type 2</option>
<select>
<label for="select1">Food Type</label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" value="" class="form-control" data-role="tagsinput" placeholder="Tags" />
<label class="sr-only" for="field-tags">Tags</label>
</div>
</div>
</div>
<div class="row">
<div class="form-inline">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="Name1" placeholder="Price" name="price" style="width:120%;" required data-rule-minlength="2">
<label class="sr-only" for="field-name">Price</label>
</div>
</div>
<div class="col-md-2">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" id="trigger2" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields2">
<input type="text" id="hidden_field2" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-35px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
<div class="col-md-3">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" id="trigger" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields">
<input type="text" id="hidden_field" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-100px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
</div>
</div>
<button class="btn btn-icon-toggle btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove"> <span class="md md-delete"></span> </button>
<button class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add"> Add More Items </button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
</div>
<!-- /div.col-md-12 -->
</div>
<div class="form-group">
<button type="button" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary">Submit Items</button>
</div>
<!--end .form-group -->
</div>
Checkbox Js:
<script type="text/javascript">
$(function() {
// Get the form fields and hidden div
var checkbox = $("#trigger");
var hidden = $("#hidden_fields");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
// Make sure that the hidden fields are indeed
// hidden.
hidden.hide();
$("#hidden_field").val("");
}
});
});
$(function() {
var checkbox = $("#trigger2");
var hidden = $("#hidden_fields2");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
hidden.hide();
$("#hidden_field2").val("");
}
});
});
</script>
Add more items JS:
$(function() {
// Remove button
$(document).on('click', '[data-role="dynamic-fields"] > .form-inline [data-role="remove"]', function(e) {
e.preventDefault();
$(this).closest('.form-inline').remove();
});
// Add button
$(document).on('click', '[data-role="dynamic-fields"] > .form-inline [data-role="add"]', function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function() {
$(this).val('');
});
container.append(new_field_group);
});
});
page Screenshot:
There are a couple of problems here:
You are cloning elements and then trying to access them via the same ID (you should use class)
Your functions don't target just clicked element but any element with the selector.
You are cloning elements so you need bind the click event to a non-cloned element: e.g. via $(document).on
I've updated some of your code to demonstrate what I'm talking about. In the html, I've added classes in the trigger2 and hidden_fields2 elements and display:none style to the hidden fields so they are hidden by default.:
<div class="col-md-2">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-35px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
In the javascript, I've changed the function to run from a $(document).on event bind and used the element class instead of the id. I've also changed the code so it only effects the checkbox you change and the closest hidden elements:
$(function() {
$(document).on('change', '.trigger2', function(){
var checkbox = $(this);
var parent = checkbox.closest('.form-inline');
var hidden = parent.find(".hidden_fields2");
hidden.hide();
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
hidden.hide();
$(".hidden_field2").val("");
}
});
});
You need to use the same logic on your other functions and inputs.

Create border around dropdown

Problem: I would like to create a border surrounding a drop-down box if left blank when the user enters a zip code. Otherwise, leave it how it is.
Currently, how it works is if the user enters a zip code and selects the submit, an alert will pop up and results will not be displayed until user selects the miles. This only occurs if user selects to find a locations using a zip code. Otherwise, it will populate the results.
Here is the form along with the script:
$(document).ready(function(){
var $zip = $('#zip');
var $city = $('#city');
var $hospital = $('#hospital');
var $miles = $('#miles');
$zip.on("change",function(){
$('#city option[value=""]').prop('selected',true).trigger('input');
$hospital.val('').trigger('input');
});
$city.on("change",function(){
$zip.val('').trigger('input');
$miles.val('').trigger('input');
});
$hospital.on("change",function(){
$zip.val('').trigger('input');
$miles.val('').trigger('input');
});
$zip.one("change", function(){
$miles.val('').trigger('input');
});
});
function checkTextField() {
var distance = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if(zip && !distance){
var alertMessage = "Please Select Distance When You Are Entering A Zip Code.";
alert(alertMessage);
return false; //Does not submit form
}
else
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group"><!---<select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>--->
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance">
<option value={{v.value}} ng-repeat="(k , v) in miles track by $index">{{v.value}}</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" onclick="return checkTextField();" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
</div>
Ok, this should work.
Modified you checkTextField() function to highlight miles field if it is empty
document.getElementById("miles").style.border = " solid #000000"
Plus your miles dropbox has oninput tag as so
oninput = "unHighlight()"
Which calls the un-Highlight function to remove the box in case the value of it anything other than "".
reference: http://www.w3schools.com/jsref/event_oninput.asp
http://www.w3schools.com/js/js_htmldom_eventlistener.asp
$(document).ready(function() {
var $zip = $('#zip');
var $city = $('#city');
var $hospital = $('#hospital');
var $miles = $('#miles');
$zip.on("change", function() {
$('#city option[value=""]').prop('selected', true).trigger('input');
$hospital.val('').trigger('input');
});
$city.on("change", function() {
$zip.val('').trigger('input');
$miles.val('').trigger('input');
});
$hospital.on("change", function() {
$zip.val('').trigger('input');
$miles.val('').trigger('input');
});
$zip.one("change", function() {
$miles.val('').trigger('input');
});
});
function checkTextField() {
var distance = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if (zip && !distance) {
var alertMessage = "Please Select Distance When You Are Entering A Zip Code.";
document.getElementById("miles").style.border = " solid #000000"
alert(alertMessage);
return false; //Does not submit form
} else
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form">
<div class="form-group">
<input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" />
</div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select>
</div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<!---<select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>--->
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" oninput = "unHighlight()">
<option value={{v.value}} ng-repeat="(k , v) in miles track by $index">{{v.value}}</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group">
<input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" />
</div>
</div>
</div>
<div class="form-group">
<input class="btn btn-warning btn-block" onclick="return checkTextField();" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" />
</div>
<script>
function unHighlight() {
var miles = document.getElementById("miles").value;
try{
if(miles != ""){
document.getElementById("miles").style.border = "none"
}
}
catch(err)
{
document.getElementById("miles").style.border = "none"
}
}
</script>
</form>
</div>
</div>

Alert User field that is blank is required

Problem: I would like to be able to alert the user if a particular field is empty. Here is how the form looks:
When the user enters a zip code and selects search, I would like a pop up to display to alert the user to select a distance and not display the results. If the user enters hospital name and city drop down, I do not want the alert to appear. Only when the zip code is entered and when the search button is selected.
Here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance">
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
and here is the script that alerts when the miles is blank:
function validateForm() {
var x = document.forms["UrgentCareSearch"]["distance"].value;
if (x == "" || x=="null") {
alert("Please select distance");
return false;
}
UPDATE
I have done the following and it still does not work the way I want to (which is to show the alert when the search button is entered and when the user has entered a zip code. Meaning once the user has entered a zip code and click on the search button to populate the results, the alert will appear notifying to select the miles and the results will not show until user has entered how many miles and click search again):
function validateForm() {
var x = document.forms["UrgentCareSearch"]["miles"].value;
var $zip = $('#zip');
if ((x == "" && $zip != "") ||(x=="null" && $zip != "")) {
alert("Please select distance");
return false;
}
and this is what I when I used required:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return checkTextField()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option value=""></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
adding required to each of the input or select elements would prevent the form from being submitted if they are left blank
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" required /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" required>
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
Or there can jquery touch look at this
first give your form an id lets say myform
$(document).ready(function()
{
$('#myform').submit(function()
{
var name = $("#hospital").val();
var name = $("#city").val();
if(name == "" || name == " ")
{
alert("Please enter name");
return false;
}
if(city == "" || city== " ")
{
alert("Please enter city");
return false;
}
//Just like this and at the end when you are satisfied
$(this).submit();
});
});
From what I understand by your problem statement, you can do the following in your validation function.
function validateForm() {
var miles = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if (zip && !miles) {
event.preventDefault(); // This will prevent the form submit
alert("Please enter the Miles.");
return false; // Does't submit the form (for IE)
}
}
Also, when calling the function, just call the function directly.
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="validateForm();">

Categories

Resources