Show/Hide div send all data to database - javascript

I have this show/hide div. And I am running into couple issues. I am using CodeIgniter by the way.
First : When I select real-estate the div shows. But if I select Service, the real-estate div won't hide. (Service has no div).
Second : If I select real-estate and fill out the form, and I change my mind and select automobile and fill out the form then send to database, I get all the fields from real-estate and automobile into my database. Which is not what I want.
Third : Is there a different approach if I wanna add more categories and more divs show/hide?
<select id="catid_1" name="catid_1">
<option value=""></option>
<option value="5">Real-Estate</option>
<option value="8">Automobile</option>
<option value="10">Service</option>
</select>
<!--Auto-->
<div id="8" class="forms">
Energie :
<select name="energy">
<option></option>
<option value="Gasoline">Gasoline</option>
<option value="Diesel">Diesel</option>
<option value="GPL">GPL</option>
<option value="Electric">Electric</option>
<option value="Hybrid">Hybrid</option>
</select><br />
Transmission :
<select name="tans">
<option></option>
<option value="Manuel">Manuel</option>
<option value="Automatic">Automatic</option>
</select><br />
Miles :
<input type="text" name="mile"/><br />
Year :
<input type="text" name="year"/><br />
</div>
<!--Realestate-->
<div id="5" class="forms">
Room :
<input type="text" name="room"/><br />
Surface :
<input type="text" name="surface"/><br />
</div>
<!--End Tech-->
$(function() {
$(".forms").hide();
$("#catid_1").change(function() {
var e = $(this).val();
if(e == '8' || e == '5') {
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
});
// Bind to the submit
$('#submit').click(function(e){
e.preventDefault();
// Parse the data only for the displayed div.
var resolve_data = function() {
var output = {};
// Here you place the acceptable fields.
$('.form-active input, .default input').each(function() {
output[$(this).attr('name')] = $(this).val();
});
return output;
};
// Submit the form here.
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: resolve_data(),
beforeSend: function(xhr, settings){
// Before sending, check the data.
alert(settings.data);
},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
});
});

first: service show/hide is not working because you're putting a conditional on the ID:
if(e == '8' || e == '5') { // <<-- remove this conditional
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
second: When you're doing your update, check the value of the drop down box and only update the fields that belong to that choice. Your form should be sending along the value of the option, so that's not to hard to do. For instance, if the select value is 5, only update the room and surface fields in your database. Don't try to clear the form when switching choices, it's safer to do this in the back end.
If you insist on doing it front end, put an actual form in there and .reset() it when changing options.
third: probably, but this seems OK no? Are you not happy with it?
http://jsfiddle.net/zf9BN/1/

Related

select2 not letting my other scripts work

Sir, my ajax isnt loading when i use select2 plugin .
it works fine when i remove it. the blur event is working.
but i want to be able to search in the dropdown, and somehow ajax isnt working
this part isnt working
$("#bank_id").focus();
so due to above script not working the blur event in the code below isnt working.
this is the script and html
<div class="col-md-6">
<div class="form-group">
<label>Bank<span><font color="red"></font></span></label>
<select class="form-control select2" name="bank_id" id="bank_id">
<c:choose>
<c:when test="${bankDetailsEdit.bank_id != 0}">
<option value="${bankDetailsEdit.bank_id }" >${bankDetailsEdit.bankName }</option>
</c:when>
<c:when test="${bankDetailsEdit.bank_id == 0}">
<option disabled selected>Select Bank</option>
</c:when>
</c:choose>
<c:forEach var="bank" items="${bankMasterDetails}">
<option value="${bank.bank_id}">${bank.bank_name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Bank Branch Name<span><font color="red"> </font></span></label>
<select class="form-control select2" name="bankBranchId" id="op1" >
<option value="${bankDetailsEdit.bankBranchId }" >${bankDetailsEdit.bankBranchName }</option>
<c:forEach begin="0" end="100" varStatus="loop">
<option></option>
</c:forEach>
</select>
</div>
</div>
<script>
$('.select2').select2();
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#bank_id").focus();
$("#bank_id").on('blur change',function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var bank_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'bank_id':bank_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/bankBranchDetails",
data : ({
'bank_id':bank_id
}),
success: function (bankList) {
$('#op1').empty();
var opt = '<option disabled selected>Select Branch</option>';
for (var i = 0; i < bankList.length; i++) {
$('#op1').append(opt);
opt = new Option(bankList[i].bank_branch_name,bankList[i].bank_branch_id);
}
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
$("#op1").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var branch_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'branch_id':branch_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/branchIfscDetails",
data : ({
'branch_id':branch_id
}),
success: function (data) {
var ifsc = data;
document.getElementById("ifsc").value=ifsc;
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
});
</script>
From this page: https://select2.org/programmatic-control/events:
Select2 has an internal event system that works independently of the
DOM event system, allowing adapters to communicate with each other.
You are tied to using the plugins event handling mechanism so the first paremeter of the jQuery on function needs to be changed.
from $("#bank_id").on('blur change',function(){
to $("#bank_id").on('select2:select',function(){
Unfortunately $("#bank_id").focus(); will not work because it is not listed in the available select2 events.
You're success callback function in the first event listener, which tries to generate options element for the 2nd select box will also not work as select2 has a different way of adding options dynamically through AJAX as listed in this page: https://select2.org/data-sources/ajax
You need to use $('#bank_id').select2('open'); instead of $("#bank_id").focus(); to open the bank selection on page load.
You can check their documentation.

Access the label text of a datalist option using jquery

I am filling a data-list in html using data from a Json . The options are being appended to the data-list with the value and label text . on click of an option , I want the value and the text to be inserted into a form text field .
The value of the option can be accessed and is successfully inserted into the text field. But I am not able to access the label of the option to insert it.
I have tried using $(this).innerhtml(); , $(this).text(); , $(this).label(); , $(this).innerhtml(); and so on..
all of which turned out to return null value (undefined) instead of the required string.
$(document).ready(function ()
{
$.ajax({
type: 'POST',
url: '#Url.Action("MyJsonFunction")',
datatype: 'json',
success: function (data) {
$.each(data, function (index, data) { $("#myid1").append("<option value='"+data.Value+"'label='"+data.Text+"'></option > ");})},
error: function ()
{
alert("Something went wrong!");}});
$("#myid2").change(function ()
{
var s = $(this).val();
var d = $(this).html();
alert(d);
$("#input1").val(s);
$("#input2").val(d);
});
});
The value of the option is being inserted to the input text field but the label of the option is null when i try to access it .
when i alert it , it displays either an empty string or "undefined" .
$('body').on('change','#myid1',function(){ alert( $(this).find(':selected').attr('label') ) });
Please try this code. I am sure this will work
Try this solution.you have to make any one option as selected, because on form load,none of your options are selected and it will surely alert as undefined.
$(document).ready(function ()
{
$("#colors").trigger('change');
});
$("#colors").change(function () {
var d = $('#colors').find("option:selected").val();
alert(d);
$('#selvalue').val(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<label for="color">Favorite Color</label>
<input list="colors" name="color">
<datalist id="colors">
<option selected=selected value="Green">
<option value="Red">
<option value="Blue">
<option value="Yellow">
<option value="Orange">
</datalist>
<input type='text' id='selvalue' placeholder='Display seleted value'/>

Select box options not getting selected by jquery with ajax response data

I have an update form in which the data is pre-populated by an ajax call. All the data is getting populated well except the select box. Im using jquery to populate data.
My select code:
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<!-- <option value="" selected></option> -->
<option value="F">Female</option>
<option value="M">Male</option>
</select>
</div>
Ajax call:
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName);
$("#middleName").val(cust.middleName);
$("#gender2").val(cust.gender);
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
I have tried these but none worked:
$('gender2 option[value='+cust.gender+']').attr('selected', 'selected');
$('#gender2 option[value='+cust.gender+']').prop('selected', true);
$("div.test select").val(cust.gender);
Note: im getting data from backed as cust.gender=M for male and cust.gender=F for female.
Try
$('#gender2').change(function() {var selectvalue =$('#aioConceptName').find(":selected").val(cust.gender);});
$("#gender2").change(function() {
//your ajax
});
Try this
When it comes to select box it requires change() event,
$.ajax({
type: "POST",
url: 'fetchData',
data: {
'custId': custID,
},
success: function (paxUpdateData) {
var cust = jQuery.parseJSON(paxUpdateData);
$("#firstName").val(cust.firstName).trigger('change');
$("#middleName").val(cust.middleName).trigger('change');
$("#gender2").val(cust.gender).trigger('change');
},
error: function (e) {
alertify.error('Error in retreiving details');
}
});
See This Demo is working , now u can put your ajax function inside document ready function , and please check in ajax Response console.log() value is same as your select option value.
$(document).ready(function(){
$('#gender2').val("O");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test " id="test">
<select id="gender2" name="gender2" class="required">
<option value="F">Female</option>
<option value="M">Male</option>
<option value="O">Other</option>
</select>
</div>

Fetching data through ajax and then apply filter using select

I have 3 different select menu: 1.Category 2.State 3.City
I am using ajax to fetch the data on "#searchresult" by using jquery on change method that send data on PHP.
Fetching is going properly but only for one "select" option.
What I want is when user change another "select" option, it will update the current "#searchresult" fetched data.
Like: Suppose, on changing "category" to "car", it fetch all the data of "cars" on "#searchresult" and now on "state" change to "new york", it update the "#searchresult" that are in new york.
I tried many different approches like using multiple if statements to find whether the select is choosen or not, but reached no where.
Thanks in advance.
My code is:
$(document).ready(function() {
$("#category").change(function() {
var data = $("#category option:selected").val();
var category = $("#category option:selected").text();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "category",
data: {
data: data
},
dataType: 'json',
cache: false,
success: function(response) {
$("#searchresult").html("");
for (var i = 0; i <= 5; i++) {
$("#searchresult").append('<div class="col-12 col-sm-10 col-md-4 col-lg-3 col-xl-2 merchant" style="background-image: url(https://im.proptiger.com/1/1543935/6/green-villa-elevation-7990949.jpeg?width=380&height=285);"> <div class="filter"></div> <span class="category">' + category + '</span> <div class="col align-self-end"> <p>' + response.contractor[i].first_name + '</p> <span>' + response.contractor[i].city_name + ',' + response.contractor[i].state_name + '</span> </div> <div class="slideup"> <p>More info?</p> Profile </div> </div>');
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
and PHP is sending data in the form of json.
Thanks
#user5745970 here is sample fiddle I created to give you an idea on what needs to be done. Link to the fiddle is below
The idea is to have 3 different change events for each of your select and trigger a call to your server. What you need to do is send the other select values as data if selected. For example, if you're changing the City when the category is already selected, you need to send both category and city to your server to get you the response. If all 3 server side calls return the same JSON structure, then you can have only 1 success and error callback.
Do change the urls, method types and callbacks accordingly to match what you need.
$(document).ready(function() {
var category = '';
var state = '';
var city = '';
$("#category").on('change', function() {
category = $("#category option:selected").text();
// here you need to check if state or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', category, handleCategorySuccess, handleCategoryError)
});
$("#state").on('change', function() {
state = $("#state option:selected").text();
// here you need to check if category or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', state, handleStateSuccess, handleStateError)
});
$("#city").on('change', function() {
city = $("#city option:selected").text();
// here you need to check if state or category is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', city, handleCitySuccess, handleCityError)
});
});
var ajax = function(url, method, data, successCallBack, errorCallBack) {
$.ajax({
type: method,
url: url,
data: data,
dataType: 'json',
cache: false,
success: successCallBack,
error: errorCallBack
});
}
function handleCategorySuccess(response) {
alert(response);
}
function handleCategoryError() {
alert('error');
}
function handleStateSuccess(response) {
alert(response);
}
function handleStateError() {
alert('error');
}
function handleCitySuccess(response) {
alert(response);
}
function handleCityError() {
alert('error');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
JSFiddle

On Clicking Select Option, make dropdown dissapear

I have a couple form elements that when clicked update the database and disappear.
At first, I have a button that reads Check In. Upon clicking it, the database is updated and a dropdown is presented in place of the button. In the dropdown, there are locations for the user to choose, that have values of their corresponding location-number, which upon clicking update the database. The last option is labeled Check Out, and upon clicking it, the database is supposed to be updated one last time, and then red text saying Checked Out should appear.
Here's my code:
<button class="checkIn">Check In</button>
<form method='post' class='myForm' action=''>
<td>
<select name='locationSelect' class='locationSelect'>
<option value='1'>Exam Room 1</option>
<option value='2'>Exam Room 2</option>
<option value='3'>Exam Room 3</option>
<option value='4'>Exam Room 4</option>
<option value='CheckOut'>Check Out</option>
</select>
</form>
and here is the jquery
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.locationSelect').hide();
$('.finished').hide();
});
$('.checkIn').click(function(){
$e = $(this);
$.ajax({
type: "POST",
url: "changeloc.php",
data: "checkIn="+$(this).val(),
success: function(){
$('.checkIn').css("display","none");
$('.locationSelect').show();
}
});
});
$('.locationSelect').change(function(){
$e = $(this);
$.ajax({
type: "POST",
url: "changeloc.php",
data: "locationSelect="+$(this).val(),
success: function(){
}
});
});
$('.locationSelect option[value="CheckOut"]').click(function(){
$e = $(this);
$.ajax({
type: "POST",
url: "changeloc.php",
data: "checkOut="+$(this).val(),
success: function(){
$('.locationSelect').css("display","none");
$('.finished').show();
alert('done');
},
error: function(request){
alert(request.responseText);
}
});
});
</script>
The problem is that everything works until the user hits Check Out, and then red text doesn't appear and the dropdown doesn't disappear. What's the problem?
Thanks for any and all help!
Having the check out button in a drop down select list isn't right. These lists are for options, not for commands.
Why don't you have a checkout button that following the list, and is hidden
<button class="checkOut" style="display:none;" value="Check Out" />
This way, once your room list has been populated, you can simply set the check out button to visible again. This means the page logics flows (checkin - select - checkout).
For the red text, replace the dropdown with something like this?
$(".checkOut").click(function(e) {
$(".locationSelect").html("<p style='color:red'>Checked out!</p>");
});
Just food for thought.
Alternatively, you could check for the selected option in the $('.locationSelect').change() handler.
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
// Perform checkout logic.
}
else {
// Perform room select logic.
}
});

Categories