change the select input on change of other select input - javascript

i have more than 2 divs that have 2 select inputs. when i change branch_country, the other branch_region changes according to branch_country value via ajax.
<div>
<select class="branch_country></select>
<select class="branch_region></select>
</div>
<div>
</elect class="branch_country></select>
<select class="branch_region></select>
</div>
and here is my ajax code
$('.branch_governorate_select').on('change', function(e) {
e.preventDefault();
console.log($(this).eq($(this)));
var countryID = $(this).val();
var status = $(this).parent().parent().find('.modal-body').find('#select-status-calendar')
.val();
var url = "{{ route('sett.doc_get_branch_region', ':id') }}";
url = url.replace(':id', countryID);
if (countryID) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
region_input.empty();
$.each(data, function(key, value) {
region_input.append('<option value="' +
value.id + '">' + value.name + '</option>');
});
}
});
} else {
region_input.empty();
}
});
it works well, but it changes all inputs with class branch_region. but i need to change only the branch_region select input that is inside the same div

Related

cant redirect on change event datalist input

I am trying to redirect to a new page with data from the datalist input after a event
(selecting a option) but for some reason its just reloading the page
here is the code I have (I am retrieving the data for the input options with php from a mysql database I don't know if this matters)
<script>
$(document).ready(function() {
$.ajax({
url: 'fetch_data.php',
dataType: 'json',
success: function(data) {
// Populate the datalist input with the data
var datalist = $('#datalist-input');
$.each(data, function(key, item) {
datalist.append('<option data-id="' + item.id + '" value="' + item.name + '">' + item.value + '</option>');
});
// Handle the change event on the datalist input
datalist.change(function() {
// Retrieve the selected option's ID
var selectedOption = datalist.find('option:selected');
var id = selectedOption.data('id');
// Construct the URL of the target page
var targetUrl = 'target_page.php?id=' + id;
// Navigate to the target page
window.location = targetUrl;
});
}
});
});
</script>

Append collected data with javascript

I have 2 different data they load based on each other id what I try to do is to append my results as row bootstrap 3 based something like:
So far I can get 3 sort of my data successfully, all the problem I
have and need help with is how to append data as described in image above?
code
javascript
<script>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key, value1) {
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key, value) {
$('div#dataaa').append('<div class="row"><div class="col-md-4" id="dataparent">'+value1.title+'</div><div class="col-md-8" id="datainfo">'+value.title+'</div></div>');
});
}
});
// second data
});
}
});
}else{
$('div#dataaa').append('select set');
}
});
});
</script>
html
<div id="dataaa"></div>
This is how I'm getting my data now:
Update
Well I have made it work so far. Remained one issue, and that is I cannot get all my data I only can get my first result.
Changed code
<script>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key1, value1) {
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Collect data as option
var helpers = '';
$.each(data, function(key, value) {
helpers = '<option value="'+value.id+'">'+value.title+'</option>';
});
var my_row = $('<div class="row">');
var my_html = '<div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-8"><select class="form-control" id="subs" name="subs[]">'+helpers+'</select></div>';
my_row.html(my_html);
$('div#dataaa').append(my_row);
}
});
// second data
});
}
});
}else{
$('div#dataaa').append('select set');
}
});
});
</script>
Update 2
As requested here is my first select option code
{{ Form::label('selectset', 'Select Set') }}
<select class="form-control" id="selectset" name="selectset">
<option value="">Select</option>
#foreach($selectsets as $selectset)
<option value="{{ $selectset->id }}">{{ $selectset->title }}</option>
#endforeach
</select>
change
$.each(data, function(key, value) {
helpers = '<option value="'+value.id+'">'+value.title+'</option>';
});
to
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
because on each iteration, it overwrite its previous result

How do I select a '<td>' and navigate to url using jquery?

