Make bootstrap-select dropdown required - javascript

I have dropdown list in my form which used bootstrap-select to show the dropdown. I want to make if user submit the form it will check the dropdown is have value or not. I already added required inside the <select> tag but nothing happen if I leave it empty and press submit button.
This is my code :
<div class="form-group">
<label for="location">Location</label>
<select name="location" id="location-form" required>
<option value="">Choose Location</option>
<?php foreach($location as $row) : ?>
<option value="<?=$row['location_id']?>"><?=$row['location_name']?></option>
<?php endforeach; ?>
</select>
</div>
How to make my select dropdown required and can validate it must filled in if user press submit button ? Thanks before.

A select always has a value set into it. Try using a radio group instead.
Check here for more information on a radio group. HTML5: How to use the "required" attribute with a "radio" input field

There is two way that helps me will share with you below.
Using this way also problem getting solved.
<form action="whatever" method="post" novalidate>
OR using this too
please try following code.
/* For checking the drop-down contain value of not use this. */
if(jQuery('#location-form').val() == ''){
alert('Please select the option for location');
}else{
return false;
}
I hope this will help you.
Thanks.

By using default bootstrap 4.* JS validations you can simply add to sezel
<select ... required="true">
and an empty option with value=""
<option value="">Select one</option>
In this way Bootstrap JS library check if is selected

Add "disabled" in yout first option(along with required in select tag) as:
<div class="form-group"> <label for="location">Location</label> <select name="location" id="location-form" required> <option value="" disabled>Choose Location</option> <?php foreach($location as $row) : ?> <option value="<?=$row['location_id']?>"><?=$row['location_name']?></option> <?php endforeach; ?> </select> </div>

I am new to coding but I have done a lot of research on this site and I found a solution (not so efficient but works). This solution is based on the fact that the html5 "required" attribute worked at least somewhat - it prevents you from proceeding next or submitting but nothing else other than that - e.g. no error message, no alert, nothing at all.
The idea of the solution is to use the "invalid-feedback" class to show an error message, make use of the fact that it won't show until you pass in a "d-block" class. Then use a couple of functions on click of a button.
$('#button').click(function () {
$('#id-error').hide(); //if there is indeed a html5 message showing, but it looks bad, then just hide it, if you inspect the msg, html has automatically generate this "id-error" id
if ($('#id').is(':disabled')){
$('#errormsg-id').removeClass('d-block');
} else if (!$('#id').val()){
$('#errormsg-id').addClass('d-block');
};
});
$('#id').change(function () {
if($('#id').val()){
$('#errormsg-id').removeClass('d-block');
};
});
<div class="form-group ">
<select id="id" class="selectpicker" required>
<option >...</option>
</select>
<div id="errormsg-id" class="invalid-feedback ">Please make a selection.</div>
</div>

This is PHP; however, for Angular (which is what I came here looking for), you could create a custom validator that checks if the <option value="">Choose Location</option> is selected. Inside the validator, you'd check the value of the control. If the control value is '', then you fail the validation.
This would work for both template driven and reactive forms.
Custom Validators in Angular

Have you put your select in form tag?
If not try placing it inside form tag.
Please refer - https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required

If required is not working you can add java script validation as given below and replace "FormnameId" with your form tag id.
<script type="text/javascript">
$(document).on('submit','form#FormnameId',function(event){
event.preventDefault();
var sel = $("#location-form").val();
if(sel == ''){
alert('Please select value first');
return false;
}
});
</script>

Related

how to set the html selected option value as selected in each page when including the same code in multiple pages

