Bootstrap Searchable Drop down - javascript

New to web development. I am working on a ASP MVC app. Currently, I am working on a form, where I need a drop down box, that is searchable. Where I can click the drop down and see all the choices and also search it.
The data for this will be an Ajax request, that has a list of Json Objects, with properties Id and Name. "Id" will be the Option value and "Name" will be Option Name.
I looked through rest of the question regarding this, mostly the solutions were around Angular and ASP Web Forms.
I am not using Angular, please suggest solutions where I can use Bootstarp and Jquery to accomplish the same. Any external plugin suggestions?
Below is the current code:
<h1 class="col-sm-10 text-center">Data Import</h1>
<hr class="col-sm-10"/>
<form class="col-sm-10 form-horizontal">
<div class="form-group">
<label for="test" class="control-label col-sm-2">Name</label>
<div class="col-sm-10">
<select class="col-sm-10 form-control" id="tenantList">
<option value="1">Value</option>
</select>
</div>
</div>
</form>
<script>
$.ajax({
url: 'api/Tenant'
})
.done(function (data) {
$('#tenantList').html("");
var list = "";
$(data).each(function(idx, object) {
list += "<option value = " + object.id + ">"+object.name+"</option>";
});
$('#tenantList').html(list);
})
.fail(function() {
console.log("Problem :(");
});
</script>
Thanks.

Checkout Jquery UI' Combobox:
https://jqueryui.com/autocomplete/#combobox

Related

Repeat Selectize select field

I have a form where the user can input multiple addresses, city, street+nbr and country.
For this field to be repeated I use the jquery repeater library. For the city field I want to use a selectize input field.
I am trying to repeat those 4 fields when clicking on the button, it copies everything correctly but the selectize field does not contain inputs (i guess this is because they have the same id?) but I don't know how to instantiate another selectize instance on that object.
This is my code:
HTML:
<div class="row">
<div class="form-group col-12 mb-2 address-repeater">
<div data-repeater-list="stcity">
<div class="input-group mb-1" data-repeater-item>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label for="companystreet"><?=lang("flow_company_street")?></label>
<input type="text" id="companystreet" class="form-control" placeholder="<?=lang("flow_company_streetname")?>" name="companystreet" required data-validation-required-message="<?=lang("flow_company_street_validation")?>">
<div class="help-block font-small-3"></div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="companystreetnumber"><?=lang("flow_company_nbr")?></label>
<input type="text" id="companystreetnumber" class="form-control" placeholder="<?=lang("flow_company_streetnbr")?>" name="companystreetnumber" required data-validation-required-message="<?=lang("flow_company_nbr_validation")?>">
<div class="help-block font-small-3"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="companycity"><?=lang("flow_company_city_or_commune")?></label>
<select id="companycity" class="companycity-select" name="companycity" autocomplete="new-password" required data-validation-required-message="<?=lang("flow_company_city_or_commune_validation")?>">
<option value="" selected><?=lang("flow_company_select_city_or_commune")?></option>
<?php
foreach ($citiesbe as $city) {
//Values are prefilled from javascript
$key = strtolower($city->name_nl) . "," . $city->zip_code;
echo "<option value=\"$key\"> $city->name_nl ($city->zip_code)</option>";
}
?>
</select>
<div class="help-block font-small-3"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="companycountry"><?=lang("flow_company_country")?></label>
<select id="companycountry" class="companycountry-select" name="companycountry" autocomplete="new-password" disabled>
<option value="BE" selected><?=lang("flow_company_country_belgium")?></option>
</select>
</div>
</div>
</div>
</div>
</div>
<button type="button" data-repeater-create class="btn btn-primary">
<i class="ft-plus"></i> Add new address
</button>
</div>
Javascript:
// Custom Show / Hide Configurations
$('.address-repeater').repeater({
show: function () {
$(this).slideDown();
},
hide: function(remove) {
$(this).slideUp(remove);
}
});
Since the button is not the selectize element, I don't know how to assign it to the newly created element.
Funny, I ran into a similar problem, but couldn't find a solution, so I had to work it out myself. Here's an explanation to the solution I applied to get selectize and jquery.repeater to work nicely.
First, checking through the browser console, you'll find out that selectize removes all the select options except the empty option, and uses it to populate it's own dropdown which is generated via javascript. This becomes a problem for jquery.repeater because it only repeats or creates a duplicate based on the initial page load, and not after. So, what gets repeated is the only select option left in the select element, which in this case (unfortunately) is the empty select option. Here's a pen explaining this, feel free to toggle the category targeting selectize in the select element to see for yourself.
So, here are the steps I took to get it to work nicely:
On repeating of the form (show() of the repeater instance), you'll need to delete the duplicated element completely from the DOM.
Create another select element(s) in the DOM with the preferred (or same) attributes/options.
Instantiate selectize on the newly created select element(s).
I'll suggest you add a class to the .form-group wrapper housing the .companycity-select select element. This will help to append a new select element at the exact place only, since there are other .form-group in the code. Check my solution below:
// Assuming your have the select element wrapper as <div class="form-group select-wrapper">
$('.address-repeater').reapeter({
show: function() {
$(this).slideDown();
// Remove the created element
$(this).find('.companycity-select').remove();
// Repeater rewrites your name attributes to avoid collisions within the same form,
// so we need to follow this same rule
// Get the length of the currently repeated items, to be used as the index for new elements
var count = $('div[data-repeater-item]').length;
// Create the new select element. The select name is based on the new name by repeater
var new_select_option = '<option value="" selected>Select city or community</option>';
var new_select_element = '<select id="companycity" class="companycity-select" name="stcity['+count+'][companycity]" autocomplete="new-password" required>'+new_select_option+'</select>';
// Append newly created element to DOM. Remember the new class added to the form-group?
$(this).find('.form-group.select-wrapper').append(new_select_element);
// Create a new instance of selectize on the new select element
$(this).find('.companycity-select').selectize({
// Populate your select options data via ajax,
// see docs: https://selectize.dev/docs.html
valueField: '',
labelField: '',
searchField: [],
options: []
});
}
});

