Odd behaviour of dropdown in Angular JS - javascript

I am making hybrid app using Angular JS, wherein there is an page which has two dropdown (select controls).
The thing should be,When I select the first dropdown the second one automatically should fill based on the data fetched on change of first doropdown; but what happens is on change of first dropdown the data is fetched but it is not getting bind to second dropdown immediately though the model of second dropdown gets the data fetched on selection of first dropdown, instead what happens is when i again change the first dropdown selection, the previous data gets bind to the second dropdown.
Below is my code for the same -
Car Make dropdown -
<select name="make"
ng-options="item.MakeId as item.Make for item in memberdetailData.VehicleData"
ng-model="memberdetailData.selected_Make_ID"
ng-change="vehiclemakeselected()">
Car Model Dropdown -
<select name="model" ng-disabled="memberdetailData.selected_Make_ID === {}"
ng-options="item.ModelId as item.Model for item in memberdetailData.Vehicle_Model"
ng-model="memberdetailData.selected_Model"></select>
Controller code -
$scope.vehiclemakeselected = function () {
console.log($scope.memberdetailData.selected_Make_ID);
//console.log($scope.memberdetailData.selected_Make_ID);
db_factory.selectVehicleMasterData('select ModelId,Model from tbl_vehicle WHERE MakeId ="' + $scope.memberdetailData.selected_Make_ID + '";', function (res) {
console.log("this is respo");
//console.log(res);
$scope.memberdetailData.Vehicle_Model = null;
$scope.memberdetailData.Vehicle_Model = res;
console.log($scope.memberdetailData.Vehicle_Model);
// console.log($scope.memberdetailData.Vehicle_Model);
$scope.memberdetailData.selected_Model = null;
$scope.memberdetailData.selected_Model = $scope.memberdetailData.Vehicle_Model[0].ModelId;
}, function () {
// globalFactory.showAlert('Data Error', 'No Salutation Master Found, Kindly Sync Salutation Master');
});
}
DBFactory -
db_factory_obj.selectVehicleMasterData = function (query, callBack, errorcall) {
var result = [];
db_factory_obj.db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, rs) {
for (var i = 0; i < rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = {
MakeId: row['MakeId'],
Make: row['Make'],
ModelId: row['ModelId'],
Model: row['Model']
}
}
////console.log(result);
callBack(result); // <-- new bit here
}, errorcall);
});
}
Please help.
Thanks.
Krunal

Related

Only first element is visible in Dynamic Dropdown list

I am trying to have a dependent Dropdown list, Districts based on the value of selected State. But my code is rendering only the first element of the dynamic dropdown list.
<div class="input-field col s3">
<select id="nativeDistr">
<option value="" disabled selected>
Native District
</option>
</select>
<label>Destination District</label>
;
Appscript Code Snippet.
function getDistricts(state) {
Logger.log("Selected State=" + state);
var fileName = "states-and-districts.json";
var files = DriveApp.getFilesByName(fileName);
try {
if (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var json = JSON.parse(content).states_districts;
for (var i = 0; i < json.length; i++) {
if (json[i]["state"] === state) {
var districts = json[i]["districts"];
}
}
}
var optList = generateOptions(districts);
Logger.log(optList);
return optList;
} catch (err) {
return "Error getting data";
}
}
Javascript code
<script>
document.getElementById("nativeState").addEventListener("change", getDistr);
function getDistr() {
var state = document.getElementById("nativeState").value;
console.log("state scriptt:" + state);
google.script.run.withSuccessHandler(updatedistricts).getDistricts(state);
}
function updatedistricts(districts) {
console.log("From districts:" + districts);
var nativeDistr = document.getElementById("nativeDistr");
nativeDistr.innerHTML = districts;
M.updateTextFields();
} // When user selects the state the valuee off the state should get registered for district search
Blockquote
Durin execution I am getting the complete list of dynamic dropdown but while rendering the page only the first element is getting displayed.
Blockquote
M.updateTextFields() do not update dynamic dropdown, it updates the text fields. So there is a need to store a global reference to materialize select box to initialize it, post that there is a need to destroy that instance, and then reinitialize the select box again.
<script>
document.addEventListener("DOMContentLoaded", function () {
var elems = document.querySelectorAll("select");
var instances = M.FormSelect.init(elems);
});
document.getElementById("nativeState").addEventListener("change", getDistr);
function getDistr() {
var state = document.getElementById("nativeState").value;
google.script.run.withSuccessHandler(updatedistricts).getDistricts(state);
}
function updatedistricts(distrList){
nativeDistr.innerHTML = distrList;
var subcatSelectElem = document.querySelectorAll("select");
var subcatSelectInstance = M.FormSelect.init(subcatSelectElem, {});
}
Credit for soln.: Chicago Computer Classes

