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

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);

Related

how to enter values ​into select options

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>

How can I send an array of values from the inputs to the controller

I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;

How to post form submit to database along with ID logged in console

I am trying to add a form submission in a bootstrap modal along with an ID of the row that was clicked to open to modal to a database. I can add the ID alone and I can add the form submission alone, but I cannot combine these two sources of information in the same database.
In the code below I get the ID (var uid), and it is logged in the console.
Is it possible to add that logged value to the ajax post? And how can I do that, so it is sent along with the form values?
$(document).ready(function () {
$(document).on('click', '#getUser', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
console.log(uid);
$("#bestilform").on("submit", function(e) {
var formURL = $(this).attr("action");
var antal_ordre = $("antal_ordre").val();
var navn_ordre = $("navn_ordre").val();
var email_ordre = $("email_ordre").val();
var telefonnummer_ordre = $("telefonnummer_ordre").val();
$.ajax({
url: formURL,
type: "POST",
data: {'id': uid, 'antal_ordre': antal_ordre, 'navn_ordre': navn_ordre, 'email_ordre': email_ordre, 'telefonnummer_ordre': telefonnummer_ordre},
dataType: 'json'
})
hide modalcontant and show order
success: function(data, textStatus, jqXHR) {
$("#seordre").show();
$("#afgivordre").hide();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
//submit form with id #submitForm
$("#submitForm").on('click', function() {
$("#bestilform").submit();
});
});
</script>
this data: 'id': uid just gives me a 0 in the database. I am converting to integer in my php file.
Define your var uid outside of the function which sets it and the function which needs it. Make it global for both functions. (not the best way to do). The better way to pass the parameter to the function which does submit. In this case you'll achieve consistency and your UID never will be undefined. You code may looks like ...
$(document).ready(function() {
//define variable
var uid;
$(document).on('click', '#getUser', function(e) {
e.preventDefault();
// set it in one function
uid = $(this).data('id'); // get id of clicked row
console.log(uid);
// and call another one
$("#bestilform").submit();
});
$("#bestilform").on("submit", function(e) {
var formURL = $(this).attr("action");
var antal_ordre = $("select[name$='antal_ordre']").val();
var navn_ordre = $("input[name$='navn_ordre']").val();
var email_ordre = $("input[name$='email_ordre']").val();
var telefonnummer_ordre = $("input[name$='telefonnummer_ordre']").val();
// uid will be avaiable over here
$.ajax({
url: formURL,
type: "POST",
data: {
'id': uid,
'antal_ordre': antal_ordre,
'navn_ordre': navn_ordre,
'email_ordre': email_ordre,
'telefonnummer_ordre': telefonnummer_ordre
},
dataType: 'json'
});
// something else???
return false;
});
//submit form with id #submitForm
$("#submitForm").on('click', function() {
$("#bestilform").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="getUser" data-id="67">click me</td>
</tr>
</table>
<br><br>
<form method="post" action="bestil.php" data-toggle="validator" role="form" class="form-group" id="bestilform">
<!-- antal måltider, som køber vil bestille-->
<div class="form-group">
<label>Antal måltider</label>
<select class="form-control selectpicker" name="antal_ordre">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<!-- navn på køber-->
<div class="form-group">
<label for="InputName1">Fulde Navn</label>
<input name="navn_ordre" type="text" class="form-control" id="exampleInputName1" placeholder="Indtast dit navn">
</div>
<!-- email på køber-->
<div class="form-group">
<label for="InputEmail1">Email</label>
<input name="email_ordre" type="email" class="form-control" id="exampleInputEmail1" placeholder="Indtast din e-mail" data-error="Hov! Det er vist ikke en email...">
<div class="help-block with-errors"></div>
</div>
<!-- telefonnummer på køber-->
<div class="form-group">
<label for="InputPhonenumber1">Telefonnummer</label>
<div class="input-group">
<span class="input-group-addon">+45 </span>
<input name="telefonnummer_ordre" data-minlength="8" type="number" class="form-control" id="exampleInputPhone1" placeholder="Indtast dit telefonnummer">
</div>
</div>
<!--modal footer-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" data-toggle="modal" data-target="#lavbestillingaccepter">Tilbage
</button>
<button type="button" class="btn btn-primary" id="submitForm" form="bestilform">Køb Måltid!
</button>
</div>
</form>

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');
});

Repeating data after form submit

I have 4 links ( view car, hand car, retrieve car and add car). Every link is load by Ajax. The problem is in (add car), the first time I click submit the data gets recorded in the database once ... when I click (view car) and go back to (add car) and submit the form again it adds the data to the database 3 times. Also when I press (view car) and back to add car and submit the from again it records the data 6 times.
ajax.js
$(document).ready(function(){
$('#viewCar').click(function(){
$("#show").load('view');
});});//end click
$(document).ready(function(){
$('#handCar').click(function(){
$("#show").load('handcar');
});//end load
});//end click
$(document).ready(function(){
$('#retrieveCar').click(function(){
$("#show").load('retrieve');
});//end load
});//end click
$(document).ready(function(){
$('#addCar').click(function(){
enter code here $("#show").load('add');
});//end load
});//end click
$(document).ready(function(){
$("#submit").click(function(e)
{
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '')
{
console.log('error some form is empty !!');
}
else
{
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function()
{
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
}); //end click
}); //end of ready
car_links.html
<div class="container">
<ul class="ul">
<li class="li"><a id="viewCar" href="#" >view cars</a></li>
<li class="li"><a id="handCar" href="#">hand car</a></li>
<li class="li"><a id="retrieveCar" href="#">retrieve car</a></li>
<li class="li"><a id="addCar" href="#">add a car</a></li>
</ul>
car_add.html
<div class="col-md-4 col-md-offset-4">
<form id="cForm" class="form-horizontal" >
<?php echo validation_errors(); ?>
<legend>add a new car</legend>
<div class="form-group">
<label class="col-sm-5 control-label" for="LN">License #:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LN" name="LN" value="" /></li>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="LT">License Ltr:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LT" name="LT" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Model">Model:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Model">
<option value="Toyota"> Toyota</option>
<option value="Audi"> Audi</option>
<option value="Hundai"> Hundai</option>
<option value="BMW"> BMW</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Year"> Year:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Year">
<option value="2010"> 2010</option>
<option value="2014"> 2014</option>
</select>
</div>
</div>
<div class="form-actions btn-action">
<button class="btn btn-success" id="submit" value="save" type="button" name="submit">save</button></li>
<button class="btn btn-danger" type="reset" name="reset"> Reset </button></li>
</div>
</form>
</div>
For starters you have each click function in its own .ready function. The .ready function is initiated when the page is loaded. If you want the function to load only on a click then you need to place the click function into a function like this.
$(function() {
$('#viewCar').click(function() {
$("#show").load('view');
});
$('#handCar').click(function() {
$("#show").load('handcar');
});
$('#retrieveCar').click(function() {
$("#show").load('retrieve');
});
$('#addCar').click(function() {
$("#show").load('add');
});
$("#submit").click(function(e) {
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '') {
console.log('error some form is empty !!');
} else {
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function() {
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
});
}
If that doesn't work or is not what you wanted please leave me a comment.

Categories

Resources