A page deals with an input field that changes behavior depending on the dropdown value.
<div class="form-group">
<label for="exampleInputEmail2">Element Name</label>
<select class="form-control" name="element_id" id="element_name">
#foreach($elements as $element)
<option value="{{ $element->element_id }}">{{ $element->element_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleInputName2">Element Value</label>
<input type="text" class="form-control" id="element_value" name="value" placeholder="Add an Element Value">
</div>
A script I have is below:
<script type="text/javascript">
<?php
echo "var javascript_array = ". $list . ";\n";
?>
$("#element_name").on('change', function(){
var id_input = $('#element_name').val();
if(id_input == 2){
$("#element_value").datepicker();
}
else if(jQuery.inArray(id_input, javascript_array)!='-1'){
$("#element_value").datepicker('destroy');
$( function() {
$("#element_value").autocomplete({
scroll: true,
autoFocus: true,
minLength: 3,
source: function( request, response ) {
$.ajax({
url: "/employees/public/admin_list/search",
dataType: "json",
data: {
searchText: request.term
},
success: function( data ) {
response($.map(data, function(item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
select: function( event, ui) {
$(this).val(ui.item.label);
return false;
}
} );
} );
}
else {
$('#element_value').datepicker('destroy');
}
});
</script>
So basically, if the value of the dropdown is 2(Birthday), the field changes to datepicker (which works), unfortunately, the part where else if(jQuery.inArray(id_input, javascript_array)!='-1') doesn't seem to work, as it doesn't change the input to a search input. (If I hardcode it to else if((id_input == 1) || (id_input == 4) || (id_input == 5)) it always works, but this list ids will increase as users creates them in the future, so I have to store them in javascript_array and just search from there).
What am I missing?
the array shows as
var javascript_array = [1,4,5];
generated from a controller as below:
$lists = Elements::select('element_id')->where('is_list', 1)->get();
foreach ($lists as $r){
$list_temp[] = $r->element_id;
}
$list = json_encode($list_temp);
the issue is jQuery.inArray must be passed the correct type.
$('#element_name').val() would set id_input as a string:-
var id_input = "4";
var javascript_array = [1,4,5]
var stringType = jQuery.inArray(id_input, javascript_array);
console.log(stringType); // -1
var intType = jQuery.inArray(parseInt(id_input), javascript_array);
console.log(intType); // 1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
so you need to parseInt the dropdown value.
an input field that changes behavior depending on the dropdown value.
If I have understood correctly, then you can achieve this in a single-line jQuery function:
$(document).ready(function(){
$('select').change(function(){
$('input').attr('type', $('option:selected').val());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="text">Text Input</option>
<option value="button">Button Input</option>
<option value="date">Date Input</option>
<option value="checkbox">Checkbox Input</option>
<option value="radio">Radio Input</option>
</select>
<input type="text" />
Related
I am trying to make autofill, so when user select the item, it will put the value into the input field, but nothing change. I am using the name instead of id.
It work if I do like below.
$(document).on('change', '[name="item_media[]"]', function(){
var itemID = $(this).val();
var itemType = 1;
$(this).parents('.body-media').find('[name="value_media[]"]').val(0);
$(this).parents('.body-media').find('[name="unit_media[]"]').val();
});
But What I am trying to do is here, seem on the success:function do not work. When I try to console all the data is there
$(document).on('change', '[name="item_media[]"]', function(){
var itemID = $(this).val();
var itemType = 1;
if(itemID){
$.ajax({
type:'POST',
url:'?syspath=ajax&controller=ajax&action=getActItemDose',
data: { 'itemId': itemID, 'itemType': itemType },
success:function(data){
var object = JSON.parse(data);
var value = object.itemValue;
var unit = object.itemUnit;
$(this).parents('.body-media').find('[name="value_media[]"]').val(value);
$(this).parents('.body-media').find('[name="unit_media[]"]').val(unit);
}
});
}else{
$(this).parents('.body-media').find('[name="value_media[]"]').val(0);
$(this).parents('.body-media').find('[name="unit_media[]"]').val();
}
});
This is how I made my html section
<fieldset>
<div class="input-group body-media">
<select class="form-select" id="basicSelect" name="item_media[]" required>
<option value="">Please Select</option>';
foreach($treat as $item_media){
$id = $item_media['media_treat_id'];
$name = $item_media['media_treat_brand'];
echo "<option value='$id'>$name</option>";
}
echo'
</select>
<input type="text" class="form-control" name="value_media[]" placeholder=Input amount use" aria-label="Amount"/>
<select class="form-select" id="basicSelect" name="unit_media[]" required>
<option value="">Select unit</option>
<option value="2">g</option>
<option value="3">ml</option>
<option value="7">unit</option>
</select>
</div>
</fieldset>
I have a couple of drop downs, when a venue is choosen from the first one, it should populate the second drop down with floor values. Using jQuery AJAX I am able to get the selected venue, send that back to my controller and get the data needed for the second drop down. However I am not able to replace the existing drop down with the new data. This is the HTML for the two drop downs:
<div class="row no-margin-xs m-b-15">
<label class="col-sm-4 col-md-3 control-label p-xs-l-0">Venue</label>
<div class="col-sm-6 col-md-4 no-padding-xs">
<select class="form-control bs-select" name="venue" id="venue_select"
data-noneSelectedText="No venue selected"
data-validation="required"
data-validation-error-msg-required="Please select a venue"
data-dynamic-visible="true"
data-dynamic-relation="venue"
>
<option value="0" >Select a Venue</option>
<!-- ** Pull venue data and list here for selections -->
#foreach($venues as $venue)
#if(!is_null($venue->name))
<option value="{{$venue->id}}" >{{ $venue->name }}</option>
#endif
#endforeach
</select>
</div>
</div><!-- /.row -->
<div class="row no-margin-xs m-b-15" id="select_floor">
<label class="col-sm-4 col-md-3 control-label p-xs-l-0">Location Floor</label>
<div class="col-sm-6 col-md-4 no-padding-xs">
<select class="form-control bs-select" name="floor" id="floor_select"
data-validation="required"
data-validation-error-msg-required="Please select a floor"
>
<option value="">Select a Floor</option>
#foreach($locations as $location)
<option value="{{ $location->floor_id }}"
data-dynamic-relation-for="venue"
data-dynamic-relation-targets="[{{ $location->id }}]"
{{ old('floor_id') === (string) $location->floor_id ? ' selected' : '' }}
>{{ $location->floor }}</option>
#endforeach
</select>
</div>
</div><!-- /.row -->
There is a lot included the HTML for these drop down (I didn't write the code) that appear to be interfering with replaceWith() function. The jQuery code that retrieves the data for the second drop down looks like this:
$('#venue_select').on("change", function(){
var selectVenueId = this.value
console.log('Selected venue', selectVenueId);
_xhr = $.ajax(
url: $("meta[name='root']").attr("content") + '/app/settings/locations/data',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
venue_id: selectVenueId,
},
dataType: 'JSON',
async: true,
cache: false,
error: function (jqXHR, textStatus, errorThrown) {
_this.SetLoading(false);
_xhr = null;
},
success: function (response) {
_this.SetLoading(false);
var locations = response;
console.log('Locations: ', locations);
var listItems = '<option value="">Select a Floor</option>';
for (var i in locations){
listItems += "<option value='" + i + "'>" + locations[i] + "</option>";
}
$('#locations-new .block-content #select_floor select#floor_select').replaceWith('<select class="form-control bs-select" name="floor" id="floor_select"></select>' + listItems + '</select>');
console.log('listItems: ', listItems);
_xhr = null;
}
});
});
This is what I get on the front end when I run it:
It's not replacing the second dropdown but adding it.
You may have noticed the additional elements in the select tags:
data-dynamic-visible="true"
data-dynamic-relation-for="venue"
They appear to have a bearing on dynamic updating, but no Google searches have turned up any reference to these. There is a dynamicRelation.js file which looks like this:
define([
"jquery",
"underscore"
], function(s) {
var DynamicRelationUiClass = function () {
// Private vars
var _this = this;
// Private functions
var _onUpdate = function (e) {
_this.Update(e.currentTarget);
};
var _construct = function () {
$(document).on("change click", "[data-dynamic-relation]", _onUpdate);
$('[data-dynamic-relation]').each(function () {
_this.Update(this, 0);
});
};
// Public functions
this.Update = function(element, duration) {
if (_.isUndefined(duration)) { duration = 250; }
element = $(element);
var relationGroup = element.data("dynamic-relation"),
currentValue = element.val();
if (parseInt(currentValue) !== NaN) { currentValue = parseInt(currentValue); }
$('[data-dynamic-relation-for="' + relationGroup + '"]').each(function () {
var t = $(this),
targets = t.data('dynamic-relation-targets'),
found = targets.indexOf(currentValue) !== -1;
t.prop("disabled", !found);
if (!found && t.prop("selected")) { t.prop("selected", false); }
});
$('.bs-select').selectpicker('refresh');
$('.multiselect').multiSelect('refresh');
};
_construct();
}
return DynamicRelationUiClass;
});
I would like any clue to a solution, especially if someone has information of the dynamicVisible feature, or short of that how to get the replaceWith() to work.
i want to show the selected value to the select option, the value actually selected but cannot show that value on select option form.
for example i have a 3 value it can be choose is anyaman, cendana, and bakulan. when 1 edit that form with value cendana, the showed value is the first sequence (anyaman) but when i open that select option that focused on the true data value (cendana).
This is HTML Script :
<div class="mb-1">
<label class="form-label" for="user-role">Asal Kelompok</label>
<select id="editkelompok_id" name="kelompok_id" class="select2 form-select">
<option disabled="" value=""> <b> Pilih asal kelompok </b></option>
#foreach($kelompok as $data)
<option value="{{$data->id}}">{{$data->nama_desa}} - {{$data->nama_kelompok}} </option>
#endforeach
</select>
</div>
The Controller
public function detaildataanggota($id)
{
$status = anggota::findOrfail($id);
return $status;
}
Java Script
<script type="text/javascript">
function detaildataanggota(id){
$.ajax({
url: "{{url('admin/pendataan/dataanggota/detail')}}" + "/" + id,
dataType: "json",
success: function(status) {
$('#editid').val(status.id);
$('#editnama_anggota').val(status.nama_anggota);
$('#editnik').val(status.nik);
$('#editjabatan').val(status.jabatan);
$('#editjenis_kelamin').val(status.jenis_kelamin);
$('#edittanggal_lahir').val(status.tanggal_lahir);
$('#editalamat').val(status.alamat);
$('#editkelompok_id').val(status.kelompok_id);
},
});
}
</script>
The problem is on #editkelompok_id
Try this
let select = $('#editkelompok_id');
select.on('change',()=>{
// Your stuff
})
or
let options = $('#editkelompok_id').children();
options.each(function() {
let option = $(this);
option.on('change', () => {
select.val(option.val());
})
})
I hope it was useful
I have a table about products. It has id, productdmc, productcode columns.
In this select menu, productdmc is showing.
When one item was selected, label its gonna change with related rows. Thats what i need. But i cant figure out the solution.
productcode.
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
Related input
<input type="text" name="productcode" id="productcode">
This is the js code. I dont know this is working. This is my actual problem.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="productdmc"]').on('change', function() {
var tmp = $(this).val();
if(tmp) {
$.ajax({
url: '/products/create/'+tmp,
type: "GET",
dataType: "json",
success:function(data) {
$('productcode').empty();
$.each(data, function(key, value) {
$('productcode').innerHTML('<input value="'+ key +'">');
});
}
});
}else{
$('productcode').empty();
}
});
});
</script>
In my Controller:
$val = DB::table("products")->pluck("productdmc","productcode");
return json_encode($val);
I know, i messed up so much. But codes are so complicated than this. I write this code in here(shorter version). Not copy-paste. I stucked here in a while. I cant find what is the real solution is.
I am open for all kinda solution.
Sorry for my bad english.
innerHTML is a property of HTML elements, not a function of jQuery's representation.
Use html(content) instead, and I think it should work:
$('#productcode').html('<input value="'+ key +'">');
Your selector is wrong, you forgot the '#'.
var $productCode = $('#productcode');
Also, when the event 'change' is triggered, you need to fetch the selected option.
var selectedValue = $element.find('option:selected').val();
HTML
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
<input type="text" name="productcode" id="productcode">
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('body').on('change', 'select[name="productdmc"]', function(e) {
var $element = $(e.currentTarget); // $(this) is also fine.
// Get selected value
var selectedValue = $element.find('option:selected').val();
var $productCode = $('#productcode');
// No value selected
if (!selectedValue) {
$productCode.val('');
return;
}
$.ajax({
url: '/products/create/' + selectedValue,
type: 'GET',
dataType: 'json',
error: function() {
$productCode.val('');
},
success: function(res) {
$productCode.val('');
if (res.length < 1) return;
$productCode.val(res[0] || '');
// This will populate more than 1 field. So,
// I'm not sure about what you expect on the backend.
// If you want to populate more than 1,
// you should change the selector/field (do not use id in this case)
// $.each(res, function(key, value) {
// $productCode.val(key);
// });
}
})
});
});
</script>
PHP
<?php
$products = DB::table('products')->get();
return response(
$products->pluck('productdmc', 'productcode')->toArray()
);
You can read more about jQuery selectors here: https://api.jquery.com/category/selectors/
I have two drop down that can be manipulate. The second drop down; httpauthmode is manipulated by the value in the first drop down;httprestype.
I want the second drop down; httpauthmode to change to default value when user selected
httpreqtype() == 2; i.e
<option value="0" selected="selected">None</option>
//I want the value = 0 be the default value
Javascript
_self.httpreqtype = ko.observable( httpreqtype );
_self.httpauthmode = ko.observable(null);
Here is my html
<label>HTTP Request Type</label><br/>
<select data-bind="value: httpreqtype" style="width:200px">
<?php
foreach($httpRequestOptions as $key=>$val) {
echo '<option value="'.$val["id"].'" >'.$val["name"].'</option>';
};
?>
//$httpRequestOptions is an array inside my viewModel, I only put a piece of my code
</select>
<label>HTTP Auth Type</label><br />
<select data-bind="value: httpauthmode" style="width:200px">
<option value="0" selected="selected">None</option>
<option value="1">Basic Authentication</option>
<option value="2" data-bind = "visible: httpreqtype() == 2" >Body Encryption</option>
<option value="3" data-bind = "visible: httpreqtype() == 2" >Basic Authentication + Body Encryption</option>
</select>
I try hours googling and already tried subscribe function, set the observable to (null), ("") and many other ways. Can someone expert help me or maybe suggest what method I can try. Really appreciate it and many thanks in advance.
You should approach this very differently. Carefully read the options binding documentation and try to rework your code to that approach. Basically it allows you to data bind the select tag, and have the options rendered dynamically by Knockout.
Something like this:
var Model = function(httpreqtype){
var _self = this;
_self.httpauthmode = ko.observable(null);
_self.httpreqtype = ko.observable( httpreqtype );
_self.httpauthmode = ko.observable(null);
var mode0 = { id: 0, txt: "None" };
var mode1 = { id: 1, txt: "Basic Authentication" };
var mode2 = { id: 2, txt: "Body Encryption" };
var mode3 = { id: 3, txt: "Basic Authentication" };
_self.availableHttpAuthModes = ko.computed(function() {
if (_self.httpreqtype() == 2) {
return [mode0, mode1];
}
return [mode0, mode1, mode2, mode3];
});
}
ko.applyBindings(new Model(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="value: httpauthmode,
optionsText: 'txt',
options: availableHttpAuthModes" >
</select>
<br /><br />Change httpreqtype:
<br /><input data-bind="value: httpreqtype, valueUpdate: 'afterkeydown'" />
Set httpauthmode to '0' (value of None) when httprestype changes to '2':
_self.httprestype.subscribe(function(value) {
if(value === '2') {
_self.httpauthmode('0');
}
});
JSFiddle