I trying to set two select-boxes to work by enabling the second select-box after choosing an option from the first.
The results comes from a json with js to a div on my page.
The 2nd select is set to disabled
First try:
JavaScript:
$(document).ready(function () {
$.getJSON('./system/feeds/built.search.php', function (json) {
var output = '';
output += '<div class="search_block">';
output += '<h2><img src="images/search_icon_big.png" alt=""> Search used cars</h2>';
output += '<form id="form1" class="form-style" method="post">';
output += '<label><strong>Company</strong><br>';
output += '<span class="select1">';
output += '<select name="companies" id="companies">';
output += '<option>All</option>';
output += '<option value="company">Company</option>';
for (var i = 0; i < json.company_models.length; i++) {
output += '<option value=' + json.company_models[i].company + '>' + json.company_models[i].company + '</option>';
}
output += '</select>';
output += '</span>';
output += '</label>';
output += '<label><strong>Model</strong><br>';
output += '<span class="select1">';
output += '<select name="models" id="models" disabled>';
output += '<option>Choose Company</option>';
$('#companies').change(function () {
if (this.value) {
document.getElementById('#models').disabled = true;
} else {
document.getElementById('#models').disabled = false;
}
});
for (i = 0; i < json.company_models.length; i++) {
output += '<option value=' + json.company_models[i].model + '>' + json.company_models[i].model + '</option>';
}
output += '</select>';
output += '</span>';
output += '</label>';
$('#search').html(output);
});
});
HTML:
<div id="search" class="grid_12"></div>
jsfiddle.net/mJdmQ
To make it more easy:
Company | Model: To choose the options from Model i must choose first an option from Company
PS: To save you sometime referring about similar questions, I already looked them...
You're looking for a .change() event with jQuery (onchange in pure js), and since this is dynamically loaded data, you'll need to use .on():
$(document).on("change", "#companies", function() {
this.value == "All" ? $("#models").prop("disabled", true) : $("#models").prop("disabled", false);
});
Related
I am trying to download CSV contents via PHP script hosted on the server.
This is the jquery code that executes and creates a table:
$(document).ready(function() {
$("#btnSubmit").click(function(){
$.ajax({
type: 'GET',
url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
data: null,
success: function(text) {
var fields = text.split(/\n/);
fields.pop(fields.length-1);
var headers = fields[0].split(','),
html = '<table>';
html += '<tr>';
for(var i = 0; i < headers.length; i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for(var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
Contents of get-csv.php file:
<?php
header('Content-Type: text/plain');
$csv = file_get_contents('http://mydomaincom/wp-content/uploads/csv-samples.csv');
echo $csv;
?>
Here is the code for button:
<!-- Begin Button -->
<div class="demo">
<input id = "btnSubmit" type="submit" value="Get It"/>
</div>
<!-- End Button -->
From browser:
I can access http://mydomaincom/wp-content/uploads/get-csv.php - no issues
I can access http://mysitecom/wp-content/uploads/csv-samples.csv - no issues
When I click on button nothing happens.
Thanks
Below I tried to put together a working snippet where you can possibly see how it works when it works ...
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
type: 'GET',
// url: 'http://mydomaincom/wp-content/uploads/get-csv.php',
// url: 'https://jsonplaceholder.typicode.com/users', // --> JSON
url: "https://data.cdc.gov/api/views/45um-c62r/rows.csv",
data: null,
success: function (text) {
var fields = text.split(/\n/);
fields.pop(fields.length - 1);
var headers = fields[0].split(','), html = '<table>';
html += '<tr>';
for (var i = 0; i < (headers.length,3); i += 1) {
html += '<th scope="col">' + headers[i] + '</th>';
}
html += '</tr>';
var data = fields.slice(1, fields.length);
for (var j = 0; j < data.length; j += 1) {
var dataFields = data[j].split(',');
html += '<tr>';
html += '<td>' + dataFields[0] + '</td>';
html += '<td>' + dataFields[1] + '</td>';
html += '<td>' + dataFields[2] + '</td>';
html += '</tr>';
}
html += '</table>';
$(html).appendTo('body');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmit">get data</button>
After looking around a bit further I did actually find some publicly available CSV data ("Rates of TBI-related Emergency Department Visits, Hospitalizations, and Deaths - United States, 2001 – 2010" from the U.S. Department of Health & Human Services) and I am now using that to demonstrate the AJAX process.
So, your code basically works. It could be simplified of course but that is not the point. I guess that the problems you encounter with your site are probably CORS-related.
I am setting a field in my HTML label from Viewbag which has a "'" in the text. when the HTML pulls up it shows ' in place of "'". How do I stop it from getting encoded?
Please find the code below.
setting text fileds in the HTML view.
$('#thStudentName').text('#ViewBag.Name');
if (sessionData.data.EventDate2Def != '' || sessionData.data.EventDate2Def != null)
$('#tdWhen').text(sessionData.data.EventDate1Def + ' and ' + sessionData.data.EventDate2Def);
else
$('#tdWhen').text(sessionData.data.EventDate1Def);
$('#tdWhere').text(sessionData.data.FacilityName);
$('#tdLocated').text(sessionData.data.Address1 + ', ' + sessionData.data.City + ', ' + sessionData.data.State + ' ' + sessionData.data.Zip);
$('#tdPhone').text(sessionData.data.Phone);
$('#tdDirections').text(sessionData.data.Directions);
$('#tdRoom').text(sessionData.data.RoomNumber);
Populating a different section with Dynamic data.
function populateSessionTable() {
var count = 1;
$('#SessionTable').html('');
var tableContent = '';
var record = '';
var Sessions = sessionData.data.Sessions;
tableContent = generateTableContent(count, Sessions[0].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').html(tableContent);
var radioStatus = '';
for (var i = 0; i < Sessions.length; i++) {
var content = Sessions[i];
radioStatus = '';
if (content.Capacity == content.Registered || content.Closed)
radioStatus = '<input disabled class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
else if (content.StartDateTimeDef == '#ViewBag.WorkshopDateDef' && t24to12Convert(content.StartTimeString) == t24to12Convert('#ViewBag.WorkshopTime'))
radioStatus = '<input class="selected-session radio" checked name="SessionId" type="radio" value="' + content.SessionId + '">';
else
radioStatus = '<input class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
record += '<tr>';
record += '<td class="session-schedule-table-btn">';
record += radioStatus;
record += '</td>';
record += '<td class="session-schedule-table-session-number"> ' + content.Number + ' </td>';
record += '<td class="session-schedule-table-session-start-time">' + t24to12Convert(content.StartTimeString) + '</td>';
record += '</tr>';
$('#SessionTBody' + count).append(record);
record = '';
if(Sessions.length != i + 1)
{
if(Sessions[i].StartDateTimeDef != Sessions[i + 1].StartDateTimeDef)
{
tableContent = '';
count++;
tableContent = generateTableContent(count, Sessions[i+1].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').append(tableContent);
}
}
}
}
populateSessionTable();
The preview shows the name in the correct format, but when it gets rendered instead of having the quote, it shows '
This is how the output is coming up
So finally it was a stupid problem and I swear I had tried this before, but this is the code that worked.
var stuName = '#ViewBag.Name';
stuName = stuName.replace("'", "'");
$('#thStudentName').text(stuName);
performing this search operation on JSON data, it works show filter data when enter term in search bar but it works only with one term as soon as I add space and other term it shows nothing, what am I doing wrong? Also it takes time to filter data around 14000 records are in JSON file
$(document).ready(function() {
$('#selectterm').change(function() {
var sterm = $(this).val();
$.ajax({
type: "GET",
url: "/fee/get/" + sterm,
success: function(res) {
if (res) {
$('#txt-search').keyup(function() {
var searchField = $(this).val();
if (searchField === '') {
$('#filter-records').html('');
return;
}
var output = '<div class="row">';
var count = 1;
$.each(res, function(key, lol) {
if ((lol.strm.toLowerCase().indexOf(searchField.toLowerCase()) != -1) ||
(lol.subject_cd.toLowerCase().indexOf(searchField.toLowerCase()) != -1) ||
(lol.catalog_nbr.toLowerCase().indexOf(searchField.toLowerCase()) != -1)) {
output += '<table class="table">';
output += '<thead>';
output += '<tr>';
output += '<th scope="col">Term</th>';
output += '<th scope="col">Subject</th>';
output += '<th scope="col">Catlog Nbr</th>';
output += '</tr>';
output += '</thead>';
output += '<tbody>';
output += '<tr>';
output += '<td>' + lol.strm + '</td>';
output += '<td>' + lol.subject_cd + '</td>';
output += '<td>' + lol.catalog_nbr + '</td>';
output += '</tr>';
output += '</tbody>';
output += '</table>';
if (count % 2 == 0) {
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#filter-records').html(output);
});
}
}
});
});
});
if (itemPrice != null) {
var option = null;
for (var i = 0; i < itemPrice.d.length; i++) {
option += '<option value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
} else {
SessioExp(response.statusText);
}
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown" >' + option + '</select></div></td>';
$.each(itemLinked, function (k, v) {
if (d.ItemCode == v.ITEMCODE) {
//Here set v.PRICELIST TO OPTION VALUE
if (v.ISLINKED) {
tblRow += '<td style="width:10%" align="center"><span id="existingData" class="fa fa-times" aria-hidden="false" style="display: none;"></span></td>';
tblRow += '<td style="width:10%" align="center"><input type="checkbox" class="chkLinked" checked /></td>';
flage = false;
}
}
});
I want set select box value when condition true if (d.ItemCode == v.ITEMCODE)
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown" >' + option + '</select></div></td>';
Here we want to show first saved value.
Assuming that your generated options have been appended to the html, you can simply call the JS function optionID.selected = true
So for that you will need to define ids to all your options
// assuming that all your values are unique
for (var i = 0; i < itemPrice.d.length; i++) {
option += '<option id=' + itemPrice.d[i].ListNum + ' value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
//pass the option id here
//P.S you can only call this funtion only if the options have been appended to the html
function defineOption(optionID) {
document.getElementById(optionID).selected = true;
}
I have an array Orte that contains postcode and the name of the city.
Now I want to change the dropdown depending on the number entered in the input field.
The input field has an onchange function. The function is the one below.
The script works so far except the last line after the for loop. It never adds the last part and I don't know why.
Can someone help me please.
Thanks in advance for the anwsers!
Burzi
function updateOrt(eingabe){
document.getElementById("ort_platzhalter").innerHTML = '<select name="ort">'
for (var i = 1; i <= Orte.length; i++){
if(Orte[i].PLZ == eingabe){
document.getElementById("ort_platzhalter").innerHTML += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
document.getElementById("ort_platzhalter").innerHTML += "</select>"
}
You should update the innerHTML in one shot. Build up the string first, then assign it. Also, arrays are zero-indexed, so I am guessing you want to start at 0, and end once it is the length of Orte (i = Orte.length).
function updateOrt(eingabe){
var str = '<select name="ort">'
for (var i = 0; i < Orte.length; i++){
if(Orte[i].PLZ == eingabe){
str += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
str += "</select>"
// now assign the str to innerHTML
document.getElementById("ort_platzhalter").innerHTML = str;
}
your problem is in the array loop.
You are going from 1 to Orte.length, when it reaches Orte.length it throws an exception and the code after the loop does not execute.
you should do it this way:
function updateOrt(eingabe){
document.getElementById("ort_platzhalter").innerHTML = '<select name="ort">'
for (var i = 0; i < Orte.length; i++){
if(Orte[i].PLZ == eingabe){
document.getElementById("ort_platzhalter").innerHTML += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
document.getElementById("ort_platzhalter").innerHTML += "</select>"
}
because arrays in javascript are 0 indexed and go up to length-1