Fill Textfield Based on Select Option - javascript

I'm trying to get "hargaJual" value when I select some option. But when I insert a new row in the table and select a new option, it will change only the first row of "Harga" and leave the second-row blank.
Here's the result :
<td>
<select class="custom-select" id="kodeSparepart" name="kodeSparepart[]">
<option value=""> --Pilih Sparepart-- </option>";
#foreach($sparepart as $s) {
<option value="{{ $s['kodeSparepart'] }}" data-price="{{ $s->hargaJual }}"> {{ $s['namaSparepart'] }} </option>";
}
#endforeach
</select>
</td>
<td>
<input class="form-control" type="text" id="hargaJualTransaksi" name="hargaJualTransaksi[]" autocomplete="off" readonly>
</td>
And here is my javascript
//for insert new row in table
$(function(){
$('#addMore').on('click', function() {
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
});
$(document).on('click', '#remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>=1) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
});
//fill hargaJualTransaksi field
$(function() {
$('#kodeSparepart').on('change', function(){
var price = $(this).children('option:selected').data('price');
$('#hargaJualTransaksi').val(price);
});
});

You need to use event delegation on since the rows are dynamically rendered to the DOM :
$(function() {
$('body').on('change', '.kodeSparepart', function(){
var price = $(this).children('option:selected').data('price');
$('.hargaJualTransaksi').val(price);
});
});
NOTE: The id attribute must be unique so you needs to change every kodeSparepart and hargaJualTransaksi to classes instead of id's, it will be something like :
<input class="form-control hargaJualTransaksi" type="text" name="hargaJualTransaksi[]" autocomplete="off" readonly>

Try below code:
$("body").on('click', '#kodeSparepart', function (event) {
var price = $(this).children('option:selected').data('price');
$('#hargaJualTransaksi').val(price);
}

Related

select2 doesn't work when add from dynamically with jquery

i have a form that the elements is dynamic. we can add a row according to the needs. Here is a image link
dynamic form
as we can see, we can add a row just press "tambah kolom" button and then the row will be attached to the form. i use jquery to adding dynamic. here is my forms code
HTML
<tr>
<td>
<input type="number" class="form-control" value="{{ old('itemujiriksa[0][jumlah_barang]') }}" name="itemujiriksa[0][jumlah_barang]">
</td>
<td>
<input type="text" class="form-control" value="{{ old('itemujiriksa[0][nama_barang]') }}" name="itemujiriksa[0][nama_barang]">
</td>
<td class="form_tabung">
<select name="itemujiriksa[0][tube_id]" class="form-control tube" style="width: 100%">
</select>
</td>
<td class="form_alat" style="display:none">
<select name="itemujiriksa[0][alat_id]" class="form-control alat" style="width: 100%">
</select>
</td>
<td>
<input type="text" class="form-control" value="{{ old('itemujiriksa[0][keluhan]') }}" name="itemujiriksa[0][keluhan]">
</td>
<td>
<input type="file" class="form-control" value="{{ old('itemujiriksa[0][fototabung][]') }}" name="itemujiriksa[0][fototabung][]" multiple />
</td>
</tr>
and here is my jquery code
jquery
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $("#input_fields_wrap"); //Fields wrapper
var add_button = $("#add_field_button"); //Add button ID
var x = {{$a}}; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
$(wrapper).append('<tr>\
<td>\
<input type="number" class="form-control" value="{{ old('jumlah_barang[]') }}" name="itemujiriksa[' + x +'][jumlah_barang]">\
</td>\
<td>\
<input type="text" class="form-control" value="{{ old('nama_barang[]') }}" name="itemujiriksa[' + x +'][nama_barang]">\
</td>\
<td class="form_tabung">\
<select name="itemujiriksa[0][tube_id]" class="form-control tube" style="width: 100%">\
</select>\
</td>\
<td class="form_alat" style="display:none">\
<select name="itemujiriksa[0][alat_id]" class="js-selectize form-control" placeholder="Pilih No Alat">\
<option disabled selected value></option>\
#foreach($alats as $at)\
<option value="{{ $at->id }}">{{ $at->no_alat }}</option>\
#endforeach\
</select>\
</td>\
<td>\
<input type="text" class="form-control" value="{{ old('keluhan[]') }}" name="itemujiriksa[' + x +'][keluhan]">\
</td>\
<td>\
<input type="file" class="form-control" value="{{ old("itemujiriksa['+ x +'][fototabung][]") }}" name="itemujiriksa[' + x +'][fototabung][]" multiple>\
</td>\
<td><a class="btn btn-danger remove_field">Hapus Kolom</a></td>\
</tr>'); //add input box
x++; //text box increment
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parents("tr").remove(); x--;
}) });
and here's my select2 code
SELECT2
$(document).ready(function() { var $select2Elm = $('.alat');
$select2Elm.select2({
width: 'resolve',
placeholder: "Pilih No Alat",
ajax: {
url: function(){
var value = $('#customer').val();
var url = "/admin/getDataAlat/ujiriksa/"+value;
console.log(url);
return url;
},
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
},
}); });
my question is
i have defined class alat to initiate the no tabung select box for populate data from select2. but after adding a new row which is the class is same. the new select box doesnt populate data. what should i do master?
you'll need to initialize each new select element after you append the html.
$(add_button).click(function(e){
//append new table rows here
$(wrapper).append('...');
//reinitialize the new select box
$('.alat').select2({
//configuration
});
});
You can initialize after append your code.
You can see below example
$(document).on("click",".add-new-item",function(e){
var html = 'your html';
$( '.element' ).append(html);
initSelect2();});
function initSelect2() {
$('.select2_single').select2();}

