Multiple else if in jQuery - php

I am doing dependent select box using jquery, ajax and php from same table of the database. Testpage
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "name") {
result = 'category';
alert ('test1');
} else if (action == "category") {
result = 'material';
alert ('test2');
} else if (action == "material") {
result = 'source_light';
alert ('test3');
} else if (action == "source_light") {
result = 'color_temperature';
alert ('test4');
} else {
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
I don't know why but it only works: test1 and test2. Test3 and 4 are not sent to php.
HTML file
Maybe something is wrong with select box? But these are just a select box with id's.
<select name="name" id="name" class="form-control action">
<option value="">Select name</option>
<?php echo $name; ?>
</select>
<br />
<select name="category" id="category" class="form-control action">
<option value="">Select category</option>
</select>
<br />
<select name="material" id="material" class="form-control">
<option value="">Select material</option>
</select>
<br />
<select name="source_light" id="source_light" class="form-control">
<option value="">Select source_light</option>
</select>
<br />
<select name="color_temperature" id="color_temperature" class="form-control">
<option value="">Select color_temperature</option>
</select>

What about something like this
$(document).ready(function(){
$('.action').change(function()
{
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
switch(action) {
case "name":
result = 'category';
alert ('test1');
break;
case "category":
result = 'material';
alert ('test2');
break;
case "material":
result = 'source_light';
alert ('test3');
break;
case "source_light":
result = 'color_temperature';
alert ('test4');
break;
default:
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});

Verify your drop down list under "action" class. As per your condition it won't trigger if your selected drop down item doesn't have value if($(this).val() != '').
Also make sure your expected drop down items have the value material for your test3 and source_light for your test4
Another suggestion: To load and trigger dynamic change event for drop down you can use below jQuery API:
$(document).on("change", ".action", function(){
//Your code here
});
If this doesn't solve your problem then please share your HTML or drop down data.
Updated answer: I can see there is no class "action" in your select/drop down items for material, source_light and color_temperature. That is why change actions of these drop down items are not catching in your $('.action').change(function() ... code block.

Related

I can't store all values from user inputs in the array. On window alert only the first array value shows up

I can't seem to save all the clone inputs into an array and pass the array via $.post(). For some reason it only passes the first array value that user selects.
I would like to
pass array by $.Post()
receive true or false if all items in array don't exist in mysql via a php.
I am stuck on the array only holding the value of the original input.
$(document).ready(function() {
$("#add").click(function() {
$("p:last").after($("p:first").clone(true)
.find("#Equi").val("").end()
);
});
});
$(document).ready(function() {
var ar1 = [];
var input = document.getElementById('#Equi');
$('#Equi').on('change', function() {
// $.post('UnitValidate2.php', {Unit: ar1}, function(data) {
ar1.push(input.value);
window.alert(ar1);
$.post('UnitValidate2.php', {Unit: ar1}, function(data) {
window.alert(data);
if(data == "True") {
window.alert("Move On");
} else {
window.alert("Cant call out unit");
// $("#Equi").val("");
}
});
});
});
<!--for clone -->
<p>
<label for="lname">Eqiupment:</label>
<!--<input type="text" id="Name" name="Name">-->
<input type="text" name="Unit[]" id="Equi" value="" list="namelist4" required/>
<datalist id="namelist4">
<select name="Nam" style="display:none">
<?php
// Include config file
require_once "../Login/config.php";
$conn1 = mysqli_connect($serverName, $userName, $password, $databaseName);
$sql4 = "SELECT * FROM `Status` WHERE Active = 'Yes' AND Status = 'Ready For Rent' ORDER BY Unit ASC";
result4 = mysqli_query($conn1,$sql4);
while ($row4 = mysqli_fetch_array($result4)) {
echo "<option value='".$row4['Unit']."'>".$row4['Unit']."</option>";
}
?>
</option>
</select>
</datalist>
There is still a lot unclear to me. I left out the PHP part where you fill the options in the <select> element. I also made up some elements for your <datalist> element. And ...
Since you are using jQuery you might as well use it properly: I changed your data collecting part to
var ar1=$('.Equi').get().map(el=>el.value);
where I search for all elements of class=Equi (I had to change this from id to class, since Ids must always be unique!), then extract them as a JavaScript Array (.get()), use .map() to get their .value attribute and eventually return the resulting array into ar1.
Since this snippet runs on Stackoverflow I had to comment out the actual $.post() commands but the console.log() shows what would have been posted in it.
$(document).ready(function() {
$("#add").click(function() {
$("p:last").after($("p:first").clone(true).find(".Equi").val("").end() );
});
$('.Equi').on('change', function(){
var ar1=$('.Equi').get().map(el=>el.value);
console.log("this will be posted:",ar1);
if (false) $.post('UnitValidate2.php',{Unit: ar1}, function(data){
console.log(data);
if(data == "True"){ console.log("Move On ");}
else { console.log("Cant call out unit");}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">add</button><br>
<datalist id="namelist4">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</datalist>
<p>
<label for="lname">Eqiupment
<input type="text" name="Unit[]" class="Equi" value="" list="namelist4" required/>:</label>
<select name="Nam">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p>
<p></p>

jquery ajax submit only submitting first value

I am submitting a form using jquery and ajax. I have my first select menu and depending on the value of this select menu a div that contains a different menu will become visible.
<table>
<tr>
<td>
<select required="" class="input-medium" id="foulTypes" name="foul" data-original-title="" title="">
<option value="">Select Foul</option>
<option value="85">AID - Aiding Runner</option>
<option value="1">BAT - Illegal Bat</option>
<option value="2">BBW - Block Below Waist</option>
<option value="3">BOB - Blocking Out of Bounds</option>
<option value="4">CHB - Chop Block</option>
</select>
</td>
</tr>
</table
<script>
var foulTypes = $('#foulTypes');
var select = this.value;
foulTypes.change(function () {
//We first disable all, so we dont submit data for more than 1 category
$("#catDPI, #catILF, #catOPI, #catOH, #catDH, #catILD, #catUNS, #catUNR, #catTGT").hide().find(".category").attr("disabled", true);
var $divSelectedCategory;
if ($(this).val() == '1') {
$divSelectedCategory = $("#catDPI");
$('#catDPI').show();
} else {
$('#catDPI').hide();
}
if ($(this).val() == '85') {
$divSelectedCategory = $("#catILF");
$('#catILF').show();
} else {
$('#catILF').hide();
}
if ($(this).val() == '2') {
$('#catOPI').show();
$divSelectedCategory = $("#catOPI");
} else {
$('#catOPI').hide();
}
//We now enable only for the selected category
$divSelectedCategory.show().find(".category").attr("disabled", false).val('');
});
</script>
<div id="catDPI" style="display:none;">
<select name="category" id="dpiCategory" class='category' style="width:210px;">
<option value="Playing Through Receiver">Playing Through Receiver</option>
<option value="arm bar">arm bar</option>
<option value="Grabbing">Grabbing</option>
</select>
</div>
<div id="catILF" style="display:none;">
<select name="category" id="ilfCategory" class='category' style="width:210px;">
<option value="">Select</option>
<option value="moving">Moving</option>
<option value="illegal">Illegal</option>
<option value="standing">Standing</option>
</select>
</div>
<div id="catOPI" style="display:none;">
<select name="category" id="opiCategory" class='category' style="width:210px;">
<option value="">Select</option>
<option value="restrict">Restrict</option>
<option value="holding">Holding</option>
</select>
</div>
The foulTypes .change function is working and the correct div is being displayed. The problem I am having is when I submit the form. If the #catDPI is visible the category menu selected value is submitted fine. If #catILF or #catOPI is visible the value for category is blank. I am not using the Ids of the category menus.
$("#submit-foul").submit(function(e){
e.preventDefault();
var category = $(".category").val();
var dataString = 'category=' + category;
if($("#submit-foul").valid()){
$.ajax({
url: 'myUrl',
type: 'POST',
success: function(data){
if(data == 1){
alert('Success');
};
}
});
}
return false;
});
I am not sure what I am doing wrong. Time to send it to the experts!! I appreciate all your help.
Try to change function "foulTypes" and add class in visible select.
foulTypes.change(function () {
//We first disable all, so we dont submit data for more than 1 category
$("#catDPI, #catILF, #catOPI, #catOH, #catDH, #catILD, #catUNS, #catUNR, #catTGT").hide().find(".category").attr("disabled", true);
var $divSelectedCategory;
if ($(this).val() == '1') {
$divSelectedCategory = $("#catDPI");
$('#catDPI').show();
$('#dpiCategory').addClass("visible");
} else {
$('#catDPI').hide();
$('#dpiCategory').removeClass("visible")
}
.... CONTINUE
In your ajax submit..
var category = $(".category.visible").val();

Getting the value of textbox

I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D

Change select dropdown based on first select dropdown?

I am trying to change the second select dropdown based on whether the first selected option contains an (m) or (ft).
My form HTML search is as follows:
<form id="search" action="/property_search" method="get" class="clearfix">
<select name="sqsize" id="sqsize" class="sqsize">
<option value="">sq.ft/sq.m:</option>
<option value="233.52m">233.52m</option>
<option value="233.52m">233.52m</option>
<option value="467.04m">467.04m</option>
<option value="2,513ft">2,513ft</option>
<option value="2,513ft">2,513ft</option>
<option value="5,026ft">5,026ft</option>
</select>
<select name="sqsizemin" id="sqsizemin" class="sqsizemin">
<option value="">Size Min:</option>
</select>
<input type="submit" class="submit" value="Search">
</form>
My Jquery is as follows:
<script type="text/javascript">
$(function(){
$('#sqsize').change(function () {
var options = '';
if($(this).val() == 'm') {
options = '<option value=""></option>';
}
else if ($(this).val() == 'ft') {
options = '<option value="6">6</option>';
}
$('#sqsizemin').html(options);
});
$('#sqsize').trigger('change');
});
Try something like this(using indexOf):
$(function(){
$("#sqsize").change(function(){
var options = '';
if($(this).val().indexOf('m') > -1) {
options = '<option value="">mm</option>';
}
else if ($(this).val().indexOf('ft') > -1) {
options = '<option value="6">6</option>';
}
$('#sqsizemin').html(options);
});
});
Working fiddle: https://jsfiddle.net/robertrozas/b0w61quf/
Try like this:
https://jsfiddle.net/kc5qqtco/
$(function(){
$('#sqsize').change(function () {
if($(this).val().match(/m/g)) {
$('<option value=""></option>').appendTo('#sqsizemin');
}
else if ($(this).val().match(/ft/g)) {
$('<option value="6">6</option>').appendTo('#sqsizemin');
}
});
});
Using indexOf will get you a working solution.
See the jsfiddle

Show Checkboxes on select box using jquery in php

I have two tables in database: city and local_area
city :
id name
1 FSD
2 LHr
Local_area :
id city_id name
1 1 Kohnoor
2 1 samnabad
3 2 joharabad
4 2 amanabad
<select>
<option value="1">Fsd</option>
<option value="2">LHR</option>
</select>
I have a select box that allows to me to choose the city to display. When I select a city it should show a new HTML element showing all local_area for the given city.
I Have to do this using jQuery, after selection I want to store my record in database table.
<select id="ddCity">
<option value="-1"></option>
<option value="1">FSD</option>
<option value="2">LHr</option>
</select>
<div id="local_area_Grid"></div>
<script>
$(function(){
$("#ddCity").change(function(){
if($(this).val() != -1){
$.ajax({
url: "Server_address",
data:{cityId = $(this).val()},
success: function(data){
var _table = $("<table></table>");
for(var i = 0; i< data.length; i++){
$("<tr></tr>").append($("<td></td>").html("<label><input type='checkbox' value='data[i]' name='local_area'/>" + data[i] + "</label>")).appendTo(_table);
}
$("#local_area_Grid").html("").append(_table);
}
});
}
});
})
</script>
You should return an array from service
You need to use jQuery AJAX to "ask" a server for list of areas corresponding to the city. Or, may be, it would be better for you to load full list of all areas with page. For example:
<script language="JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select id="city" name="city">
<option value="0">- Select -</option>
<option value="1">Fsd</option>
<option value="2">LHR</option>
</select>
<div id="area" style="display:none">
</div>
<script language="JavaScript">
var areas = {
'1' : { '1' : 'Kohnoor' },
'2' : { '1' : 'amanabad' }
}
$(function (){
var areaSelect = $('#area');
var citySelect = $('#city').change(function (){
var value = $(this).val();
if( value && typeof areas[value] != 'undefined' ){
areaSelect.empty().show();
for( var i in areas[value] ){
areaSelect.append('<input type="checkbox" name="area[]" value="'+i+'" />'+areas[value][i]+'<br />');
}
}else{
areaSelect.empty().hide();
}
});
});
</script>

Categories