How to display data value in real time depending on the other column with AJAX/PHP/JAVASCRIPT?

I'm currently trying to do a survey system. I have a dynamic dropdown that displays one column 'questiontitle' from my table database. Here's my code of displaying the 'questiontitle' in the dropdown.
<?php
$query=mysqli_query($con, "SELECT * FROM question");
while($row=mysqli_fetch_array($query))
{
?>
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
<?php
}
?>
echo "</select>";
And here's my database table.
My main question is how do I display the 'Option_1 to Option_10 columns' depending on the 'answer_type' column when a data is clicked from the dropdown in real time without refreshing the page? Like if the 'answer_type' is checkbox, it will display the option1-10 as checkbox and if it's radiobutton, it will display the option1-10 as radiobuttons.
There is a lot work to be done to achieve what you want to do. But I can give you a small snippet which you can use to start.
What you still have to do is
Show a page with all questions in the select box. This is done in PHP
checking how ajax works. Expand the showQuestion() function with ajax functionality so your question & answer data is retrieved from the server. this is a good read. When you got your answer, call the appropriate function to display your question and answers. OR store all your information locally...
add a button so that you can send the answers to the server. Listen to the click event and send data (small modifications are required to what I have wrote though) to the server (read the link that I have shown in point 2)
// question object
var questions = {
json1: {
questiontitle: 'How frequently ...',
answertype: 'radiobutton',
options: ['Heavy user', 'serious user', 'regular user', 'light user']
},
json2: {
questiontitle: 'What part of the day...',
answertype: 'checkbox',
options: ['Morning', 'Afternoon', 'Early evening', 'lat evening']
},
json3: {
questiontitle: 'To what extend does the ...',
answertype: 'radiobutton',
options: ['1-5 times', '6-10 times', '> 10 times']
}
};
// function that adds the "questions" input elements to the container
function insertToQuestionBox(els) {
var box = document.getElementById('questionBox');
// cleanup box
while(box.firstChild) box.removeChild(box.firstChild);
// populate with els
for(var i = 0; i < els.length; ++i) box.appendChild(els[i]);
}
// creates the input element based on args
function createInput(type, name, text) {
var i = document.createElement('input');
i.type = type;
i.name = name;
var l = document.createElement('label');
l.textContent = text;
var s = document.createElement('section');
s.appendChild(l);
s.appendChild(i);
return s;
}
// create element with question in it
function createQuestionEl(question) {
var s = document.createElement('span');
s.textContent = question;
return s;
}
// function that is called if the question is of type radio
function handleRadioButtons(data) {
var inputs = [];
inputs.push(createQuestionEl(data.questiontitle));
for(var i = 0; i < data.options.length; ++i) {
inputs.push(createInput('radio', 'rraaddioo', data.options[i]));
}
insertToQuestionBox(inputs);
}
// create checkboxes
function handleCheckboxes(data) {
var inputs = [];
inputs.push(createQuestionEl(data.questiontitle));
for(var i = 0; i < data.options.length; ++i){
inputs.push(createInput('checkbox', 'nana' + i, data.options[i]));
}
insertToQuestionBox(inputs);
}
// gets called each time the drop down has changed
function showQuestion() {
var data = questions[this.value];
switch(data.answertype) {
case 'radiobutton': handleRadioButtons(data); break;
case 'checkbox': handleCheckboxes(data); break;
// todo when default? error ?
}
}
// listen to select changes
document.getElementById('showQuestion').addEventListener('change', showQuestion);
<select id="showQuestion">
<option>please choose</option>
<option value="json1">show json1</option>
<option value="json2">show json2</option>
<option value="json3">show json3</option>
</select>
<div id="questionBox"></div>
On select box change event pass questionid to server side and query your database for answer_type and options and in that method add a condition
$options = '';
if(anwsertype=='radio') {
$options .= <input type="radio" /> Your option
} else {
$options .= <input type="checkbox" />Your option
}
The above condition should be in a loop for each option.

How do I populate a select input based on 2 radio button values, from mysql

