Select box need Focus in first element of the search field (multiselect) - php

This is my select Box Now its working fine, But I want the first element in search to be focus, Any idea will appreciate
$('.newmultiselect').multiselect({
enableFiltering: true,
filterPlaceholder: 'Search',
enableCaseInsensitiveFiltering : true,
includeSelectAllOption: false,
onChange: function(element, checked) {
var selectID = $(element).parent().attr('id');
$("#"+selectID).valid();
}
});
searchMultiselect();
My state field Div
<div class="col-12 col-sm-6 col-md-6 col-lg-4">
<div class="form-group">
<p>State<span class="notice-txt">*</span></p>
<select class="form-control validrmvcls newmultiselect" id="state" name="state">
<option value="">--Select--</option>
#foreach($states as $st)
<option value="{{$st['state_prefix']}}">{{$st['state_prefix']}}</option>
#endforeach
</select>
</div>
</div>

You can use css first child property, and for selecting default you can pass the value of first option in your result dataSet.

Krzysztof Janiszewski please have a look

Just add onDropdownShown callback and focus on your input.
EDIT
If you don't want to focus on input but first element, just do it like this:
onDropdownShown : function() {
$('li:visible:not(.multiselect-filter)').eq(0).focus();
}

Related

Assign "select" attribute to jquery select2 dropdown dynamically

I am working on jquery select2 dropdown. I have to display the multiple selected option in select area. For this purpose i loop through each of select2. If condition is met i will assign 'selected' attribute property to option so that it may appears in the select area.
But somehow the select2 fails to display the selected ''.
HTML CODE:
<div class="form-group col-md-12">
<label for="inputsskill">Skill<span class="required-field">*</span></label>
<fieldset>
<select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
#if(!$skills->isEmpty())
#foreach($skills as $skill)
<option value="{{$skill->id}}">{{$skill->name}}</option>
#endforeach
#endif
</select>
</fieldset>
</div>
JQUERY CODE:
// parse skills
var parseData = JSON.parse(skill);
// parseData is an array which contain 1,2,3 values like ['1','2','3']
$("#skill_name > option").each(function() {
// if select2 and array values matches assign selected attribute to that option
if( $.inArray($(this).val(), parseData) !== -1 ) {
$(this).attr('selected', 'selected');
}
});
Select2 Jquery:
$( "#skill_name" ).select2({
});
I dont know where i am going wrong, i would appreciate if someone guide me in this.
Thanks,
you can achieve this functionality with PHP easily.
E.g : fetch skills from the database which you want to preselect and create an array of skills. Then match this in your loop.Like
<div class="form-group col-md-12">
<label for="inputsskill">Skill<span class="required-field">*</span></label>
<fieldset>
<select class="custom-select w-100" name="skill_name[]" id="skill_name" multiple="multiple" style="width: 100%;">
#if(!$skills->isEmpty())
#foreach($skills as $skill)
<option value="{{$skill->id}}" <?php
if(in_array($skill->name, $selectedskillsArray)){
echo $selected = 'selected';
}
?> >{{$skill->name}}</option>
#endforeach
#endif
</select>
</fieldset>
</div>
Try this one.
Jquery solution
$( "#skill_name" ).select2({
});
$('#skill_name').val(["1","2","3"]).trigger('change');

Multi select dropdown select all

