I am new to jquery and ajax. I really need you help.
I have two select box, one dynamically add options to a select when the first select box is checked. I used ajax to dynamically get those values. I am getting values correctly from database. But when I try to append these options inside second select box it is not working. My code is below
$(document).ready(function() {
$("#categories").change(function() {
var categoryId = $("#categories").val();
//alert(categoryId);
if(categoryId == 2) {
$.ajax({
url: "<?= base_url();?>Web/getRateType",
method: "POST",
dataType: "json",
success:function(data) {
//alert(data[0].status);
$("#rate_container").css('display', 'block');
$("#expected_salary_container").css('display', 'none');
$("#rate_categories").empty();
// var str = '<label>Rate*</label></br>';
//str += '<select name="rate_categories" style="font-size:15px" id="rate_categories"><option value="0">Select</option>';
var str = '';
$.each(data, function(key, value) {
//alert(value['rate_id']);
str +='<option value="'+ value['rate_id'] +'">'+ value['rate_cat_name'] +'</option>';
});
alert(str);
//str += '</select>';
var x = $("#rate_categories").append(str);
if(x){
alert(x);
}
}
});//$("#rate_categories").append('<option value="'+ value.rate_id +'">'+ value.rate_cat_name +'</option>');
}
else if (categoryId == 1) {
document.getElementById("expected_salary_container").style.display = "block";
document.getElementById("rate_container").style.display = "none";
}
else{
document.getElementById("expected_salary_container").style.display = "none";
document.getElementById("rate_container").style.display = "none";
}
});
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<?php foreach($categories as $key => $value) { ?>
<option value="<?php echo $value['type_id']; ?>"><?php echo $value['cat_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
here alert(x) is working fine. but the html is not appending inside select box. could anybody please help
jQuery is referenced in the header:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first. However please check the network tab JS file load.
You should put the references to the jquery scripts first.
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.2.6.min.js"></script>
Please use compatible new jquery CDN Url in above script tag.
Examine the code below and see if that works for you. I've changed the vanilla JS to jQuery. You may need to re-insert your php code back in.
$(document).ready(function() {
//Hide everything
$("#expected_salary_container, #rate_container").hide();
$("#categories").change(function() {
var categoryId = $("#categories").val();
console.log(categoryId);
//alert(categoryId);
if (categoryId == 2) {
let data = ["Item 1", "Item 2", "Item 3"];
str = "";
$.each(data, function(key, value) {
//alert(value['rate_id']);
str += '<option value="' + value + '">' + value + '</option>';
console.log(str);
});
var x = $("#rate_categories").append(str);
$("#expected_salary_container").hide();
$("#rate_container").show();
} else if (categoryId == 1) {
$("#expected_salary_container").show();
$("#rate_container").hide();
} else {
$("#expected_salary_container").hide();
$("#rate_container").show();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label>Job Type*</label>
<select name="categories" id="categories">
<option value="0">Select</option>
<option value="2">Cat 1</option>
<option value="1">Cat 2</option>
<option value="2">Cat 3</option>
</select>
</div>
</div>
<div id="rate_container">
<div class="form-group">
<label>Rate*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>
<div id="expected_salary_container">
<div class="form-group">
<label>Salary*</label>
<select id="rate_categories" name="rate_categories">
<option value="0">Select</option>
</select>
</div>
</div>
<form class="uk-form-stacked">
<label class="uk-form-label" for="kUI_dropdown_basic_select">Select a user</label>
<select id="kUI_dropdown_basic_select" class="uk-form-width-medium" onchange="getIPL();">
<?php foreach ($response->result->allAcc as $data) { ?>
<option value="<?php echo $data->Id;?>"> <?php echo $data->Name; ?></option>
<?php } ?>
</select>
</form>
<script>
function getIPL() {
var urlmenu = document.getElementById( 'kUI_dropdown_basic_select' );
urlmenu.onchange = function() {
window.open( 'admin_mailbox.php?Id=' + this.options[ this.selectedIndex ].value,"_self");
};
}
</script>
Thank you for taking the time for reading my question.
onchange() is not working for the first time
second time it works fine
Remove onchange from select box. And change your JS with this :
<script>
var urlmenu = document.getElementById( 'kUI_dropdown_basic_select' );
urlmenu.onchange = function() {
window.open( 'admin_mailbox.php?Id=' + this.options[ this.selectedIndex ].value,"_self");
};
</script>
When you are using document.getElementById for getting element id, than no need to use onchange() event in <select>
And i also suggest you to add one more option for selection <option>Select</option>
Test Example (change as per your PHP Code):
var urlmenu = document.getElementById( 'kUI_dropdown_basic_select' );
urlmenu.onchange = function() {
window.open( 'admin_mailbox.php?Id=' + this.options[ this.selectedIndex ].value,"_self");
};
<form class="uk-form-stacked">
<label class="uk-form-label" for="kUI_dropdown_basic_select">Select a user</label>
<select id="kUI_dropdown_basic_select" class="uk-form-width-medium">
<option value="">Select</option>
<option value="test1">Test1</option>
<option value="test2">Test2</option>
</select>
</form>
Very easy and simple code below
<form class="uk-form-stacked">
<label class="uk-form-label" for="kUI_dropdown_basic_select">Select a user</label>
<select id="kUI_dropdown_basic_select" onmousedown="this.value='';" class="uk-form-width-medium" onchange="getIPL(this.value);">
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
<option value="ccc">ccc</option>
<option value="ddd">ddd</option>
</select>
</form>
javascript function
function getIPL(value) {
//var urlmenu = document.getElementById( 'kUI_dropdown_basic_select' );
//urlmenu.onchange = function() {
window.open( 'admin_mailbox.php?Id=' + value,"_self");
//};
}
You have already defined onchange event of select box here...then why you use onchange again on same element.
Use following code
<form class="uk-form-stacked">
<label class="uk-form-label" for="kUI_dropdown_basic_select">Select a user</label>
<select id="kUI_dropdown_basic_select" class="uk-form-width-medium">
<?php foreach ($response->result->allAcc as $data) { ?>
<option value="<?php echo $data->Id;?>"> <?php echo $data->Name; ?></option>
<?php } ?>
</select>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#kUI_dropdown_basic_select").change(function(){
window.open( 'admin_mailbox.php?Id=' + $(this).val() ,"_self");
});
});
</script>
I have a code where it disables the button on page load since the value of the dropdown is empty. However, when a value is selected (the values are from the database, it is populated and it is working), the button is still disabled.
Jquery:
<script>
$(document).ready(function(){
$('.send').attr('disabled',true);
$('#kagawad').keyup(function(){
if($(this).val() != ""){
$('.send').attr('disabled', false);
}
else
{
$('.send').attr('disabled', true);
}
})
});
</script>
html:
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Select Kagawad</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<?php
include 'config.php';
$selectSql = "SELECT firstName, middleName, lastName
FROM table_position p
LEFT JOIN person r ON p.Person_idPerson = r.idPerson
WHERE p.bar_position = 'Barangay Kagawad' AND p.activeOrInactive = 'Active'";
$result = mysqli_query($conn, $selectSql);
?>
<select class="form-control" id = "kagawad" name = "kagawad" required>
<option value="">Choose...</option>
<?php
while ($line = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $line['firstName'].' '.$line['middleName'].' '.$line['lastName'];?>"> <?php echo $line['firstName'].' '.$line['middleName'].' '.$line['lastName'];?> </option>
<?php
mysqli_close($conn);
}
?>
</select>
</div>
<button id="send" type="submit" class="send btn btn-success" name="addCedula">Save Record</button>
How can I do it? What do I need to modify my code? Thank you!
Use change event on the <select>.
Instead of attr(), use prop() to set the disabled status.
Use ID selector, to disable the button.
Code:
$('#kagawad').on('change', function () {
$('#send').prop('disabled', !$(this).val());
}).trigger('change');
I have 2 different SELECT OPTION in a form.
The first one is Source, the second one is Status. I would like to have different OPTIONS in my Status drop-down list depending on the OPTION selected in my Source drop-down.
Source:
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
Status:
<select id="status" name="status">
</select>
Options:
- If Source is MANUAL, then Status is OPEN or DELIVERED
- If Source is ONLINE, then Status is OPEN or DELIVERED or SHIPPED
My non-working attempt:
<script>
$(document).ready(function () {
var option = document.getElementById("status").options;
if (document.getElementById('source').value == "MANUAL") {
$("#status").append('<option>OPEN</option>');
$("#status").append('<option>DELIVERED</option>');
}
if (document.getElementById('source').value == "ONLINE") {
$("#status").append('<option>OPEN</option>');
$("#status").append('<option>DELIVERED</option>');
$("#status").append('<option>SHIPPED</option>');
}
});
</script>
Try something like this... jsfiddle demo
HTML
<!-- Source: -->
<select id="source" name="source">
<option>MANUAL</option>
<option>ONLINE</option>
</select>
<!-- Status: -->
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
</select>
JS
$(document).on('ready', function () {
$("#source").on('change', function () {
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
switch (listindex)
{
case "manual" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
break;
case "online" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Source:
<select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select source</option>
<option value="manual">MANUAL</option>
<option value="online">ONLINE</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Status:
<script type="text/javascript" language="JavaScript">
document.write('<select name="status" id="status"><option value="">Select status</option></select>')
</script>
<noscript>
<select id="status" name="status">
<option value="open">OPEN</option>
<option value="delivered">DELIVERED</option>
</select>
</noscript>
</div>
</body>
</html>
For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list
function dropdownlist(listindex)
{
document.getElementById("ddlCity").options.length = 0;
switch (listindex)
{
case "Karnataka":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");
break;
case "Tamilnadu":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");
break;
}
}
*
State:
--Select--
Karnataka
Tamilnadu
Andra pradesh
Telngana
<div>
<p>
<label id="lblCt">
<span class="red">*</span>
City:</label>
<select id="ddlCity">
<!-- <option>--Select--</option>
<option value="1">Dharawad</option>
<option value="2">Belgum</option>
<option value="3">Bagalkot</option>
<option value="4">Haveri</option>
<option>Hydrabadh</option>
<option>Vijat vada</option>-->
</select>
<label id="lblCity"></label>
</p>
</div>
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
You're better off making two selects and showing one while hiding the other.
It's easier, and adding options to selects with your method will not work in IE8 (if you care).
I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.
HTML DYNAMIC DEPENDENT SELECT
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br/>
<select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>State:</label><br/>
<select name="state" id="state-list" class="demoInputBox">
<option value="">Select State</option>
</select>
</div>
GETTING STATES VIA AJAX
<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
}
});} </script>
READ STATE DATABASE USING PHP
<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>
for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.
The answer should be updated to replace the defunct functions .change & .ready
$(document).on('ready',function() {
$("#source").on('change', function(){
var el = $(this);
if (el.val() === "ONLINE") {
$("#status").append("<option>SHIPPED</option>");
} else if (el.val() === "MANUAL") {
$("#status option:last-child").remove();
}
});
});
I'm trying to send the selected option text to the url using jquery but whenever I wrap my form between <form></form> tags it stops working and sends the value instead of the text. If I remove the form tags it behaves the way i expect.
I want to know if there's any way to make it work without excluding the form tags
Thanks!
<form>
<select name="brand" id="brand" class="update">
<option value="">Seleccionar</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="model" id="model" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="size" id="size" class="update" disabled="disabled">
<option value="">----</option>
</select>
<input type="submit" value="Search" id="submit">
</form>
</div>
</div>
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="js/core.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var brand = $('#brand option:selected').text();
var model = $('#model option:selected').text();
var size = $('#size option:selected').text();
location.href ='index.php?s='+brand+'+'+model+'+'+size+'';
});
});
</script>
The form is submitting, you'll need to prevent that:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var brand = $('#brand option:selected').text();
var model = $('#model option:selected').text();
var size = $('#size option:selected').text();
location.href ='index.php?s='+brand+'+'+model+'+'+size+'';
});
});
You need to return false from your event handler to prevent the form submission from taking place.
Just add
return false;
at the end. (You can also do what adeneo's answer says to do; either should work.)