Ok I have a page name "my_file.html" with the code,
<script> //Beahvior on change
jQuery("#selectBox").change(function() {
document.getElementById("selectBox").value =$( "#selectBox).val();
location = $("#selectBox option:selected").val();
});
</script>
<!--A select html tag -->
<div class="block2">
<select id="selectBox">
<option value="check.html">Check.html</option>
<option value="going.html">Going.html</option>
<option value="check123.html">Check123.html </option>
</select>
</div>
Now this page(my_file.html) is loaded externally into the three files "check.html" ,"going.html" and "check123.html" with Jquery.Ok now I manually type the directory of "check.html" and the page is loaded,when selecting "going.html" from the option list the page going.html is loaded with the 'my_file.html' content but the option 'value="going.html"'is not mark as selected.The option list simply shows "check.html" as the selected option.This same behavior happens on selecting 'check123.html' option too.I also cannot load the 'check.html' page because it is already set as selected.
I have been trying to figure out the solution of this problem but to no avail,any help would be good.
If you want to know what I want to achieve go to this link http://readcomiconline.to/Comic/The-Walking-Dead/Issue-1?id=1715
Below the navigation bar you will see the "Issue" select option tag and when you choose any chapter from the drop down list,that issue is loaded and also the selected 'Issue' is set as selected.
Maybe the selectedIndex would do what you want:
document.getElementById("selectBox").selectedIndex = 2;
This way you can control what option is selected.
that site seems use "get" to achieve that,
in the top of my_file.html
<?php
$selectedCheck = $_GET['selected'];
?>
and in your div
<div class="block2">
<select id="selectBox">
<option value="check.html" <?php echo (($selectedCheck == 'check.html') ? 'selected':'');?>Check.html</option>
<option value="going.html" <?php echo (($selectedCheck == 'going.html') ? 'selected':'');?>>Going.html</option>
<option value="check123.html" <?php echo (($selectedCheck == 'check123.html') ? 'selected':'');?>>Check123.html </option>
</select>
</div>
it maybe not a smart way but it work and pretty easy to use :)
or maybe just add a default option like "Please choose one" and set it as selected, then whatever u selected the select will mark "Please choose one" selected.

Bootstrap multiselect form no validation message when no option selected

I have a form on my page that uses multiselect. Here is the relevant part of the form
<select required id="reqs2" name="reqs2[]" multiple="multiple" class="form-control">
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
and at the bottom of the page I have
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#reqs2').multiselect();
});
</script>
It all works fine if the user makes at least one selection, but if they don't make a selection, the form doesn't submit and no validation error message is displayed. Validation messages show for other required input fields, but not this one.
Any ideas what changes I need to make?
Thanks in advance
Thanks for your help, but I managed to solve it by removing the "required" element from the field on the form and adding a line to my php file as follows
Instead of
$try2 = implode(', ', $_POST['reqs']);
I add this before so it now becomes
if(isset($_POST['reqs']))
$try2 = implode(', ', $_POST['reqs']);
Now client can skip the field without an error showing
This seems to check if there is an entry in the field - if there is it implodes it; if not, it ignores it.

Javascript OnChange Script - Stop Form Submission

I have a project im working on, that needs a javascript OnChange Script for a dropdown box on media upload page.
I have a drop-down box with 2 options -'Yes' and 'No'. If the user selects 'No' i don't want the form to submit and possibly display a message saying why.
Is anyone able to provide a script to do this? I have to enter this on the attribute itself (eah attribute has the ability to have a OnChange script), i can change the attribute references to the specific ones needed. More of a general 'formula' for the script is needed.
Maybe i'm too vague and its not possible to make on the information i have given you.
Thanks in advance,
T.
first, write javascript code like this
<script>
function output()
{
var input = document.getElementById('input').value;
if(input==0){
alert("WHY???");
document.getElementById("out").value="why?";
}else{
document.getElementById("out").value="Ok";
}
}
</script>
and for the html code
<form>
<select name="input" id="input" onchange="output()">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<input type="text" id="out" name="out">
</form>
note: javascript not java

placeholder text for chosen plugin for single select not working

