Selectpicker validator forcing user to select a value - html

I am currently developing a web application using ASP.NET Core v2.2.
I'm having troubles in one of my forms where I have several "multiselect" (using bootstrap-select selectpicker). The problem is that the form doesn't allow users to not select any options in a multiselect before being submitted.
Here's an example of one of my multiselects that I'd like to be "optional" :
<form asp-controller="Home" asp-action="Index" method="post" role="form" id="bsForm">
<div class="row row-mb-2">
<div class="col col-sm-4">
<label class="col-form-label" style="float:left">Product :</label>
</div>
<div class="col">
<select asp-for="product.ProductId"
class="form-control selectpicker" multiple data-live-search="true"
style="display: initial !important"
asp-items="#(new SelectList(ViewBag.ListOfProducts,"ProductId","ProductName"))">
<option data-hidden="true"></option>
</select>
</div>
</div>
<div class="row">
<input type="submit" value="Submit" class="btn btn-primary" style="width:25%" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker();
});
</script>
When I'm looking into it (by inspecting the element), it looks like there is some kind of validator running and forbidding users to let these selectpickers not selected.
If you have any idea of how to disable this validator (or just the fact of forcing users to select a value), I would be grateful.
Thanks in advance !
Edit :
So I've found something that does the trick. I think that by doing so I removed every existing validations conditions. Here's what I did :
<script type="text/javascript">
$(document).ready(function () {
$('#bsForm').validate({
rules: {
}
});
});
</script>
Since this is kind of a butchering solution, I'm still looking for a better solution.

Related

Can't submit the page even though using preventDefault in laravel