Post form along with multiple files to Web API

I'm still new to how Web API 2.0 works but I'm starting to get the hang of things. The one issue I've been having though is how to post a form along with multiple files that the user uploaded to my controller.
I guess I mainly need help with how to use JavaScript or jquery with ajax to post all of the correct values.
Here is a snippit of my HTML:
<form id="CreateAnnouncementForm" class="form-horizontal">
<input type="hidden" name="announcementTypeID"/>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="col-sm-2 control-label">Headline</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="headline" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">More Info</label>
<div class="col-sm-10">
<textarea class="form-control" name="moreInfo"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Attachments</label>
<div class="col-sm-10">
<input type="file" name="Attachments" multiple/>
</div>
</div>
</div>
</div>
</div>
</form>
Here is the JavaScript/jQuery/Ajax that I normally use to post my form to the controller:
onAnnouncementCreate: function () {
var form = $("#CreateAnnouncementForm");
var validator = $(form).kendoValidator().data("kendoValidator");
if (validator.validate()) {
var options = {
url: getApiUrl() + "/Announcement",
dataType: "json",
type: "POST",
headers: {
"Authorization": "Bearer " + getJwtToken(),
"LocationId": getCurrentLocation()
},
data: $(form).serialize(),
statusCode: {
200: function () {
$("#AnnouncementCreateModal").modal("hide");
announcementViewModel.reloadGrids();
},
400: function (response) {
toastr.options = { "positionClass": "toast-bottom-full-width";
toastr.error(response.responseText);
}
}
};
$.ajax(options);
}
}
Now I believe it would be best if I just created a ViewModel that contained both the ViewModel for all of the values in my form and have it contain an IEnumerable for the attachments that the users can upload within the form.
The trouble I'm having though is correctly adding the attachments to the form so that they map correctly.
My ViewModel will look like this:
public class AnnouncementCreateViewModel
{
public AnnouncementViewModel Announcement { get; set; }
public IEnumerable<HttpPostedFileBase> Attachments { get; set; }
}
Of course I would then need to change the names in my form to reflect the new model.
If anyone can help me on how to post them to my controller that would be much appreciated as that's the only thing I'm still struggling with.
Since this turned out to be more difficult than I thought it would be. I decided to go an alternative route.
Since I'm already using the Kendo UI framework, I am now using the Kendo Upload widget to handle the uploading of my files. I have it asynchronously upload the files to my Web API controller and then I have a separate action to handle the form when it's submitted.
Of course I'm welcome to other answers as well that might be able to solve this issue by posting all of the data in one call but for now, this will do.

How do I correctly use select2 Jquery to search and select data?

Hi All I have been trying to apply this Select2 jQuery plugin for sometime now but it doesn't work. I followed the demo example given but it always shows an error like this. The html select option have null data.
project.html
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label">Customer Name</label>
<div class="col-lg-10 col-md-9">
<select required class="form-control customer-options" name="ptype" ng-model="projDetails.cname">
<option ng-repeat="cusName in cusNames" value="{{cusName.Id}}">{{cusName.Name}}</option>
</select>
</div>
</div>
Here is the jQuery implementation.
project.js
$(document).ready(function () {
$(".customer-options").select2();
});
$scope.createProject = function () {
var projDetails = {
pname: $scope.projDetails.pname,
cname:$scope.projDetails.cname,
ptype: $scope.projDetails.ptype,
desc: $scope.projDetails.desc,
std: $scope.projDetails.std,
etd: $scope.projDetails.etd,
status:"Not assinged"
};
ProjService.Project(projDetails, function (res) {
console.log(res, data);
});
I gave last couple of codes so that anyone can understand that I bind data. :)
The error is this :=
angular.js:13642 query function not defined for Select2 s2id_cname
How to make this correctly work. Help would be appreciated. Thanks
try this, it works for me. You can convert it to anularjs or use as it is.
http://ionicmobile.blogspot.in/2015/10/jquery-select2-editable-with-dynamic.html

Add HTML form on button click

I have an HTML form in my website/application.
The form has lots of fields of input text, select, and PHP code, as well, to fill drop down values.
Is there any way I can clone/create the same form when the user clicks on the Add button? Let's say, if the user clicks 5 times, it would have five forms on the UI.
HTML
<form id = "buyerForm" role="form" method="POST" enctype="multipart/form-data" style="margin-top:30px;">
<span class="customerno" style="font-size: 22px;">Buyer 1 (Form 2)</span>
<div class="form-group">
<label>APPLICANT DETAILS</label>
</div>
<div class="form-group">
<label>Mr. / Mrs</label>
<select class="form-control" name="jnameTitle" id="jnameTitle">
<option>Please Select One</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="MS">MS</option>
</select>
</div>
// similar fields are omitted to reduce the complexity
<div class="form-group">
<label>Address</label>
<textarea name="jaddress" id="jaddress" class="form-control" cols="80" rows="5" ></textarea>
</div>
<button type="submit" name="jointCustomers" id="jointCustomers" class="btn btn-success btn-lg btn-flat">Save</button>
<button type="reset" class="btn btn-default btn-lg">Reset</button>
</form>
if you're using jQuery (or dont mind using it) you could just use clone to add the form again to the parent container
$("#youButton").click(function(){
$("#buyerForm").clone().appendTo("#yourParentWrapper");
});
see this fiddle
Yes, there is a way.
Lets say you have the main page -> mainPage.php, where you can have a list and the button (addForm).
Then you will have your myform.php page that will generate a form it self.
The process is very simple.
You press the btn AddForm
You make a request using AJAX against your function that generate the form in the myform.php page.
Inside your AJAX code, you will add your form inside the list object.
Note: This is only a basic idea. You must adapt the code to your needs.
//Your main page, will contain a list.mainPage.php
<ul id="myFORMS">
<li><button id="idBtnElement" type="button">AddForm</button></li>
</ul>
//Your php code to create the form. You can create a function if you want
$arrToJSON = array(
"myFormHtml"=>"You will put your HTML form code here"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idBtnElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_ADDFORM"
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "myFormGenerator.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
formStrHtml=dataset[index].myFormHtml;
}
//JavaScript
//Here you can grab formStrHtml in apped at the end of the list in your main page.
$("#myFORMS ul").append('<li>'+formStrHtml+'</li>');
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}