I am using jquery to pull football data from an api as follows
type: 'GET',
dataType: 'json',
url: "http://api.football-data.org/v1/competitions/426/teams",
processData: true,
//idLength: url.Length - url.LastIndexOf("/", StringComparison.Ordinal) - 1,
//id: url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1, idLength),
success: function (data, status) {
var trHTML = '';
$.each(data.teams, function (key, item) {
var id = item._links.self.href;
var indexOfLastBackSlash = id.lastIndexOf("/") + 1;
id = id.substring(indexOfLastBackSlash);
//$('<option>', { text: item.TeamName, id: item.ID }).appendTo('#lstTeams');
trHTML += '<tr class="info"><td>' + item.name +
'</td><td>' + item.code +
'</td><td>' + item.shortName +
'</td><td>' + item.squadMarketValue +
'</td><td>' + item.crestURL +
'</td><td>' + id +
'</td></tr>';
I want to be able to select a 'td' and navigate to another url like "http://api.football-data.org/v1/teams/322/fixtures" for the team with id of 322. How can I do so?
You can create a function which will do same ajax request but this time for single record. On your target's click event you need to call that function passing the id you need to fetch records for. One way of doing this is to set a data attribute to your target container.
Below is the sample code performing similar functionality.
$(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/',
method: 'GET',
dataType: 'json'
}).then(function(Data) {
$.each(Data, function (key, data) {
var id = data.id;
var title = data.title;
$('.tableAllRecords').append('<tr><td><a href=# class=mylink data-id='+id+'>'+id+'</a></td><td>'+title+'</td></tr>');
});
});
});
function fetchSingle(id) {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + id,
method: 'GET',
dataType: 'json'
}).then(function(data) {
var id = data.id;
var title = data.title;
var body = data.body;
$('.tableSingleRecord').append('<tr><td>'+id+'</td><td>'+title+'</td><td>'+body+'</td></tr>');
});
}
$(document).on('click', '.mylink', function(e) {
var id = $(this).data('id');
fetchSingle(id);
e.preventDefault(); // disabling anchor's default [redirect] behaviour
});
Here is the link to fiddle. https://jsfiddle.net/2h54vu7h/
If you need to display records on a new page, you simply have to pass id into your url and on next page you have make an ajax request getting the id variable from url.
Example: '<a href=somepage.html?id='+id+'>View Details</a>';

Dropdown value not being retained

I have a dropdown which gets its value from a model and is first populated. On click of that dropdown, I populate other values using AJAX. I am able to populate the dropdown but once I select an option from the dropdown, it gets reset to first value in the dropdown. What I want is the dropdown to populate once on click and then function like a normal dropdown. How do I put a condition for it?
This is the code for initially setting the dropdown value with the defined value 'field.Value'
ddlValue = "<option value="+field.Value+ " selected='selected'>" + field.Value+"</option>";
<td><select id='#String.Format("selValue{0}", field.Field)' class='ddlValue'>#Html.Raw(ddlValue)</select></td>
And this is the AJAX function which populates it.
$('body').on('click', '.ddlValue', function () {
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
});
});
If you want the ajax population to happen only once, you need to remove the event listener after it has occurred. Something like so:
$('.ddlValue').on('click', function () {
$(this).off('click'); //This removes the event after it has happened once.
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
});
});
Please note, the follow will not work:
$('body').on('click', '.ddlValue', function () {
$(this).off('click');
...
This seems like a silly way of doing this. You could do the same operation on loan without having any interaction with the user to populate the dropdown.
That being said to fix your solution simply add a global variable
$first = true
$('body').on('click', '.ddlValue', function () {
if($first) {
$first = false
var target = event.target.id;
var rowId = $('#' + target).closest("tr").prop("id");
var field = $('#' + rowId).find(".fieldvalue").html();
$.ajax({
cache: false,
url: '#Url.Action("PopulateDropdown", "AdvancedSearch")',
type: "POST",
data: { Field: field }
}).done(function (data) {
var listb = $('#' + target);
listb.empty();
$.each(data.value, function (index, value) {
listb.append($('<option>', {
value: value,
text: value
}, '<option/>'))
});
}
});
});

Populate Dropdown List based on Autocomplete Value

I have three form fields for country(text input), city(text input) and street(dropdown):
country is autocomplete
city is auto-filled based on the result of country
street I want to generate dropdown list based on selected city
Here is my current JavaScript script:
$(".country").autocomplete("get_city.php",{ mustMatch:true })
.result(function (evt, data, formatted) {
$(".city").val(data[1]);
});
So far it's auto-filling the city(text input).
My problem now is to generate drop down list based on the filled city.
I Think you need somthing like this:
$(".country").change(function () {
var webMethod = "filewithdata.php";
var parameters = { id: $('.country').val() };
$.ajax({
type: "GET",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//console.log(response);
json_obj = $.parseJSON(response);
var output = '';
for (var i in json_obj) {
if (json_obj[i][4] == 1) {
output += '<option value="' + json_obj[i][0] + '">' + json_obj[i][0] + '</option>'
}
}
$('#dropdownElement').empty().append(output);
},
error: function (e) {
$(divToBeWorkedOn).html("Unavailable");
alert("Errror:" + e);
}
});
});

Categories