Use specific select option when loading the page (jQuery + Ajax) - javascript

I retrieve a URL with jQuery + Ajax and determine the display based on certain select options.
The selection works fine, however I can't manage to place a default. I would like value="3" to be preselected and show the corresponding result already when loading the page, without having selected an option before.
How can I do this?
Here is my code so far:
$(document).ready(function() {
$("#reportMonth").on('change', function() {
var reportMonth = $('#reportMonth :selected').val();
if(reportMonth){
$.ajax({
type: "GET",
url: "https://api.tools.paeddy.de/server_info",
dataType: "json",
timeout: 15000,
})
.done(function(JSONOut) {
var out = "Server " + JSONOut[reportMonth].server + " = " + JSONOut[reportMonth].status;
$('#output').html(out);
})
.fail(function(xhr, status, error) {
$('#output').html("<div class='error'>Error: " + xhr.status + ' - ' + error + "</div>");
});
$('#show_output').html('<div id="output"></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
<select id="reportMonth" name="reportMonth">
<option value="">Select:</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
</select>
</form>
<div id="show_output"></div>
</body>
</html>
JSFiddle

It looks like you're looking for the selected attribute. You'll also need to run the AJAX code to fetch the result for the default value, so extract your onchange handler into a function, then call it inside the onready handler. Like this:
function getResult() {
var reportMonth = $('#reportMonth :selected').val();
if (reportMonth) {
$.ajax({
type: "GET",
url: "https://api.tools.paeddy.de/server_info",
dataType: "json",
timeout: 15000,
})
.done(function(JSONOut) {
var out = "Server " + JSONOut[reportMonth].server + " = " + JSONOut[reportMonth].status;
$('#output').html(out);
})
.fail(function(xhr, status, error) {
$('#output').html("<div class='error'>Error: " + xhr.status + ' - ' + error + "</div>");
});
$('#show_output').html('<div id="output"></div>');
}
}
$(document).ready(function() {
getResult();
$("#reportMonth").on('change', getResult);
});
<!DOCTYPE html>
<html>
<body>
<form>
<select id="reportMonth" name="reportMonth">
<option value="">Select:</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3" selected>4</option>
</select>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="show_output"></div>
</body>
</html>

Just and some timeout and call trigger change.
$(document).ready(function() {
setTimeout(function() {
$("#reportMonth").trigger('change');
});
$("#reportMonth").on('change', function() {
var reportMonth = $('#reportMonth :selected').val();
if(reportMonth){
$.ajax({
type: "GET",
url: "https://api.tools.paeddy.de/server_info",
dataType: "json",
timeout: 15000,
})
.done(function(JSONOut) {
var out = "Server " + JSONOut[reportMonth].server + " = " + JSONOut[reportMonth].status;
$('#output').html(out);
})
.fail(function(xhr, status, error) {
$('#output').html("<div class='error'>Error: " + xhr.status + ' - ' + error + "</div>");
});
$('#show_output').html('<div id="output"></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
<select id="reportMonth" name="reportMonth">
<option value="">Select:</option>
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3" selected="selected">4</option>
</select>
</form>
<div id="show_output"></div>
</body>
</html>

Related

how to get json data in jquery for dinamic combobox

I have json data in here
Which is obtained from the Propinsi id but I do not understand how to use json data into my combobox, my script in here... please tell me how to correct this
$(document).ready(function(){
$('#propinsi').on('change',function(){
var prop_kode = $('#propinsi').val();
console.log(prop_kode);
if (prop_kode == "") {
$('#kabupaten').prop('disabled', true);
}
else {
$('#kabupaten').prop('disabled', false);
$.ajax({
url:"<?=$url; ?>/show_kabupaten",
type:"POST",
data: {'prop_kode' : prop_kode},
dataType: 'html',
success: function(data){
$('#kabupaten').html(data);
// $.each(json, function(i, value) {
$('#kabupaten').append($('<option>').text('Pilih Kabupaten').attr('value', 'value'));
$.each( kabupaten, function( kab_nama, kab_kode ) {
alert( kabupaten.kab_nama);
});
console.log(data);
},
error: function(){
alert('error .......');
}
})
}
});
});
Something like this?
$('#propinsi').on('change', function() {
var prop_kode = $('#propinsi').val();
if (prop_kode == "") {
$('#kabupaten').prop('disabled', true);
return;
}
$('#kabupaten').prop('disabled', false);
// This is just because I don't know where to find your json data
var data = JSON.parse('{"kabupaten":[{"kab_id":"8","prop_kode":"12","kab_kode":"120‌​1","kab_nama":"KABUP‌​ATEN NIAS","kab_status":"1","kab_created_by":"1","kab_created_dat‌​e":"1496631492"},{"k‌​ab_id":"9","prop_kod‌​e":"12","kab_kode":"‌​1202","kab_nama":"KA‌​BUPATEN MANDAILING NATAL","kab_status":"1","kab_created_by":"1","kab_created_da‌​te":"1496631518"}]}');
$("#kabupaten").html("");
$.each(data.kabupaten, function(i, kab) {
var id = kab.kab_id;
var name = kab.kab_nama;
$("#kabupaten").append('<option value="' + id + '">' + name + '</option>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="propinsi">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<select id="kabupaten"></select>
To implement it into your JS, the code below may help.
// Add this code just below the line $('#kabupaten').prop('disabled', false);
$.ajax({
url: "<?=$url; ?>/show_kabupaten",
type: "POST",
data: {'prop_kode': prop_kode},
dataType: 'json',
success: function(data) {
$("#kabupaten").html("");
$.each(data.kabupaten, function(i, kab) {
var id = kab.kab_id;
var name = kab.kab_nama;
$("#kabupaten").append('<option value="'+id+'">'+name+'</option>');
});
},
error: function() {
alert('error .......');
}
});

Select2 Change Event - Change the options for next select2 box on first select2 box value change

I have 2 select2 boxes. First is Category and next is Sub-category.
Now, I want to change the options for subcategory box based on Category box selected value. And the data for Subcategory box should load using AJAX.
Please help me.
just solved it myself
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select class="js-data-example-ajax" id="category" >
<option value="">Select a category</option>
<option>cat1</option>
<option>cat2</option>
<option>cat3</option>
</select>
<select class="js-data-example-ajax" id="sub-category" >
</select>
<script>
$("#category").select2({
placeholder: "Select a category",allowClear: true
});
$("#sub-category").select2({
placeholder: "Select sub-category",allowClear: true
});
$('#category').on("change", function (e) {
var result = '';
var catval = $(this).val();
if(catval != '') {
url = "subcats_top/"+ catval;
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function(data){
var length = data.length;
if(length > 0) {
for(key in data) {
result += '<option value="' + data[key].id + '">' + data[key].name + '</option>';
}
} else {
}
$("#sub-category").html(result);
}
});
}
});
</script>

pass id from php while loop to jquery

i have a form that has select boxes. this form has a table and each row has been created by php while loop from database. for example
<select name="1265483" id="1265483" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<select name="5894253" id="5894253" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
the id of each select is that entry's id in database. i want to get those ids to make an onchange function then send that id to ajax.
You can use something like:
$("select").change(function () {
$this = $(this);
$.post("some/url/dot.php", {data: $this.attr("id")}, function () {
// code...
});
});
you can do by below code
var your_selected_value = $('#5894253 option:selected').val();
$.ajax({
type: "POST",
url: "your_url",
data: {selected: your_selected_value},
success: function(data) {
// Stuff
},
error: function(data) {
// Stuff
}
});
put this code in onchange function
Try using the select class name:
$("select.form-control").change(function (e) {
var selectId = $(this).attr('id'),
ajaxUrl = "demo_test.php?id=" + selectId;
$.ajax({
url: ajaxUrl,
success: function (result) {
if (result) {
//success code
}
}
});
});

Ajax Post, jQuery not working on the ResponseData result page

I have a Post Form in wich i use to Search results.
<form method="post" enctype="multipart/form-data" name="byMonthYear">
<label><h2>Search Colection by Month and Year:</h2></label>
<select name="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="year">
<?php
$get_year = date('Y') + 1;
for($i = $get_year;$i >= 2013;$i--){
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<input type="button" value="Search" onclick="return search_buss_byMonthYear()">
</form>
On click i call AJAX to get the results search_buss_byMonthYear();
function search_buss_byMonthYear(){
$('#loading').show();
var month = document.forms['byMonthYear']['month'].value;
var year = document.forms['byMonthYear']['year'].value;
var dataString = 'month='+ month + '&year=' + year;
if(month == '')
{
document.getElementById("results").innerHTML = "<div class='alert_error'>You must fill all fields! <br></div>";
}else{
$.ajax({
type: "post",
url: "inc/byMonthYear.php",
data: dataString,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
$('#loading').hide();
document.getElementById("results").innerHTML = responseData;
},
error: function(jqXHR, textStatus, errorThrown) {
$('#loading').hide();
document.getElementById("results").innerHTML = "<div class='alert_error'>Your action had errors! <br></div>";
}
});
}
}
on the File byMonthYear.php i have the php script to get the results, and is working very good, BUT i want to add some additional javascript action on that page byMonthYear.php.. But its not responding the jQuery there!
I put just alert("hello"); to test is but its not responding !!
Any idea how to bind the jQuery to work in this conditions !
Thanks
The Javascript you added does not work in byMonthYear.php. You are trying to call a php webpage by ajax and that page will be executed server side not client side.
You can try to return the Javascript code by echo and a flag. If that flag is set then display the Alert(). Use JSON to send data.
Guess you understood.
i am not a hundred percent sure but try including your javascript file to the new php page
it souds like a problem i had a wile back where i was using ajax to call load a page but the javascript did not work so i had to include them again like so
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="myjava.js"></script>
</head>
Solved:
I just added this on success and javascript responds.
success: function(responseData, textStatus, jqXHR) {
$('#results').html( responseData );
},
Thanks for answers.

event is not defined javascript firefox (json)

can any body tell me why my code error on firefox?
HTML:
Size : <select class="size" id="size<?php echo $dat_women->id; ?>" name="size" onchange="change_size(<?php echo $dat_women->id; ?>)">
JS:
function change_size(id_product){
var size = document.getElementById(event.target.id).value;
$.ajax({
dataType:"json",
url: site_url + "main/add_cart/" + id_product + "/" + size,
success:function(data){
window.location.assign("cart");
},
error: function(data){
alert('Anda belum memilih ukuran');
}
});
};
Error:
event is not defined
Try sending the element as a parameter to the function call:
In your HTML:
onchange="change_size(this,<?php echo $dat_women->id; ?>)"
and in your function defnition:
function change_size(element, id_product)
then you can get the size like this:
var size = element.value;
Plunker Example
HTML:
<select class="size" id="size2" name="size" onchange="change_size(this, 2)">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
JS:
function change_size(id_product){
var size = $(this).value;
$.ajax({
dataType:"json",
url: site_url + "main/add_cart/" + id_product + "/" + size,
success:function(data){
window.location.assign("cart");
},
error: function(data){
alert('Anda belum memilih ukuran');
}
});
};

Categories