I have ajax code that when I choose AREA (first select box) I get all the cities in this area.
The issue is when I first enter the page - I want that the second select box (the cities select box) to be fill with the area default (the first choice)
This is what I already have:
Client side:
<script>
$(document).ready(function(){
$('#areaID').change(function(){
var areaID=$('#areaID').val();
$('#cityID').load('scripts/ajax/getCities.php?areaID=' + areaID);
return false;
});
});
</script>
<form method="post" action="page.php">
<select id="first" name="areaID">
<option value="1">center</option>
<option value="2">north</option>
<option value="3">south</option>
</select>
<select id="cityID" name="cityID"> </select>
</form>
$(function () {
function updateCitySelectBox() {
var areaID = $('#areaID').val();
$('#cityID').load('scripts/ajax/getCities.php?areaID=' + areaID);
return false;
}
updateCitySelectBox();
$('#areaID').change(updateCitySelectBox);
});
Related
can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>
I've got two select option. I want to change the second select options value based on the first option value. I'm using thymleaf as template engine.
When the first select is being selected, I make an ajax call to the controller and get the value as a list. I'm getting the value from ajax call but couldn't able to append the value to the second select option. console.log() shows the option value correctly but it didn't update HTML code.
First Select option:
<select id="brand" th:onchange="changeBrand()" class="form-control">
<option th:selected="true" th:disabled="true"
th:text="'Please Select A Brand'"></option>
<option th:each="brand : ${Calculator}"
th:value="${brand}"
th:text="${brand}">Choose Brand</option>
</select>
Second Select:
<div class="input-group">
<select id="model" class="form-control">
<option th:selected="true" th:disabled="true"
th:text="'Please Select A Model'"></option>
</select>
</div>
Ajax:
<script th:inline="javascript">
/*<![CDATA[*/
function changeBrand() {
var selectedBrand = $( "#brand option:selected" ).text();
$.ajax({
url:"duty/getAllModel",
data:{brand:selectedBrand},
type:"POST",
success:function(data){
// Resetting select option
var select = document.getElementById("model");
select.options.length = 0;
options = data.options;
for (var i = 0; i < data.length; i++) {
select.options[select.options.length] = new Option(data[i],i);
}
for (var i = 0; i < select.childElementCount; i++) {
console.log(select.options[i]);
}
},error:function (error) {
console.log(error);
}
});
}
/*]]>*/
Console.log() value:`
Nokia
Samsung`
<script>
$(document).ready(function() {
$('#state').change(function(event) {
var $c=$("#state").val();
$.get('getCities',{id:$c},function(responseJson) {
var $select = $("#city");
$select.find('option').remove();
$.each(responseJson, function(key, value) {
$('<option ></option>').val(key).text(value).appendTo($select);
});
});
});
});
</script>
<form action="postingRequirementSaving" th:object="${PostRequirementCommand}">
<label>State:</label>
<select th:field="*{stateid}" id="state">
<option value="0" selected="selected">– Select an option –</option>
<option th:each="var :${state}" th:value="${var.stateid}" th:text="${var.statename}"></option>
</select> <span class="error"></span>
<label>City:</label>
<select th:field="*{city}">
<option value="0">Select City</option>
</select>
</form>
Json response is not supporting multiple select jquery plugin.
please can any one help me to resolve it.
i'm using spring hibernate frame work.
when i'm using static data it works fine, but when it comes dynamic it doesn't working.
If you are using a plugin you have to initialize the select field after your response loaded.
For example if you use this plugin :
<script src="jquery.multiple.select.js"></script>
you will have to initialize your city selector after receiving the jsonResponse. And also in above code you have to add a id to the selector.
<script>
$(document).ready(function() {
$('#state').change(function(event) {
var $c=$("#state").val();
$.get('getCities',{id:$c},function(responseJson) {
var $select = $("#city");
$select.find('option').remove();
$.each(responseJson, function(key, value) {
$('<option ></option>').val(key).text(value).appendTo($select);
});
$select.multipleSelect();
});
});
});
</script>
my site is : http://server1.bioprotege-inc.net/permanent_Files/digichat_admin_panel/#Home
the link that says "home" drops down the content that i specified what id like to do but cant get to work is use one of the options on the drop down menu to drop the same content as the link home does but i cant get it to work like that and suggestions?
// JavaScript Document
$(document).ready(function(){
$("#Home").click(function(){
Load_ajax_page("Content_Files/Home.html");
});
$("#Chat").click(function(){
Load_ajax_page("Content_Files/Chat.html");
});
$("#Rules_List").click(function(){
Load_ajax_page("Content_Files/Rules_List.html");
});
$("#The_Team").click(function(){
Load_ajax_page("Content_Files/The_Team.html");
});
$("#Forums").click(function(){
Load_ajax_page("Content_Files/Forums.html");
});
});
function Load_ajax_page(url){
//this is a jquery method to make a ajax request
$.post(url,"",function (data){
//this is the place where the data is returned by the request
//remove loading and add the data
$("#response").html(data);
});
}
HTML CODE NOW FOR DROPDOWN MENU:
<form onclick="">
<select onchange="window.open(this.options[this.selectedIndex].value,'_top')" style="width:582px; height:25px;">
<option value="#">Enter Free Hosted Sites:</option>
<option value="#"></option>
<option value="#Home">Hosted1 - Shadow Hunters</option>
<option value="http://www.google.com">Hosted2</option>
<option>Hosted3</option>
<option>Hosted4</option>
</select>
</form>
<br />
<div id="response"></div>
You can use this code:
<script type="text/javascript">
try{
xmlhttp = new XMLHttpRequest();
}
catch(ee){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E){
xmlhttp = false;
}
}
}
div_base = "";
valor = 0;
function abre(arquivo,metodo,div){
div_base = div;
valor++;
xmlhttp.open(metodo,arquivo+"?valor="+valor);
xmlhttp.onreadystatechange=response
xmlhttp.send(null)
}
function response() {
nova_div = div_base;
document.getElementById(nova_div).innerHTML="<div style='top:50%;left:50%;position:absolute;'>Loading...</div>"
if (xmlhttp.readyState==4){
document.getElementById(nova_div).innerHTML=xmlhttp.responseText
}
}
</script>
<form>
<select name="menu">
<option onclick="javascript: abre('Content_Files/Home.html','GET','response');">Home</option>
<option onclick="javascript: abre('Content_Files/Chat.html','GET','response');">Chat</option>
<option onclick="javascript: abre('Content_Files/Rules_List.html','GET','response');">Rules_List</option>
<option onclick="javascript: abre('Content_Files/The_Team.html','GET','response');">The_Team</option>
<option onclick="javascript: abre('Content_Files/Forums.html','GET','response');">Forums</option>
</select>
</form>
<br /><br />
<div id="response"></div>
i am using an ajax event which is triggered when i hit the submit button to add data to the database but since when i orignally created this page they were all in seprate files for testing purposes so now when i have put all the code together i have notice that 4 submit buttons i was using to refresh the page and then change the data being seen by filtering it are triggering the ajax query i have placed the code bellow.. i am quite stumped in what is the only way to go about this...
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var process= $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php',
data: {
'uname': checkVal,
'id': userid
},
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
});
$('form').bind('submit', function(){ // it is triggering this peice of code when the submit buttons are clicked ???
$.ajax({
type: 'POST',
url: "requestadd.php",
data: $("form").serialize(),
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
return false;
});
$("#claim").change(function(){
$("#area").find(".field").remove();
//or
$('#area').remove('.field');
if( $(this).val()=="Insurance")
{
$("#area").append("<input class='field' name='cost' type='text' placeholder='Cost' />");
}
});
});
</script>
</head>
<body>
<div id="add">
<form name="form1aa" method="post" id="form1a" >
<div id="area">
<input type=text name="cases" placeholder="Cases ID">
<select id="claim" name="claim">
<option value="">Select a Claim</option>
<option value="Insurance">Insurance</option>
<option value="Warranty">Warranty</option>
</select>
</div>
<select name="type" onChange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="">Select One</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<br />
<input type=text name="comment" placeholder="Comments Box">
<input type="submit" value="Submit" name="Submit">
</form>
</div>
<?
$sql="SELECT * FROM $tbl_name ORDER BY cases ASC";
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%' ORDER BY cases ASC";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%' ORDER BY cases ASC";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%' ORDER BY cases ASC";
}
$result=mysql_query($sql);
?>
<!-- Filter p1 (Start of) !-->
<form action="ajax-with-php.php" target="_self">
<input type="submit" name="all" value="All" /> // the issue is mainly occuring here when i click any of thesse meant to refesh the page and change the query with the if statements but is trigger the other code i commented
<input type="submit" name="tpc" value="TPC" />
<input type="submit" name="drc" value="DRC" />
<input type="submit" name="bsc" value="BSC" />
</form>
$('form').bind('submit', function(){ ...
will bind to all forms. Change it to
$('form#form1a').bind('submit', function(){ ...
and it will only bind to the first form, not the second.
$('form').bind('submit', function(event){
event.preventDefault();
$.ajax({...
Try making the changes above 1) adding the event argument to your callback 2) executing the .preventDefault() method. When using AJAX with the submit event this is neccessary to stop the page from reloading and interrupting your async request.
There may be more issues than that, but hopefully that will get you on the right track.