Show hide input element based on selection

Hi I am trying to show hide input element based on selection value of another element.
However I am unable to achieve it. I am not sure what is wrong I am doing.
The JS Fiddle is here :
https://jsfiddle.net/rovvLt9e/1/
<div>
<table>
<tr id="type">
<td height="30">Type</td>
<td>
<input type="radio" name="type" value="Document" checked>Document
<input type="radio" name="type" value="Parcel">Parcel
</td>
</tr>
</br>
</br>
<tr id="height">
<td height="40">Approx weight of consignment</td>
<td>
<select name="weight">
<option selected>200gms</option>
<option>200 - 500gms</option>
<option>500 - 750gms</option>
<option>750gms - 1Kg</option>
<option>1Kg - 5Kg</option>
<option> > 5Kg</option>
</select>
</td>
</tr>
</table>
</div>
</br></br>
<div id="text"> text</div>
The Jquery is :
$(document).ready(function () {
if ($('#type').val() == "Parcel") {
$('#height').show();
}
else {
$('#height').hide();
}
});
https://jsfiddle.net/rovvLt9e/1/
Try to use change event to accomplish your task,
$(document).ready(function() {
var elem = $('#height');
var radios = $(':radio[name=type]').change(function() {
elem.toggle(radios.filter(":checked").val() == "Parcel");
});
});
And note, you have to use attribute selector here as there was no element with id type.
DEMO
There is no element with id type. Bind change event to input[name=type] and toggle visibility like following.
$('input[name=type]').change(function() {
$('#height').toggle(this.value=="Parcel");
});
$('input[name=type]:checked').change(); //to set initial state
UPDATED FIDDLE
Try using selector #type input , .change() event
$(document).ready(function() {
var h = $("#height");
$("#type input").change(function() {
if (this.checked && this.value == "Parcel") {
h.show();
} else {
h.hide();
}
}).change()
});
jsfiddle https://jsfiddle.net/rovvLt9e/6/

when option selected do stuff ( btw, all the elments have dynamic id)

I searched for similar questions, I found some but their solution did't help me.
For example:
First question
Second question
My problem is:
I have a table that the user can add rows dynamically, so I am creating a unique id for each row and all elements inside as well.
each row have two text fields and select with two options, and when you select one of the option the text feild should be dislpay:block and the second will be display: "none", depending on your choice.
I built here some example that will shows the general structure (JSFiddle)
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>
<input id="description-first-1" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-1" name="description-second-2" type="text" placeholder = "second">
<select id="select-1">
<option>
<option id="first-opt-1">1</option>
<option id="second-opt-1">2</option>
</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="description-first-2" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-2" name="description-second-2" type="text" placeholder = "second">
<select id="select-2">
<option>
<option id="first-opt-2">1</option>
<option id="second-opt-2">2</option>
</option>
</select>
</td>
</tr>
$(function() {
$("#select-1").change(function() {
if ($("#first-opt-1").is(":selected")) {
$("#description-first-1").show();
$("#description-second-1").hide();
} else {
$("#description-first-1").hide();
$("#description-second-2").show();
}
}).trigger('change');
});
http://jsfiddle.net/8vz121rq/9/
In my example for that matter you can seen that there are only 2 rows but it can also be 10 rows with different id's.
How to get jquery identify which row and all the elements inside of it i'm changing if the id's of all elements is dynamic ?
First of all, you need event delegation as the rows are dynamically generated, such as:
$("table").on("change", "[id^='select']", function() {
// do your stuf
});
Or in your case:
$("table").on("change", "#select-1", function() {
// do your stuf
});
So, is this what you needed?
$(function() {
$("table").on("change", "[id^='select']", function() {
var $this = $(this);
var $row = $this.closest("tr");
var ID = this.id.replace(/^[^\-]+\-(\d+)$/gi, '$1');
var sIndex = $this.prop('selectedIndex');
var part = sIndex === 2 ? "second" : "first";
if (!sIndex) {
$row.find("input").show();
return;
}
$row.find("input").hide();
$row.find("#description-" + part + "-" + ID).show();
});
});
Demo#Fiddle
P.S. The above is purely based on your markup and ID structure!

Once button is click the dropdown will reset