Here is my Controller function and view of multi select dropdown.How can i include 'all' condition to select all data that are in multselect dropdown .Please Help me
Controller Function
$where2 = array('departments.isDeleted =' => 0);
$data['dept'] = $this->general_model->get('departments',$where2);
View:
<div class="form-group">
<label class="col-sm-3 control-label">Departments</label
<div class="col-sm-6">
<select name="departmentId[]" class="form-control" multiple="multiple" id="departmentId" >
<?php if(is_array($dept)){ foreach($dept as $depts){ ?>
<option value="<?php echo $depts['departmentId'];?>">
<?php echo $depts['departmentName'];?>
</option>
<?php }} ?>
</select>
</div>
</div><!--/form-group-->
Before <?php if(is_array($dept)){ foreach($dept as $depts){ ?>
add <option value="all">All</option>
Sometimes the easiest solutions are the least apparent ;)
Note: you could make it so that (with js) when the "all" option is selected the rest are deselected for better ui but it really doesn't matter. On the backend you can just have a condition checking for all as selected and disregard the rest that are selected (because you have multiple enabled).

repopulate child dropdow when parent dropdown changed

TL;DR
How to make jQuery request from parent dropdown ( using .change() ) to working url that outputs JSON and repopulate child dropdown.
END TL;DR
I'm using Laravel 5.1 so my code will be a bit Laravel specific but not much since this is beginner level jQuery problem.
I have two dropdowns. One is for categories (parent) and other is for subcategories (child).
My parent dropdown:
<div class="form-group">
{!! Form::label('category_id', '*Categories') !!}
{!! Form::select('category_id', $categories, null) !!}
</div>
which generates
<div>
<label for="category_id">Categories</label>
<select id="category_id" name="category_id">
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
</div>
My child dropdown:
<div sytle="display:none;">
{!! Form::label('subcategory_id', 'Subcategory') !!}
{!! Form::select('subcategory_id', [], null) !!}
</div>
which generates
<div sytle="display:none;">
<label for="subcategory_id">Subcategories</label>
<select id="subcategory_id" name="subcategory_id">
</select>
</div>
I have defined route: subcategoriesfordropdown/{i} to which I send i and it gives me JSON with the children of parent category. For example if I use URL subcategoriesfordropdown/2 I get:
{"3":"Subcategory 1 title","4":"Subcategory 2 title"}
Numbers in "" are subcategories IDs. This is all working properly.
Now I want to repopulate child dropdown with these id/title pairs so that I get:
<div sytle="display:none;">
<label for="subcategory_id">Subcategories</label>
<select id="subcategory_id" name="subcategory_id">
<option value="3">Subcategory 1 title</option>
<option value="4">Subcategory 2 title</option>
</select>
</div>
I made this jQuery script:
<script>
$(document).ready(function(){
$("#category_id").change(function (){
var category = $(this).val();
alert( "Category: " + category );
});
});
</script>
And it pops an alert box with category ID as I change the parent dropdown values. However, instead of alert function I want it to run POST request (I believe POST is the right one here but GET is OK too) to get the JSON data and create options values from it. Also change the display:none; but that shouldn't be a problem.
I tried replacing alert(); with:
$.post( "/subcategoriesfordropdown/" + category, , function( data ){
alert( "Data: " + data );
});
to receive the data given by subcategoriesfordropdown/{i} but I'm failing here.
So here is my TODO list:
run POST request
get JSON data
populate child dropdown with JSON data
remove display:none; attribute
I hope I ain't missing something elese here. Thank you all in advance!
You're definitely on the right tracks.
The only issue I see with your $.post is the extra , after category. I'd also suggest using the "json" tag - it just prevents you have to use json_decode within the function.
To update the select box you can use Javascript along these lines.
(Untested, but theoretically correct barring typos)
$.post( "/subcategoriesfordropdown/" + category, function( data ){
var $select = $('#subcategory_id');
$select.empty();
$.each(data, function(value, text){
$select.append($("<option></option>")
.attr("value", value).text(text));
});
$select.show();
}, "json");

jQuery Related (Dependent) Selects Plugin

I found this jquery plugin for dependent select box . This worked now but i have big problem ! when put this in submit form not worked because this plugin worked with form id and post/get data using json. Original Demo HERE
Problem e.x:
<div id="box">
<form action="search.php" method="POST" >
<form id="example-1">
<div class="field">
<label for="name">state :</label>
<select name="stateID">
<option value="">Choose State »</option>
<option value="MA">Massachusetts</option>
<option value="VT">Vermont</option>
</select>
</div>
<div class="field">
<label for="name">Country :</label>
<select name="countyID">
<option value="">Choose County »</option>
</select>
</div>
<div class="field">
<label for="name">town :</label>
<select name="townID">
<option value="">Choose Town »</option>
</select>
</div>
<div class="field">
<label for="name">village :</label>
<select name="villageID">
<option value="">Choose Village »</option>
</select>
</div>
</form>
</form>
</div>
If I Remove form action this plugin worked perfectly, Otherwise not worked. How To Fix This Thanks.
To elaborate on my comment, you can capture the submit of the form and do with it what you like.
$("form").submit(function(e){
e.preventDefault(); //stop the default behavior
$.ajax({
type: 'POST', //default is get, set to 'POST' if you want to post.
url: 'search.php',
success: function(data){
//if our data was returned from our search file as json, then...
$("#element").html(data.a) //returns the a value from our json object
$("#element").html(data.b) //returns the b value from our json object
//etc
}
});
});
The submit function stops the form from submitting per the usual fashion, and stops the page-reload. Then we use an ajax request to send our data through the 'POST' method to our file search.php. The returned data is sent in an object, and we access it through our success:function(data). Then, if our data was returned with JSON values, we can use data.a to get the a value, or data.b to get the b value of our JSON string.

Show/hide fields depending on select value

I am trying to show and hide a few form fields depending on the value of one of my select fields. I am looking to use arrays to hold what should be shown and what should not be shown for each select value, to save me from a massive switch statement, but cannot figure out how to do it.
I am using PHP and jQuery. Any help would be great.
Try something like this:
<select id="viewSelector">
<option value="0">-- Select a View --</option>
<option value="view1">view1</option>
<option value="view2">view2</option>
<option value="view3">view3</option>
</select>
<div id="view1">
<!-- content -->
</div>
<div id="view2a">
<!-- content -->
</div>
<div id="view2b">
<!-- content -->
</div>
<div id="view3">
<!-- content -->
</div>
then in the jQuery:
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
});
});
There are a few different ways you could do this. The simplest is to have a few separate fieldsets, each one containing a single group of fields. Then, in jQuery, dependent on the select-menu's value you can show/hide these fieldsets, e.g.
<fieldset id="f1">
<input name="something1" />
<input name="something2" />
<input name="something3" />
</fieldset>
<fieldset id="f2">
<input name="something4" />
<input name="something5" />
<input name="something6" />
</fieldset>
<select name="fieldset-choice">
<option value="f1">Fieldset 1</option>
<option value="f2">Fieldset 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=fieldset-choice]').change(function(){
var fieldsetName = $(this).val();
$('fieldset').hide().filter('#' + fieldsetName).show();
});
// We need to hide all fieldsets except the first:
$('fieldset').hide().filter('#f1').show();
</script>
Note: For the above technique to be entirely unobtrusive you might want to dynamically build the select-menu with the names of all the different fieldsets.
Alternatively you can prefix each fields name with a meaningful prefix, and then hide/show according to that attribute:
<input name="group1-name1" />
<input name="group1-name2" />
<input name="group2-name3" />
<input name="group2-name4" />
<input name="group2-name5" />
<select name="field-choice">
<option value="group1">Group 1</option>
<option value="group2">Group 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=field-choice]').change(function(){
var groupName = $(this).val();
$('input').hide().filter('[name^=' + groupName + ']').show();
});
// We need to hide all fields except those of the first group:
$('input').hide().filter('[name^=group1]').show();
</script>
To fire up the code on load, just add .change(). As shown below...
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
}).change();
});
My 2 cents :
I needed to show/hide fields depending on many previous select value (not only one).
So I add a parent attribute to div fields like this :
<div id="view" parent="none">
<select class=selector id="view">
<option value="0"> -- Make a choice --</option>
<option value="s1">sub 1</option>
<option value="s2">sub 2</option>
<option value="s3">sub 3</option>
</select>
</div>
<!-- you need to define the parent value with the value of parent div id -->
<div id="s1" parent="view">
<!-- if you want to have a selector be sure it has the same id as the div -->
<select class=selector id="s1">
<option value="0">-- Make a choice --</option>
<option value="s1_sub1">sub 1 of s1</option>
<option value="s1_sub2">sub 2 of s1</option>
<option value="s1_sub3">sub 3 of s1</option>
</select>
</div>
<!-- Make the same thing for s2 and s3
Define div s2 here
Define div s3 here
-->
<!-- and finally if that's your final step you put what you want in the div -->
<div id="s1_sub1" parent="s1">
You are inside s1 sub1
</div>
Now the jquery code :
$(document).ready(function() {
$('select[class=selector]').change(function() {
//next div to show
var selectorActive = $(this).val();
//div where you are
var parentValue = $(this).attr("id");
//show active div and hide others
$('div').hide().filter('#' + selectorActive).show();
while (parentValue!="none") {
//then show parents of active div
$('div[id=' + parentValue + ']').show();
//return the parent of div until "none"
parentValue = $('div[id=' + parentValue + ']').attr("parent");
}
});
// print only the first div at start
$('div').hide().filter("#view").show();
});
That's works like a charm and you don't need to define maps
I hope this will help
#Martin Try this
`$('#viewSelector').trigger('change');`
Here is a very simple example:
The purpose is to show A SIMPLE EXAMPLE of how to use an array of values to show/hide fields depending upon the value of a select.
In this demo, I could have used the classNames to show/hide the group of fields all-at-once -- but that's not the purpose of the example -- so the classNames were used only for CSS.
Because the demo uses IDs (with two arrays of these IDs) for the demo, it doesn't matter whether the fields to be hidden are input fields, divs, imgs or what-have-you. The ID identifies whatever-it-is-to-be-hid.
var aPeople = ['bob','sam','ted'];
var aTransport = ['car','bike','truck'];
$('#mySel').change(function(){
$('.alldiv').hide(); //Hide them all to start...
let sel = $(this).val(); //Get selected option value
if ( sel=='ppl' ){
for (let i=0; i<aPeople.length;i++){
$('#' + aPeople[i]).show();
}
}else if ( sel=='tpt' ){
for (let i=0; i<aTransport.length;i++){
$('#' + aTransport[i]).show();
}
}else{
//Choose selected
$('.alldiv').show();
}
});
.alldiv{width:30vw;height:10vh;padding:2vh 2vw;text-align:center;}
.ppl{background:palegreen;}
.tpt{background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="mySel">
<option value="">Choose:</option>
<option value="ppl">People</option>
<option value="tpt">Vehicles</option>
</select>
<div id="bob" class="alldiv ppl">People: Bob</div>
<div id="car" class="alldiv tpt">Vehicle: Car</div>
<div id="truck" class="alldiv tpt">Vehicle: Truck</div>
<div id="sam" class="alldiv ppl">People: Sam</div>
<div id="ted" class="alldiv ppl">People: Ted</div>
<div id="bike" class="alldiv tpt">Vehicle: Bike</div>

Categories