I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action) My form inputs are filled dynamically here is my code.
HTML
<div class="modal-body">
<form id="update_form">
<!-- loaded below -->
</form>
</div>
another request that fill my form data
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<input type="hidden" name="request_type" value="{{RegisterTypesNames::Faculty}}">
<label>University</label>
<select name="university" class="custom-select" id="university{{$action}}">
<option selected value="1">University of Cansas</option>
</select>
</div>
<div class="form-group col-md-6">
<label>Faculty</label>
<input type="text" class="form-control" name="faculty" id="faculties{{$action}}">
</div>
<div class="form-group col-md-6">
<label>Init</label>
<input type="text" class="form-control" name="short_name" id="short_names{{$action}}">
</div>
</div>
<button type="submit" class="btn btn-primary"><span class="fa fa-save"></span> Save</button>
And jquery code
$('#update_form').submit(function (e) {
$.ajax({
url: '/update_data',
type: "POST",
data: $('#update_form').serialize(),
dataType: "json",
success: function (data) {
console.log(data.result);
}
});
e.preventDefault();
});
Note: I use multiple partial forms like this all others works fine
I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action)
Interpretation: the statements "page refreshed" and "used preventDefault" indicate that the problem is that the code inside the $("#id").submit( is not firing and the page's default submit is kicking in hence the "page refreshed".
As the jquery event is not firing, it likely means that the HTML does not exist when the script runs. This can usually be handled by putting in a doc.ready; OP indicates that it's already in doc.ready.
The alternative is to use event delegation. Though it's not clear if the code is running before the HTML is generated or if the HTML is added after (subtle difference).
The solution for event delegation is to use:
$(document).on("submit", "#update_form", function(e) {
e.preventDefault();
$.ajax({...
});

Can't make the validation work in Bootstrap

I'm trying to implement validation by Bootstrap and I've pasted the following sample on my page:
<div class="form-group has-success">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control form-control-success" id="inputSuccess1">
<div class="form-control-feedback">Success! You've done it.</div>
<small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>
I can see that the appearance of the input control has changed (it's a bit rounded and much more aesthetic now) but it still doesn't show the green border as can be seen on the page linked to. The Bootstrap I'm linking to is pointed out as follows.
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" />
I have tried to google for this issue but to no avail. I have a fiddle illustrating the issue.
What can I do about it? What am I missing?
Bootstrap 5 (Update 2021)
Since jQuery is no longer required for Bootstrap 5, it's easy to do client-side validation with vanilla JavaScript. The docs include a generic code example that should work on all forms with needs-validation..
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
Bootstrap 5 Form Validation Demo
Bootstrap 4 (Original Answer)
Validation has changed as of the Bootstrap 4 beta release.
The valid state selectors use the was-validated class which would be added dynamically after validating the form via client-side JavaScript. For example...
<form class="container was-validated" novalidate="">
<div class="form-group">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control" name="i1" id="inputSuccess1">
<div class="valid-feedback">Success! You've done it.</div>
</div>
<div class="form-group">
<label class="form-control-label" for="inputSuccess2">Input with danger</label>
<input type="text" class="form-control" name="i2" required="" id="inputSuccess2">
<div class="invalid-feedback">That didn't work.</div>
</div>
<div class="">
<button type="submit" class="btn btn-secondary">Text</button>
</div>
</form>
https://codeply.com/go/45rU7UOhFo
Form Validation Example Demo - Bootstrap 4.0.0
As explained in the docs, if you intend to use server-side validation you can simply set the is-valid or is-invalid classes on the form-controls...
<form class="container">
<div class="form-group">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control is-valid" id="inputSuccess1">
<div class="valid-feedback">Success! You've done it.</div>
</div>
</form>
It appears the validation changes again in the final release version of Bootstrap 4: http://getbootstrap.com/docs/4.0/components/forms/#validation.
It becomes more complicated than I thought.
Custom style client side validation is recommended:
When validated, the form adds a class named was-validated.
Feedback messages are wrapped within .valid-feedback or .invalid-feedback.
For server-side validation:
No need for was-validated class on the <form> tag.
Add .is-valid or .is-invalid on the input control.
Add .invalid-feedback or .valid-feedback for the feedback message.
my simple way....
<input type="text" class="form-control" id="unombre"
placeholder="su nombre" name="vnombre" required
onblur="valida(this.id)">
<script>
function valida(v) {
var dato = document.getElementById(v).value
document.getElementById(v).className +=' is-valid';
}
</script>

How to set up search option for a charity website

I wonder if you could help me, I'm a graphic designer but trade with super basic HTML experience.
I'm volunteering for a small charity in Birmingham who is looking to create a community planning tool, I said I'll try and help design it, for free of course.
One of main options on the site is people can search to get resources. This is the interface:
Is there a really simple way to link this up?
For example, if someone clicked 'Balsall Heath Ward' and then 'Community' in the drop down menus then clicked search now it will take them to BHcommunity.html which will have resources. Same if somebody clicked 'Moseley Ward' and then clicked 'Sustainability' then search now, it would take them to MWsustainability.html. Does that make sense?
Basically I just need something that commands to point towards links, but I don't know where to start, can anybody give me some advice or help?
If anybody can help I can swop for free design support?
Thanks so much for the support!
Nath
Ps: Here is the code.
<h3 class="demo-panel-title">Fill out the relevant information:</h3>
<div class="col-xs-3"> <div class="form-group has-error"> <input type="text" value="" placeholder="What is your name?" class="form-control" /> </div> </div>
<div class="col-xs-3"> <div class="form-group has-success"> <input type="text" value="" placeholder="What is your email address?" class="form-control" /> <span class="input-icon fui-check-inverted"></span> </div> </div>
<div class="col-xs-3"> <div class="form-group"> <input type="text" value="" placeholder="What organisation are you associated with?" class="form-control" /> </div> </div>
<br/>
<div class="col-xs-3"> <h3 class="demo-panel-title">Which Ward do you want to explore?</h3> <select class="form-control select select-primary" data-toggle="select"> <option value="0">Moseley & Kings Heath Ward</option> <option value="1">Balsall Heath Ward</option> </select> </div>
<br/> <div class="col-xs-3"> <h3 class="demo-panel-title">What data do you need?</h3> <select class="form-control select select-primary" data-toggle="select"> <option value="0">Choose one</option> <option value="1">Local economy</option> <option value="2">Transport</option> <option value="3">Leisure</option> <option value="4" selected>Housing</option> <option value="5">Community</option> <option value="6">Planning</option> <option value="7">Sustainability</option> </select> </div> <br/>
I'd need to add a way to search
I have put together a reasonably simple example of how to do this, linked below. Firstly I have modified your HTML a little, changing the value attributes of your options to be more descriptive. I have added some IDs to elements for ease of location without the need for jQuery as you can see in the small extract here:
<div class="col-xs-3">
<h3 class="demo-panel-title">What data do you need?</h3>
<select id="data-type-select" class="form-control select select-primary" data-toggle="select">
<option value="0">Choose one</option>
<option value="economy">Local economy</option>
<option value="transort">Transport</option>
<option value="leisure">Leisure</option>
<option value="housing" selected>Housing</option>
<option value="community">Community</option>
<option value="planning">Planning</option>
<option value="sustainability">Sustainability</option>
</select>
</div>
In the javascript I have kept it as simple as possible, I hope you can see how I have gathered the information and used it to pick which html file you want to go to.
(function() {
function attachEvents () {
var submitButton = document.getElementById('ward-information-submit-button');
submitButton.addEventListener('click', submitButtonListener);
}
function submitButtonListener () {
getFormData();
}
function getFormData () {
var selectWardElement = document.getElementById('ward-select');
var selectDataTypeElement = document.getElementById('data-type-select');
pickDestination({
selectedWard: selectWardElement.options[selectWardElement.selectedIndex].value,
selectedDataType: selectDataTypeElement.options[selectDataTypeElement.selectedIndex].value
});
}
function pickDestination (options) {
if (options.selectedWard === 'moseley' && options.selectedDataType === 'economy') {
console.log('MWsustainability.html');
window.location = 'MWsustainability.html';
}
if (options.selectedWard === 'balsall' && options.selectedDataType === 'community') {
console.log('BHcommunity.html');
window.location = 'BHcommunity.html';
}
}
attachEvents();
}());
I have a working version of this here which includes some additional comments to hopefully help you make sense of it. You will need to extend this code to make it work for all of your cases and I'm sure there are other requirements you have which you could apply these concepts to. Keep me updated and I'll help you learn where I can.
I appreciate the offer of something in return but it is unnecessary, just keep paying it forward as you are now. Good luck!
https://jsfiddle.net/rvb56sx6/
You may consider making a JSON file or Javascript Object that holds string values for all the links you need. Then make a function that gets the values of the dropdown menus and chooses a link accordingly. Also, consider using Jquery to simplify this process. ( I use it in this example. Meaning that it must be used if you want to use the below function). You can include it by adding the below script tag in your html before you add the script tag for the file with the below function.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="path/to/JS/File/with/below/function"></script>
Javascript Object
var links = {
balsallHeathWard {
community: '<Link to community>'
...
},
...
}
Javascript Function
$(function goToLink() {
$(document).on('click', '#<submitButtonIdName>', function(){
var ward = $('#<wardChooserSelectTagIdName>').val();
var subchoice = $('#<subChoiceTagIDName>').val();
if(ward == "Balsall Heath Ward") {
if(subchoice == "Community") {
window.location.href = links.balsallHeathWard.community;
} else if ...
...
} else if ...
...
});
})();
The function would look something like the function above. I couldn't complete it because I don't have all the options and links that you have for what can be chosen from the charity website. But this is a general idea. It definitely needs work though, but I am willing to help if you need it (I have a soft spot for charities).

Angular binding with form automatically

jsfiddle demo: https://jsfiddle.net/zpufky7u/1/
I have many forms on the site, which was working fine, but just suddenly angular is binding all the forms with class="ng-pristine ng-valid"
Is this a setting or what can cause angular to auto-bind forms?
I'm using angular version: angular#1.4.7
Following is my form, as you can see there is no model inside form
<form name="app_bundle_notification_type" method="post">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<div class="checkbox">
<label class="required">
<input type="checkbox" id="app_bundle_notification_type_isNewsletter" name="app_bundle_notification_type[isNewsletter]" required="required" value="1" checked="checked">
Yes, I would like to receive email newsletter for new deals, coupons and news.
</label>
</div>
</div>
</div>
</div>
<div class="row m-y-1">
<div class="col-sm-12">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
<input type="hidden" id="app_bundle_notification_type__token" name="app_bundle_notification_type[_token]" class="form-control" value="b-_qAF6LHFy_GtPlsFG3iguhVXfGsj38TXm22Ke8j0k">
</form>
Angular app.js
define(['angular'], function() {
var app = angular.module("myApp", []);
app.init = function () {
angular.bootstrap(document, [app.name]);
};
return app;
});
So far I found the issue, if you do angular.bootstrap(document, [app.name]); then it is binding the form. it was not causing this issue before.
Presuming you are using a form tag around your form, Angular automatically adds those classes to each ng-model inside your form.
This allows you much more control over the elements inside your form to perform any validation or logic you want your form to capture or enforce before submitting.
Much of it is listed in the docs here
https://docs.angularjs.org/api/ng/directive/form
For this reason, Angular prevents the default action (form submission
to the server) unless the <form> element has an action attribute
specified.
New version accepts empty action="", check release version at https://github.com/angular/angular.js/pull/3776

HTML Angular form appears twice on page

I'm having what probably seems like a noob problem. I have a simple Angular controller that controls a form on a page. The markup for the form is pretty straight forward. When I load the page, I see the form rendered twice, rather tha once as it should be. What am I doing wrong here?
Here is my HTML:
<div class="container">
<div class="col-lg-12">
<div class="row">
<h2>CREATE</h2>
<div class="col-lg-6 col-lg-offset-2">
<div class="form-container" ng-controller="NewPostQuestionCtrl">
<form accept-charset="UTF-8" name="form.postQuestionForm" ng-submit="createPostQuestion(postQuestion)" class="new_post_item" novalidate>
<input name="utf8" type="hidden" value="✓">
<input name="authenticity_token" type="hidden" ng-model="postQuestion.token" ng-init="postQuestion.token='<%= form_authenticity_token %>'">
<input name="employer_id" type="hidden" ng-model="postQuestion.employer_id" ng-init="postQuestion.employer_id='<%= current_employer.id %>'">
<div class="form-group">
<label>Question</label>
<textarea class="question-textbox" name="question" ng-model="postQuestion.question" required></textarea>
</div>
<div class="form-group">
<label>Image</label>
<input class="" name="image" ng-model="postQuestion.image" type="file" required>
</div>
<div class="form-group">
<label>Publish Question</label>
<select class="" name="published" ng-model="postQuestion.published" required>
<option value="true">Publish</option>
<option value="false">Don't Publish</option>
</select>
</div>
<input class="submit-btn" name="commit" type="submit" value="Publish Post" ng-disabled="form.postQuestion.$invalid">
</form>
</div>
</div>
</div>
</div>
</div>
Here is my controller:
app.controller('NewPostQuestionCtrl', ['$scope', '$http', function($scope, $http) {
$scope.form = {}
$scope.postQuestion = {
token: $scope.token,
employer_id: $scope.employer_id,
question: $scope.question,
published: $scope.published,
image: $scope.image
};
}]);
Thanks!
Do you have the full HTML for your application to hand? Is it only the form that is rendered twice or also the h2 element? Is it possible you have the ng-view directive twice in your markup?
Hope that helps!
I don't think this will help anyone, but I figured out my problem and it was a really obvious oversight.
I have two <%= yield %> tags in my application.html.erb that are nested inside an if/else statement. The second tag was outside the statement, which was evaluating to true, causing my partial to be rendered twice.
I think it is loading twice.
Check in your .js file where you map the urls with controller. If you have the controller set in the app.js or any_file.js(where you map url with controller and views), you dont have to include the ng-controller in the html..