I have this script:
$(function () {
/* function for dynamic numbering */
function updateRowOrder() {
$('td.id').each(function (i) {
$(this).text(i + 1);
});
}
/* if input textValue get press keyboard enter */
$("#textValue").keydown(function (e) {
if (e.keyCode == 13) {
/* if get so trigger to addBtn */
$("#addBtn").trigger("click");
$(this).val("");
}
});
$(document).on("click", "#addBtn, .delRow ", function (e) {
/* if document clicked is addBtn */
if ($(this).is("#addBtn")) {
/* Append template script to table tbody */
$($("#template").html()).appendTo("#dataTables-example tbody");
/* Append textValue value to class rowValue and change classname */
$(".rowValue").append($("#textValue").val()).attr("class", "rowValues");
$(".taskValue").append($("#task").val()).attr("class", "taskValues");
$(".roleValue").append($("#role").val()).attr("class", "roleValues");
var appendComma = ($(".roleValue1").val() == '') ? '' : ' , ';
$(".roleValue1").append(appendComma + $("#id_select").val()).attr("class", "roleValues");
/* Update Numbering */
updateRowOrder();
}
else {
/* Just remove the tr on the click of a mouse */
$(this).closest("tr").remove();
/* Update Numbering */
updateRowOrder();
}
$('.up, .down').click(function(e){
e.preventDefault();
var row = $(this).parents("tr:first");
//selects all of row's tds except position number
// var row = $(this).parents("tr:first");
// selects the entire row
if ($(this).is(".up")) {
row.insertBefore(row.prev());
}
else if ($(this).is(".down")){
row.insertAfter(row.next());
}
else{
}
$('tbody tr[class="move"] td:first-child').each(function(idx, item) {
$(this).text(idx+1);
});
});
/* clearing input textValue */
$("#textValue").val("");
$('select option').filter(function(i){ return this.hasAttribute('selected') }).prop('selected', 'selected');
});
});
I include here that when addBtn click the drop down o select tag will reset into its default value.
This code:
$('select option').filter(function(i){ return this.hasAttribute('selected') }).prop('selected', 'selected');
And this is my sample table:
<table class="table table-bordered" id="dataTables-example">
<thead>
<tr>
<td>Activity</td>
<td><input type="text" id="textValue" class="typeahead form-control"/></td>
</tr>
<tr>
<td>Task Code</td>
<td>
<select name="" id="task" class="selectpicker form-control">
<option value="default" disabled="disabled" selected="selected">Default</option>
<?php
foreach($tasktype as $task)
{
?>
<option value="<?=$task['TaskCode']?>"><?=$task['TaskCode']?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Primary Role Code</td>
<td>
<select name="" id="role" class="selectpicker form-control">
<option value=""></option>
<?php
foreach($rolecode as $role)
{
?>
<option value="<?=$role['RoleName']?>"><?=$role['RoleName']?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Secondary Role Code</td>
<td>
<select id="id_select" class="selectpicker form-control" multiple data-live-search="true">
<?php
foreach($rolecode as $role)
{
?>
<option value="<?=$role['RoleName']?>"><?=$role['RoleName']?></option>
<?php
}
?>
</select>
</td>
</tr>
</thead>
</table>
<button type="button" class="btn btn-primary" id="addBtn"><i class="fa fa-plus fa-fw"></i>Add</button>
When I try it, I select values then click the Add button but still it not reset but instead it display the one I selected. And when I add again without choosing anything in the drop down, the value is null or no value.
I think it is working at the back-end but not working on the one I display.
Anyone tell me what is the problem?
Set the value on the select, not the selected property on the option.
function displaymessage() {
$("select").each(function() { this.selectedIndex = 0 });}
This Will reset the drop down value to index number 0.

Display the selected value in another DIV element

I am asking the user to select his/her gender . Later on I want to display the selected gender in another <div> element as shown below. How can I do this?
<div id="v1">
<table>
<tr>
<td>Male or Female</td>
</tr>
<tr>
<td align="left">
<select id="gender" name="gen">
<option>Male</option>
<option>Female</option>
<option>Do not wish to specify</option>
</select>
</td>
</tr>
</table>
</div>
Now I need to display the selected value in another <div>:
<div id="v2">
<h2>I WANT TO DISPLAY THE SELECTED VALUE HERE</h2>
</div>
Try this code if you are using jQuery.
$("#gender").change(function() {
$("#v2 h2").html($(this).val());
});
Demo
Try this:
$(function () {
$("#selection").on("change", function () {
var text = $(this).find('option:selected').text();
$('#v2 h2').text(text);
});
});
Demo here
To get also the value:
$(function () {
$("#selection").on("change", function () {
var text = $(this).find('option:selected').text();
var value = $(this).val();
var string = 'Text: '+text+' - Value: '+value;
$('#v2 h2').text(string);
});
});
Demo here
$(document).ready(function() {
$('#contact-location').change(function(){
var location = $(this).val(),
div = $('#' + location);
var txt=$('#txtfiled11').val();
div.append(txt);
$('.hide').hide();
div.show();
});
});
Another Demo
Update Fiddle DEMO with TEXTFIELD VALUE3
Use
$("#dropdown").prop("disabled", false);

Categories

Resources