how to enter values ​into select options - javascript

I want to know how to enter the onchange () result value into the select option, then make it an option
I have a database value, namely REGULAR PACKAGE with a value of 3000 and the value of the package YES 12000 results. I want to enter this value into the select option
javascript
<div class="form-group col-md-3">
<label for="inputEmail4">TARIF REGULER</label>
<input type="text" name="" class="form-control" id="tarif" placeholder="">
</div>
$(document).ready(function(){
$('#kec_order').change(function(){
var id=$(this).val();
$.ajax({
url : "<?php echo base_url();?>order/get_tarif",
method : "POST",
data : {id_tarif: id},
async : false,
dataType : 'json',
success: function(data){
$('#tarif').val(data[0].reguler);
}
});
});
});
//result value 12000
and I want to enter a value ('#tarif') into the select option
div class="form-group col-md-3">
<label for="pakey">Pilih paket</label>
<select class="form-control" name="paket" id="pilihpaket">
<option >Paket Reguler</option>
<option value="">Paket Yes</option>
</select>
</div>

Related

Dependent select menu in Jquery Ajax

I want to create a form so that when the user selects the State, the office box will show the number of offices in that State, when the user selects the specific City will show the number of offices in that City and when the user selects the Hometown, the number of offices in that Home Town will only show in the select box. Please see the attached picture for a better understanding. I am completely new in this field so I can't do.
This is my HTML code
<div class="row">
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">State</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">City</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">Home Town</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">Office</label>
<select name="" id="" class="form-control"></select>
</div>
</div>
This is jquery code
$(document).ready(function () {
$('#division-dd').on('change', function () {
var idDivision = this.value;
$("#office-dd").html('');
$.ajax({
url: "{{url('get-division-offices')}}",
type: "POST",
data: {
division_id: idDivision,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (result) {
$('#office-dd').html('<option value="">Select City</option>');
$.each(result.division_offices, function (key, value) {
$("#office-dd").append('<option value="' + value
.id + '">' + value.office_name + '</option>');
});
$('#office-dd').html('<option value="">Select Hometown</option>');
}
});
});
$('#distric-dd').on('click', function () {
var idDivisionOffice = this.value;
$("#office-dd").html('');
$.ajax({
url: "{{url('get-distric-offices')}}",
type: "POST",
data: {
distric_id: idDivisionOffice,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (res) {
$('#office-dd').html('<option value="">Select Hometown</option>');
$.each(res.distric_offices, function (key, value) {
$("#office-dd").append('<option value="' + value
.id + '">' + value.office_name + '</option>');
});
}
});
});
});

HTML radio button always submits last option to PHP

No matter what option is chosen, this code will always submit the second option to PHP.
Here is my form:
<div class="modal">
<div class="modalContent">
<div class="modalHeader">
<p>Add an income / expense</p>
<span class="closeBtn" onclick="closeit()">×</span>
</div>
<form class="insertData" action="insert.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="category">Category</label>
<select name="category" required>
<option value="food">Food</option>
<option value="bills">Bills</option>
<option value="rent">Rent</option>
</select>
<label for="amount">Amount</label>
<div class="radios">
<input type="radio" name="ie" value="income"><p>Income</p>
<input type="radio" name="ie" value="expense"><p>Expense</p>
</div>
<input type="number" name="amount" required>
<label for="description">Description (optional)</label>
<textarea type="text" name="description"></textarea>
<input id="start" type="text" name="start" value="" required style="display:none;">
<input id="end" type="text" name="end" value="" required style="display:none;">
<input class='submitBtn' type="submit" name="" value="Submit">
</form>
</div>
</div>
Here is the PHP (just echoing for debugging purposes right now):
if (isset($_POST['name'])) {
echo htmlspecialchars($_POST['ie']);
}
The data is going in via AJAX here (using FullCalendar)
select: function (start, end) {
document.getElementsByClassName('modal')[0].style.display = 'block';
document.getElementById('start').value = $.fullCalendar.formatDate(start,
"Y-MM-DD HH:mm:ss");
document.getElementById('end').value = $.fullCalendar.formatDate(end,
"Y-MM-DD HH:mm:ss");
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});
},
No matter what option is chosen it will always submit 'expense'.
If I swap them around on the form then it will always submit 'income', so it seems to be always the last option is being submitted.
This error occurs because you loop all element has name attribute, and get the value. Including radio button. If you want to get selected radio button you must add if, for check if radio button has checked.
You can use code below, this code simpleer then you must check radio button:
$('form.insertData').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
$.ajax({
url: url,
type: type,
data: $('form.insertData').serialize(),
success: function (response) {
calendar.fullCalendar('refetchEvents');
location.reload();
document.getElementsByClassName('modal')[0].style
.display = 'none';
}
});
return false;
});