So I have a registration form for archery contests and I want users to select 2 things (their age category and their bow type).
Once those 2 are selected, I want the next field (select) to show up and be populated with information from my mysql database.
This field is a selection of shooting levels, differenciated in classes.
In the database, I have 4 tables.
1 for age category (id, name)
1 for bow type (id, name)
1 for shoot level (id, name)
1 table to link all above (id, ac_id, bt_id, sl_id)
So based on radio 1 being clicked and radio 2 being clicked, I want to fire a query on the link table to only get the shooting levels which belong to the 2 radio values..
Can anyone please help me with this?
Try this:
$('#age').click(function(){
var age = $(this).val();
var bow = $('#bow').val();
function getShootingLevel(age, bow);
});
$('#bow').click(function(){
var age = $('#age').val();
var bow = $(this).val();
function getShootingLevel(age, bow);
});
function getShootingLevel(age, bow)
{
// ajax call
}
P.S. You can also check if radio is selected or not.
I got it :)
$(document).ready(function() {
$('input[type=radio][name=leeftijdscategorie]').change(function() {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
$('input[type=radio][name=schiettechniek]').change(function() {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
});
function removeOptions(selectbox) {
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--) {
selectbox.remove(i);
}
}
function GetLevels(agetype,bowtype) {
removeOptions(document.getElementById(\"schietklasse\"));
$.ajax({
url: '/info/wscript.php',
data:
{
agetype: agetype,
bowtype: bowtype
},
type: 'post',
dataType: 'json', // returns response data as json//
success: function(output) {
var selectBox = document.getElementById(\"schietklasse\");
var options = output; //JSON.parse(output);
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add( new Option(option.text, option.value, option.selected) );
}
}
});
}
I basically made this radio check seperate (so double) because I want people to be able to change their choice. Now, it fires a POST to a php file which gets the information and returns it as JSON.

how to append value in select tag inside dynamic table

im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.

Need help to write Jquery script that will append text to the ends of existing DropDown list option names

Just to give you a better idea I am making a computer customization page with a bunch of dropdown lists
that display the Part name and have the PartID as the data value. I wish to append all the part name text values for all options excluding the currently selected option with the price difference between the price of this part and the currently selected one.
i.e:
[Intel i7 950] - selected visible option
[Intel i7 960 (+ $85)] - not selected but in the drop down list
[Intel i7 930 (- $55)] - not selected but in the drop down list
I do not have the price, so I would need to retrieve the price for all the option data values (PartID)
and return it as a json collection ({PartID, Price}) key value pairs as the page loads in Ajax call. I would only need to make one Ajax call and use this data for all onchange events for my dropdown list.
Then using Javascript/Jquery, for each option, using its data value (PartID) as key, find its price from the returned Json collection and append to the end of the non selected options text value the difference between its price and the currently selected options price. This will have to run every time (onchange) that a new option is selected.
Using ASP.NET MVC3/Razor
Here's what my dropdown list html looks like, I have about ten such dropdown lists:
<select id="partIdAndCount_0__PartID" name="partIdAndCount[0].PartID">
<option value="">Select processor</option>
<option value="3">Intel Core i7 950</option>
<option value="4">Intel Core i7 930</option>
</select>
Someone has now suggested I take the easier approach and simply add the cost to each option as additional attribute. In my view I have code as follows:
#Html.DropDownList("partIdAndCount[0].PartID", new SelectList(Model.Processor.Products, "ProductID", "Name"), "Select processor" )
I can add additional attributes but only to the select tag and not option?
new { datacost = Model.Processor.Products[0].ListPrice }
I know how to get at the text value of all the options/option and to change it entirely, but not how to append to it or use javascript to use the options data values to find their price in the json collection and then only append to the non selected options text values etc. Also no idea how initially gather all options data values and pass them in an ajax call to my action method that will return the json result.
<script type="text/javascript">
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { mydata = data; OnSuccess(data) },
dataType: "json"
});
});
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
break;
}
};
$(this).find('option').each(function () {
$(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
var newtext = uop - sop;
var text = $(this).attr("text");
$(this).find('span').html(newtext);
});
});
};
//$(document).ready(function () { $("#partIdAndCount_0__PartID").prepend('<option value="0">Select Processor<option>'); });
</script>
Maybe it would be easier if you just included the price of each item in the option (inside of a data-cost attribute, or whatever), like this (just guessing on the prices):
<select id="partIdAndCount_0__PartID" name="partIdAndCount[0].PartID">
<option value="">Select processor</option>
<option data-cost="210" value="5">Intel Core i7 930</option>
<option data-cost="250" value="3">Intel Core i7 950</option>
<option data-cost="280" value="4">Intel Core i7 960</option>
</select>
Then use this script to update the options instead of needing to make numerous calls to your server to get more json data. Here is a demo.
$('select')
.find('option').each(function() {
// add spans to the option, done here because it doesn't
// seem to work if you include the span in the markup
$(this).append(' <span></span>');
}).end()
.change(function() {
var v, diff,
// get cost of selected option
sel = parseFloat($(this).find('option:selected').attr('data-cost'), 10) || 0;
// Add cost difference to option
$(this).find('option[data-cost]').each(function() {
v = parseFloat($(this).attr('data-cost'), 10);
diff = '(' + (sel > v ? '-' : '+') + ' $' + Math.abs(sel - v) + ')';
if (sel === v) {
diff = '';
}
$(this).find('span').html(diff);
});
})
// show values on init
.trigger('change');

Categories

Resources