how do i pass this bootstrap html form to next page with javascript?

i have a simple form with a gender drop down and a temperature dropdown and i want them to go to the next page and just simple be outputted to the screen. I think i may have to change my save button as well. must use javascript with i could use php lol
<div class="form-group">
<label for="sel1">Gender:</label>
<select class="form-control" id="gender">
<option>Male</option>
<option>Female</option>
</select>
</div>
<div class="form-group">
<label for="sel1">Temperature (Degrees):</label>
<select class="form-control" id="gender">
<option>Fahrenheit</option>
<option>Celcius</option>
</select>
</div>
<div style="text-align: center;"> Save Settings</div>
I think that you can use local storage for this:
localStorage.setItem('showInTheNextPage', $('.form-group').html());
Then, in the next page:
var fromPrevPage = localStorage.getItem('showInTheNextPage');
$('.form-group').html(fromPrevPage);
UPDATE : Illustration
https://stackoverflow.com/a/16264547/1845408
Page 1: http://jsfiddle.net/Xotic750/dfqsK/
Page 2: http://jsfiddle.net/Xotic750/ayvPq/
may be you do not need to pass to the "next" page? may be you need to reload rest (or some part of the page in background), namely use ajax?
{your form html here}
Save Settings
<div id="content"></div>
<script >
function reload(evt) {
var body = $('form#some-form').serializeArray();
var xhr = $.post(window.location.origin+'/api'+window.location.pathname, body )
.done(function(data) {
console.log( "success" );
$('#content').html(data);
})
.fail(function() {
console.log( "error" );
});
}
</script>
assuming use of JQuery.

Categories

Resources