I have the chosen plugin for single select implemented in my code. I am trying to add the Placeholder text for the search boxes but I am not able to. I have tried the following things:
<select id="search_pi" name="search_pi" type="text" class="chosen-select"
style="width:450px;" onchange="this.form.submit()" >
<option value="">Search Project/Initiative...</option>
<?php
include "../includes/search_dropdown.php";
foreach($proj_ini_Array as $qa){
echo "<option value = \"$qa\">$qa</option>";
}
?>
JS
<script>
$(document).ready(function() {
$('.chosen-select').chosen({
placeholder_text_single: "Select an option",
no_results_text: "Oops, nothing found!"
});
});
</script>
In the select field, I also tried using data-placeholder="Select an option" but that does not help too. Can someone please let me know what am I missing?
Thanks in advance.
use data-placeholder="YOUR TEXT" in select tag
Okay. I found out the answer. We need to have the first option as blank for the placeholder text to be activated for Single select search box.
<select id="search_pi" name="search_pi" type="text" class="chosen-select" style="width:450px;" onchange="this.form.submit()" >
<option> </option>
<?php
include "../includes/search_dropdown.php";
foreach($proj_ini_Array as $qa){
echo "<option value = \"$qa\">$qa</option>";
}
?>
In the above case, placeholder text will default to "Select an option".
For a customized placeholder-text for a single search select box you can edit your js file as below and have the first option blank for the placeholder text to be displayed:
<script>
$(document).ready(function() {
$('.chosen-select').chosen({
placeholder_text_single: "Select Project/Initiative...",
no_results_text: "Oops, nothing found!"
});
});
</script>
To make your first option simply a guidance text, but unable for users to select it, use this:
<option selected="selected" disabled>Search Project/Initiative...</option>
* Edit *
Ah sorry, didn't read your question clearly enough to begin with.
Apparently the first <option> needs to be an empty one. See this jsfiddle.
User response #Zack Joerdan solved my problem.
So the spring required value inside option
<select placeholder="Placeholder goes here">
<option value=""><!-- Empty option goes here. --><option>
<option>Other Option</option>
</select>
There's actually a better/easier solution to this problem if you are constructing via HTML rather than JS. You have to do two things.
The first <option> in your <select> should be empty.
You should include placeholder="Placeholder goes here" in your <select>. Apparently this was once called data-placeholder, which I think has led to some confusion.
So, in total:
<select placeholder="Placeholder goes here">
<option><!-- Empty option goes here. --><option>
<option>Other Option</option>
</select>
You can just simply add data-placeholder="YOUR TEXT" No need to use jquery for the same
Here is the example
<select id="search_pi" data-placeholder="Select Project/Initiative..." name="search_pi" type="text" class="chosen-select" style="width:450px;" onchange="this.form.submit()" >
<?php
include "../includes/search_dropdown.php";
foreach($proj_ini_Array as $qa){
echo "<option value = \"$qa\">$qa</option>";
}
?>
</select>
<select data-placeholder="Select language" class="chosen-select">
<option></option>
<option>English</option>
<option>Urdu</option>
<option>Hindi</option>
<option>Chinese</option>
</select>
Add data-placeholder attribute on select and make sure first option is empty.

How to ensure a <select> form field is submitted when it is disabled?

