default select not displayed in dropdown - javascript

This is dynamically loaded dropdown box from a php file. I have put a default option Select Language But this is not displaying once the ajax elements loaded.
How can I make the select language as default even after the ajax items are loaded?
<select id="name">
<option style="display:none;" selected>Select language</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>

$el.empty() statement removes all the options from the select. You shouldn't remove the first option.
For this, use not method and :first pseudo-class in order to keep the default option.
$el.find('option').not(':first').remove();

Because you need to remove old options, and add new ones without loosing the default "Select language" text, you can do like this:
<select id="name">
<option style="display:none;" selected>Select language</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
//adding your default value
$el.append('<option selected>Select language value</option>');
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>

Related

Append collected data with javascript

I have 2 different data they load based on each other id what I try to do is to append my results as row bootstrap 3 based something like:
So far I can get 3 sort of my data successfully, all the problem I
have and need help with is how to append data as described in image above?
code
javascript
<script>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key, value1) {
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key, value) {
$('div#dataaa').append('<div class="row"><div class="col-md-4" id="dataparent">'+value1.title+'</div><div class="col-md-8" id="datainfo">'+value.title+'</div></div>');
});
}
});
// second data
});
}
});
}else{
$('div#dataaa').append('select set');
}
});
});
</script>
html
<div id="dataaa"></div>
This is how I'm getting my data now:
Update
Well I have made it work so far. Remained one issue, and that is I cannot get all my data I only can get my first result.
Changed code
<script>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key1, value1) {
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Collect data as option
var helpers = '';
$.each(data, function(key, value) {
helpers = '<option value="'+value.id+'">'+value.title+'</option>';
});
var my_row = $('<div class="row">');
var my_html = '<div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-8"><select class="form-control" id="subs" name="subs[]">'+helpers+'</select></div>';
my_row.html(my_html);
$('div#dataaa').append(my_row);
}
});
// second data
});
}
});
}else{
$('div#dataaa').append('select set');
}
});
});
</script>
Update 2
As requested here is my first select option code
{{ Form::label('selectset', 'Select Set') }}
<select class="form-control" id="selectset" name="selectset">
<option value="">Select</option>
#foreach($selectsets as $selectset)
<option value="{{ $selectset->id }}">{{ $selectset->title }}</option>
#endforeach
</select>
change
$.each(data, function(key, value) {
helpers = '<option value="'+value.id+'">'+value.title+'</option>';
});
to
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
because on each iteration, it overwrite its previous result

How to Get Value From HTML Dropdown List using Jquery

I have dropdown list and i want to retrieve data from database when select value of downlist. This is working without having error. But this is working when i click on dropdown list, not in dropdown value. That mean work only for default value. please help me how to rectify this error. code as below.
HTML code for Dropdown list
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01" >Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
Jquery Code is Here
<script type="text/javascript">
$(document).ready(function () {
$("option").click(function () {
var txt = $("#lab-no:selected").val();
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
</script>
First you need to target your select $('#lab-no') and use change event instead of click. Then you can target the selected option.
$(document).ready(function () {
$("#lab-no").change(function () {
var txt = $("select option:selected").val()
console.log(txt)
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01" >Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
Try with $("#lab-no").change. This Way your event will trigger after you have made a change in the dropdown.
You should not use :selected in $("#lab-no:selected").val() since its not needed. $("#lab-no").val() will return the selected value.
Working Demo
$(document).ready(function() {
$("#lab-no").change(function() {
var txt = $("#lab-no").val();
console.log(txt)
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {
'search': txt
},
dataType: "text",
success: function(data) {
$('#table-row').html(data);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01">Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
You can use in simple way like:
var drpSelectedValue=$("#lab-no").val();
May this help for you.
You should try like this
1.You need to change jquery event
<script type="text/javascript">
$(document).ready(function () {
$("#lab-no").change(function () {
var txt = $("#lab-no").val();
alert(txt) //place alert and check value. You will get values which you have selected
if (txt == '') { //make changes here
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
</script>

AJAX filled Select2 not clickable

I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

Select2 Change Event - Change the options for next select2 box on first select2 box value change

I have 2 select2 boxes. First is Category and next is Sub-category.
Now, I want to change the options for subcategory box based on Category box selected value. And the data for Subcategory box should load using AJAX.
Please help me.
just solved it myself
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select class="js-data-example-ajax" id="category" >
<option value="">Select a category</option>
<option>cat1</option>
<option>cat2</option>
<option>cat3</option>
</select>
<select class="js-data-example-ajax" id="sub-category" >
</select>
<script>
$("#category").select2({
placeholder: "Select a category",allowClear: true
});
$("#sub-category").select2({
placeholder: "Select sub-category",allowClear: true
});
$('#category').on("change", function (e) {
var result = '';
var catval = $(this).val();
if(catval != '') {
url = "subcats_top/"+ catval;
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function(data){
var length = data.length;
if(length > 0) {
for(key in data) {
result += '<option value="' + data[key].id + '">' + data[key].name + '</option>';
}
} else {
}
$("#sub-category").html(result);
}
});
}
});
</script>

get the multiple checked value from select tag using multiple="true"

<Select id="chkProduct" multiple="true">
</select>
<script type="text/javascript">
$(function () {
$(document).ready(function() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'http://###.##.##.##/####/Country.svc/ProductBind',
data: '{}',
dataType: "json",
processData: false,
success: function (data) {
var oi;
for (var i = 0; i < data.Data.length; i++) {
appendString = "<option value='"+data.Data[i].Product+"'>"+data.Data[i].Product +"</option>";
$("#chkProduct").append(appendString);
}
},
error: function (result) {
alert("Error");
}
});
});
});
</script>
i need some suggestion how can i get the checked value after binding the data..
this dropdown bind checkbox with default OK AND CANCLE button and on OK cleck i get single checked value instead if multiple checked value...
it allow to select multiple check but it take single checked item value...and i want multiple checked value
For a multiple select, the .val() returns an array of the selected values (not text). Here is an example:
Given an empty select and a button we'll click to get the selected values
<select name="chkProduct" id="chkProduct" multiple="true" data-native-menu="false">
</select>
<button id="btnGet">Get Selected</button>
The script loads some options on pagecreate (this would be your ajax function) and then the click handler displays the selected values as a comma delimited list:
$(document).on("pagecreate", "#page1", function(){
var appendString = '';
for (var i = 0; i < 6; i++) {
appendString += "<option value='"+ i +"'>item "+ i +"</option>";
}
$("#chkProduct").empty().append(appendString).selectmenu( "refresh" );
$("#btnGet").on("click", function(){
alert($("#chkProduct").val());
});
});
Here is a working jsFiddle

Categories