How to store onchange selected dropdown value into hidden input field?

This is my jquery ajax code where i have done dropdown populated things and storing onchange id into hidden input field.Why is it not storing into id field? I checked in alert if the value is coming or not. Value is coming but it's not storing into hidden field.
<script type="text/javascript">
$(document).ready(function() {
$("#village").change(function(){
$('#hiddenVillage').val( $(this).val());// this code to store id into this field
});
$('#taluka').change(function()
{
var myObject = {talukaid: $(this).val(),districtid: $('#district').val(), state_id:$('#stateDrop').val()};
var cpytaluka= $(this).val();
$('#hiddenTaluka').val($(this).val(cpytaluka));// this code to store id into this field
$.ajax({
type : "get",
url : "villages.htm",
data : myObject,
success : function(response) {
$('#village').append(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
$('#district').change(function()
{
var myObject = {districtid: $(this).val(), state_id:$('#stateDrop').val()};
var cpydistrict= $(this).val();
$("#hiddenDistrict").val($(this).val(cpydistrict));// this code to store id into this field
$.ajax({
type : "get",
url : "taluka.htm",
data : myObject,
success : function(response) {
$('#taluka').append(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
$('#stateDrop').change(function()
{
var state = $(this).val();
$("#hiddenstate").val(state);// this code to store id into this field
$.ajax({
type : "get",
url : "district.htm",
data : "State_ID=" + state,
success : function(response) {
$('#district').append(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
});
</script>
This is my form where i have included input field below every dropdown field
<form action="search-Leaders-list" id="searchleader" method="GET">
<div class="row">
<div class="form-group col-lg-3">
<select id="stateDrop"
title="State <i class="fa fa-angle-down"></i>">
<option value="small">State</option>
<c:forEach items="${stateList}" var="state">
<option value="${state.state_Id}">${state.state_Name}</option>
</c:forEach>
</select> <input type="hidden" id="hiddenstate">
</div>
<div class="form-group col-lg-3">
<select id="district">
<option value="small">District</option>
</select> <input type="hidden" id="hiddenDistrict">
</div>
<div class="form-group col-lg-2">
<select id="taluka">
<option value="small">Taluka</option>
</select> <input type="hidden" id="hiddenTaluka">
</div>
<div class="form-group col-lg-2">
<select id="village"
title="Villages <i class="fa fa-angle-down"></i>">
<option value="small">Villages</option>
</select> <input type="hidden" id="hiddenVillage">
</div>
<div class="form-group col-lg-2">
<input type="submit" value="Search" class="submit">
</div>
</div>
</form>
Kindly please help me.
i don't really get your question. if you want to get the id of this dropdown box and save it in the hidden field.
$('#taluka').change(function()
{
$('#hiddenTaluka').val(this.id);
or
using
$('#hiddenTaluka').val($(this).attr('id'));
if you want to store the value of dropbox selected item.
var cpydistrict= $(this).val();
$("#hiddenDistrict").val(cpydistrict);

How to populate a modal box SELECT form control before it is shown using the shown.sb.modal event

I have a simple modal popup that edits an item retrieved from the back end. The for has several input and select controls. The input form controls work properly but the select controls are not pre-populated as intended.
The basic architecture of my functions as follows:
function BootboxEditItem(id) {
$.ajax({
// Load back end data
})
.done(function(data) {
var itemData = data;
$.ajax({
// Load form template for modal
url: '/modal/item/edit-item.html',
......
})
.success: function (data) ({
var box = bootbox.confirm({
// Set up bootbox buttons;
},
callback: function(result){
// Post edited data back to the server
}
)};
box.on("shown.bs.modal", function(e) {
// Populate the modal here using data from the backend.
// This is where the problem lies!
})
box.modal("show");
});
}
Below is the full JavaScript code:
function BootboxEditItem(id) {
var itemDao = '';
$.ajax({
type: "GET",
contentType: "application/json",
url: "/api/item/edit/" + id,
dataType: "json",
cache: false
})
.done(function (data) {
itemDao = data;
$.ajax({
type: "GET",
url: '/modal/item/item-edit-form.html',
success: function (data) {
console.log(itemDao);
var box = bootbox.confirm({
message: data,
title: "Edit Item: [" + itemDao.item.sysId + "]",
buttons: {
cancel: {
label: "Cancel",
className: "btn-danger btn-fixed-width-100"
},
confirm: {
label: "Save",
className: "btn-success btn-fixed-width-100"
}
},
callback: function (result) {
}
});
box.on("shown.bs.modal", function(e) {
console.log(e.currentTarget);
var selectItemLevel = document.getElementById('editItemLevel');
console.log(selectItemLevel);
$(selectItemLevel).empty();
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt);
});
$(e.currentTarget).find('select[name="editItemLevel"]').val(selectItemLevel);
$(e.currentTarget).find('input[name="editIdentifier"]').val(itemDao.item.identifier);
$(e.currentTarget).find('textarea[name="editItemValue"]').val(itemDao.item.itemValue);
});
box.modal('show');
}
});
});
}
Here is the code for the HTML file:
<form id="editItem" action="/api/items/save" method="post">
<input type="hidden" name="artifactId" id="artifactId" value="" />
<input type="hidden" name="editId" id="editId" value="" />
<input type="hidden" name="editSysId" id="editSysId" value="" />
<input type="hidden" name="editSortIndex" id="editSortIndex" value="" />
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemLevel">Item level:</label>
<select class="form-control" id="editItemLevel" name="editItemLevel"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="editItemClass">Item class:</label>
<select class="form-control" id="editItemClass" name="editItemClass" onchange="itemEditClassChange();"></select>
</div>
</div>
</div>
<div class="row" id="editRequirementRow">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemType">Requirement type:</label>
<select class="form-control" id="editItemType" name="editItemType"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="createIdentTemplate">Identifier prefix:</label>
<select class="form-control" id="editIdentTemplate" name="editIdentTemplate" onchange="itemEditIdentTemplateChange();"></select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="createMediaType">Media type:</label>
<select class="form-control" id="editMediaType" name="editMediaType"></select>
</div>
</div>
<div class="col-sm-6" id="editIdentField">
<div class="form-group">
<label for="editIdentifier">Identifier:</label>
<input type="text" class="form-control" id="editIdentifier" name="editIdentifier" />
</div>
</div>
</div>
<div class="form-group">
<label for="editItemValue">Item details:</label>
<textarea class="form-control" rows="5" cols="50" id="editItemValue" name="editItemValue"></textarea>
</div>
And here is the output intended for one of the SELECT controls as printed by console.log();
<select class="form-control" id="editItemLevel" name="editItemLevel">
<option value="1">Level 1</option>
<option value="2">Level 2</option>
<option value="3">Level 3</option>
<option value="4">Level 4</option>
<option value="5">Level 5</option>
<option value="6">Level 6</option>
<option value="7">Level 7</option>
<option value="8">Level 8</option>
<option value="9">Level 9</option>
<option value="10">Level 10</option>
It seems your each loop is not properly appending the <option></option>.If you have chrome developer tools and you know how to use it, put a breakpoint in this function and make sure the select options are being created and added to the DOM:
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt); //breakpoint here
});
Also, since you are already using jQuery, you could add them to the DOM like this:
$.each(itemDao.itemLevels, function (key, index) {
$(selectItemLevel).append('<option value="'+index+'">Level '+index+'</option>');
});
Thanks to #nilerafetr24, but the problem was not about appending properly. Rather it was about how to get hold of the SELECT control before being shown.
Certainly, the following doesn't work document.getElementById('editItemLevel'), but the following works $(e.currentTarget).find('select[name="editItemLevel"])'.
So, my final solution is to rewrite the loop thus; after combining with the solution suggested by #nilerafetr24 which seems more efficient:
$.each(itemDao.itemLevels, function (key, index) {
$(e.currentTarget).find('select[name="editItemLevel"]).append('<option=value="'+index'">Level '+index+'</option');
});

ajax 'change' is not fired when value 'select value is set from php

I have a form with city, state and country.
the upon selecting a city - I automatically populate the state and country via ajax from the a mysql database.
However, when I try to select from the database to the form, the ajax change is not fired.
please What am i doing wrong? How do i read from db to select and still autpopulate dependent field?
Here is my code
< script type = "text/javascript" >
function profileLocationFunction() {
$('#profilecity').change(function() {
var id = $(this).val();
var dataString = id;
$.ajax({
type: "GET",
url: "locationautocomplete.php",
dataType: 'json',
data: {
datatext: dataString,
type: 'cityselect'
},
cache: false,
success: function(data) {
$('#profilestate').html(data.message1);
$('#profilecountry').html(data.message2);
},
error: function(xhr, status, error) {
alert("Hello! ERROR!" + error);
}
});
});
}
$(document).ready(function() {
profileLocationFunction();
}); < /script>
<?PHP require_once("include/DbConfig.php");
if($_GET['type']=='cityselect') {
$stateid="";
$statedata="";
$countryid="";
$countrydata="";
//fetch state from city
$id=$_GET['datatext'];
$city_query="SELECT DISTINCT CITY.STT_ID, STATE.STT_ID, STATE.STT_NAME FROM CITY, STATE WHERE CITY.CTY_ID='".$id."' AND CITY.STT_ID = STATE.STT_ID";
$result=mysqli_query($DB_con, $city_query);
while ($row=mysqli_fetch_assoc($result)) {
$stateid=$row['STT_ID'];
$statedata=$row['STT_NAME'];
}
//fetch country
$country_query="SELECT DISTINCT STATE.CTR_ID, COUNTRY.CTR_ID, COUNTRY.CTR_NAME FROM STATE, COUNTRY WHERE STATE.STT_ID='".$stateid."' AND STATE.CTR_ID = COUNTRY.CTR_ID";
$countryresult=mysqli_query($DB_con,
$country_query);
while ($row=mysqli_fetch_assoc($countryresult)) {
$countryid=$row['CTR_ID'];
$countrydata=$row['CTR_NAME'];
}
//send result
echo json_encode(array("message1"=>'<option value="'.$stateid.'">'.$statedata.'</option>',
"message2"=>'<option value="'.$countryid.'">'.$countrydata.'</option>'));
}
?>
<div class="form-group">
<label for="city" class="col-sm-3 control-label">City*</label>
<div class="col-sm-7">
<input type="hidden" name="profileselectedcityid" id="profileselectedcityid" value='' />
<select type="text" class="form-control" name="profilecity" id="profilecity" placeholder="City">
<option selected="selected">--Select City--</option>
<?php if(!$site->FetchAllCities()) { echo '
<script type="text/javascript">
alert("ERROR");
</script>'; } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="state" class="col-sm-3 control-label">State*</label>
<div class="col-sm-7">
<input type="hidden" name="profileselectedstateid" id="profileselectedstateid" value='' />
<select type="text" class="form-control" name="profilestate" id="profilestate" placeholder="City">
<option selected="selected">--Select State--</option>
</select>
</div>
</div>
<div class="form-group">
<label for="country" class="col-sm-3 control-label">Country*</label>
<div class="col-sm-7">
<input type="hidden" name="profileselectedcountryid" id="profileselectedcountryid" value='' />
<select type="text" class="form-control" name="profilecountry" id="profilecountry" placeholder="City">
<option selected="selected">--Select Country--</option>
</select>
</div>
</div>
Try to replace your javascript code to:
function profileLocationFunction() {
var id = $(this).val();
var dataString = id;
$.ajax({
type: "GET",
url: "locationautocomplete.php",
dataType: 'json',
data: {
datatext: dataString,
type: 'cityselect'
},
cache: false,
success: function(data) {
$('#profilestate').html(data.message1);
$('#profilecountry').html(data.message2);
},
error: function(xhr, status, error) {
alert("Hello! ERROR!" + error);
}
});
}
$(document).ready(function() {
$('#profilecity').change(profileLocationFunction).change();
});
I just remove the event from function, maybe it's better.

Categories

Resources