I have a select form field that I want to mark as "readonly", as in the user cannot modify the value, but the value is still submitted with the form. Using the disabled attribute prevents the user from changing the value, but does not submit the value with the form.
The readonly attribute is only available for input and textarea fields, but that's basically what I want. Is there any way to get that working?
Two possibilities I'm considering include:
Instead of disabling the select, disable all of the options and use CSS to gray out the select so it looks like its disabled.
Add a click event handler to the submit button so that it enables all of the disabled dropdown menus before submitting the form.
Disable the fields and then enable them before the form is submitted:
jQuery code:
jQuery(function ($) {
$('form').bind('submit', function () {
$(this).find(':input').prop('disabled', false);
});
});
<select disabled="disabled">
....
</select>
<input type="hidden" name="select_name" value="selected value" />
Where select_name is the name that you would normally give the <select>.
Another option.
<select name="myselect" disabled="disabled">
<option value="myselectedvalue" selected="selected">My Value</option>
....
</select>
<input type="hidden" name="myselect" value="myselectedvalue" />
Now with this one, I have noticed that depending on what webserver you are using, you may have to put the hidden input either before, or after the <select>.
If my memory serves me correctly, with IIS, you put it before, with Apache you put it after. As always, testing is key.
I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.
// With jQuery
$('#selectbox').focus(function(e) {
$(this).blur();
});
Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.
I faced a slightly different scenario, in which I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using
$('#toSelect').find(':not(:selected)').prop('disabled',true);
it dows not work with the :input selector for select fields, use this:
jQuery(function() {
jQuery('form').bind('submit', function() {
jQuery(this).find(':disabled').removeAttr('disabled');
});
});
Same solution suggested by Tres without using jQuery
<form onsubmit="document.getElementById('mysel').disabled = false;" action="..." method="GET">
<select id="mysel" disabled="disabled">....</select>
<input name="submit" id="submit" type="submit" value="SEND FORM">
</form>
This might help someone understand more, but obviously is less flexible than the jQuery one.
The easiest way i found was to create a tiny javascript function tied to your form :
function enablePath() {
document.getElementById('select_name').disabled= "";
}
and you call it in your form here :
<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">
Or you can call it in the function you use to check your form :)
I use next code for disable options in selections
<select class="sel big" id="form_code" name="code" readonly="readonly">
<option value="user_played_game" selected="true">1 Game</option>
<option value="coins" disabled="">2 Object</option>
<option value="event" disabled="">3 Object</option>
<option value="level" disabled="">4 Object</option>
<option value="game" disabled="">5 Object</option>
</select>
// Disable selection for options
$('select option:not(:selected)').each(function(){
$(this).attr('disabled', 'disabled');
});
Just add a line before submit.
$("#XYZ").removeAttr("disabled");
Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled.
This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
Based on the solution of the Jordan, I created a function that automatically creates a hidden input with the same name and same value of the select you want to become invalid. The first parameter can be an id or a jquery element; the second is a Boolean optional parameter where "true" disables and "false" enables the input. If omitted, the second parameter switches the select between "enabled" and "disabled".
function changeSelectUserManipulation(obj, disable){
var $obj = ( typeof obj === 'string' )? $('#'+obj) : obj;
disable = disable? !!disable : !$obj.is(':disabled');
if(disable){
$obj.prop('disabled', true)
.after("<input type='hidden' id='select_user_manipulation_hidden_"+$obj.attr('id')+"' name='"+$obj.attr('name')+"' value='"+$obj.val()+"'>");
}else{
$obj.prop('disabled', false)
.next("#select_user_manipulation_hidden_"+$obj.attr('id')).remove();
}
}
changeSelectUserManipulation("select_id");
I found a workable solution: remove all the elements except the selected one. You can then change the style to something that looks disabled as well.
Using jQuery:
jQuery(function($) {
$('form').submit(function(){
$('select option:not(:selected)', this).remove();
});
});
<select id="example">
<option value="">please select</option>
<option value="0" >one</option>
<option value="1">two</option>
</select>
if (condition){
//you can't select
$("#example").find("option").css("display","none");
}else{
//you can select
$("#example").find("option").css("display","block");
}
Another option is to use the readonly attribute.
<select readonly="readonly">
....
</select>
With readonly the value is still submitted, the input field is grayed out and the user cannot edit it.
Edit:
Quoted from http://www.w3.org/TR/html401/interact/forms.html#adef-readonly:
Read-only elements receive focus but cannot be modified by the user.
Read-only elements are included in tabbing navigation.
Read-only elements may be successful.
When it says the element may be succesful, it means it may be submitted, as stated here: http://www.w3.org/TR/html401/interact/forms.html#successful-controls

Categories

Resources