I have created 4 dropdown of book levels, each one dependent on its upper level (ex. Book Level 2 shows dropdown values dependent on Book level 1 category and so on...) and it is working fine also, but now I want only Book Level 4 independent and should show the values if the Book Level 1 is not empty. i.e., onchange Book level 1, Book Level 2 dropdown shows the value dependent on Book level 1 category and it also should show the Book Level 4 dropdown values which are independent. Help is required.
index.php
<body>
<form method="post" name="AddBookDetails">
<table>
<tr>
<td>Book Level 1</td>
<td><select id="bl1" name="bookl1"><option value="" selected="selected">Book Level 1</option>
<?php
mysqli_set_charset($db,'utf8');
$result=mysqli_query($db,"select * from booklevel1 ORDER BY booklevel1 ASC");
if ($result>0){
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['bl1_code'].'">'.$row['booklevel1'].'</option>';
}
}
else{
echo '<option value="">Book Level 1 not present</option>';
}
?></select></td>
</tr>
<tr>
<td>Book Level 2</td>
<td><select id="bl2" name="bookl2" ><option value="" >Select Level 2</option></select></td>
</tr>
<tr>
<td>Book Level 3</td>
<td><select id="bl3" name="bookl3" ><option value="" >Select Level 3</option></select></td>
</tr>
<tr>
<td>Book Level 4</td>
<td><select id="bl4" name="bookl4" ><option value="" >Select Level 4</option></select></td>
</tr>
</table>
<input name="addbook" type="submit" value="Save">
</form>
</body>
ajaxData.php
<body>
<?php
include 'dbConfig.php';
if(!empty($_POST["bl1_code"])){
$query2=$_POST['bl1_code'];
$query = $db->query("SELECT * FROM booklevel2 WHERE bl1_code LIKE '%$query2%' ORDER BY booklevel2 ASC");
$rowCount = $query->num_rows;
//Book Level 2 option list
if($rowCount > 0){
echo '<option value="">Select Level 2</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['bl2_code'].'">'.$row['booklevel2'].'</option>';
}
}else{
echo '<option value="">Level 2 empty</option>';
}
}
elseif(!empty($_POST["bl2_code"])){
$query3=$_POST["bl2_code"];
$query = $db->query("SELECT * FROM booklevel3 WHERE bl2_code LIKE '%$query3%' ORDER BY booklevel3 ASC");
$rowCount = $query->num_rows;
//Book Level 3 option list
if($rowCount > 0){
echo '<option value="">Select Level 3</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['bl3_code'].'">'.$row['booklevel3'].'</option>';
}
}else{
echo '<option value="">Level 3 empty</option>';
}
}
elseif(!empty($_POST["bl3_code"])){
$query4=$_POST["bl3_code"];
$query = $db->query("SELECT * FROM booklevel4 WHERE bl3_code LIKE '%$query4%' ORDER BY booklevel4 ASC");
$rowCount = $query->num_rows;
//Book Level 4 option list
if($rowCount > 0){
echo '<option value="">Select Level 4</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['bl4_code'].'">'.$row['booklevel4'].'</option>';
}
}else{
echo '<option value="">Level 4 empty</option>';
}
}
?>
</body>
ajax.js
// JavaScript Document
$(document).ready(function() {
$('#bl1').on('change',function(){
var blevel1 = $(this).val();
if(blevel1){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl1_code='+blevel1,
success:function(html){
$('#bl2').html(html);
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
}else{
$('#bl2').html('<option value="">Select Level 1 First</option>');
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
$('#bl2').on('change',function(){
var blevel2 = $(this).val();
if(blevel2){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl2_code='+blevel2,
success:function(html){
$('#bl3').html(html);
}
});
}else{
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
$('#bl3').on('change',function(){
var blevel3 = $(this).val();
if(blevel3){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl3_code='+blevel3,
success:function(html){
$('#bl4').html(html);
}
});
}else{
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
});
create bl1,bl2,bl3 bl4 function. on change call the function.
something like this
<select id="bl1" onchange="bl1()">
Just before bl1 function ends, call bl4();
function bl1()
{
$('#bl1').on('change',function(){
var blevel1 = $(this).val();
if(blevel1){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'bl1_code='+blevel1,
success:function(html){
$('#bl2').html(html);
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
});
}else{
$('#bl2').html('<option value="">Select Level 1 First</option>');
$('#bl3').html('<option value="">Select Level 2 First</option>');
$('#bl4').html('<option value="">Select Level 3 First</option>');
}
//function name here and business logic here
if(blah blah)
{
bl4();
}
else{ //blah blah}
}
}
I stumbled upon some code that has jQuery validation which is triggered after an ajax call that adds items to the DOM. The validation is working but the message is missing. just the field is highlighted. I have been playing with this for a while to get it to work, but so far no luck. Any ideas, thoughts appreciated.
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var otherIncomesCount = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var count = otherIncomesCount;
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
});
The validation succeeds for both required on additionalIncomeTypeIDMenu, and required and positive on amountTextBox, but the messages for both fail to show up:
function addOtherIncomeValidation(container) {
if (container) {
var additionalIncomeTypeIdMenu = $(container).find('select.other-income-type-id');
var amountTextBox = $(container).find('input.other-income-amount');
$(additionalIncomeTypeIdMenu).rules('add', {
required: true,
messages: {
required: 'Please select an income type'
}
});
$(amountTextBox).rules('add', {
required: true,
positive: true,
messages: { positive: 'must be positive number'
}
});
}
}
BTW The ajax call returns a partial EditorTemplate here, which you can see uses ValidationMessageFor.
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />#Html.ValidationMessageFor(x => x.AdditionalIncomeTypeId)
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />#Html.ValidationMessageFor(x => x.Amount)
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
HTML:
<div id="OtherIncome" class="applicant-section">
<h2 class="header2">Other Income</h2>
<div class="cornerForm">
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_0__Id" name="OtherIncome[0].Id" type="hidden" value="385" />
<label class="other-income-type-id-label" for="OtherIncome_0__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_0__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_0__AdditionalIncomeTypeId" name="OtherIncome[0].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option selected="selected" value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_0__Amount" name="OtherIncome[0].Amount" style="" type="text" value="0.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XNxxxxx753/385">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_1__Id" name="OtherIncome[1].Id" type="hidden" value="412" />
<label class="other-income-type-id-label" for="OtherIncome_1__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_1__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_1__AdditionalIncomeTypeId" name="OtherIncome[1].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option selected="selected" value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_1__Amount" name="OtherIncome[1].Amount" style="" type="text" value="22.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XN42093753/412">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div id="additional-other-income"></div>
<input id="numberOfNewOtherIncomes" name="numberOfNewOtherIncomes" type="hidden" value="0" />
<input data-val="true" data-val-number="The field OriginalOtherIncomeTotal must be a number." id="OriginalOtherIncomeTotal" name="OriginalOtherIncomeTotal" type="hidden" value="22.0000" />
<a class="editable-link" href="/Applicant/AddOtherIncome?appId=XNxxxxx753" id="add-other-income-link">Add Other Income</a>
</div> </div>
Validation code:
$.validator.addMethod('positive', function(value, element) {
var check = true;
if (value < 0) {
check = false;
}
return this.optional(element) || check;
}, "Value must be a positive number."
);
I didn't think I would find my own answer but I did. first I have to apologize for my response to #Sparky with his request for rendered HTML. I did a "View page source" but that didn't include all the stuff which was added from the ajax call after the server delivered it's stuff. I suspect if I did include the extra DOM stuff at first, you would have pinpointed the issue sooner. My bad. Now on to the answer.
It appears that when injecting an EditorTemplate into the DOM in the way shown above, it doesn't properly process the page like you would expect in MVC. The code for #Html.ValidationMessageFor simply does not get parsed AT ALL. I am a little new to validation as you can see so I don't know why it behaves this way. To solve my problem here is what I did:
I updated my Editor Template slightly to look like this:
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />
#Html.ValidationMessageFor(x=>x.AdditionalIncomeTypeId)
<span id="AdditionalIncomeTypeIdValidation"></span>
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />
#Html.ValidationMessageFor(x=>x.Amount)
<span id="amountValidation"></span>
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
Notice the new span tags, which is are added next to the #Html.ValidationMessageFor.
then in my success function from the ajax call in javascript I made these changes:
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var count = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var amountValidation = $(item).find('#amountValidation');
var typeIdValidation = $(item).find('#AdditionalIncomeTypeIdValidation');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
amountValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'Amount')
.attr('data-valmsg-replace','true');
typeIdValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'AdditionalIncomeTypeId')
.attr('data-valmsg-replace','true');
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
notice I am manually adding in the missing validation spans that were not rendering. Now the validation message shows up at validation! Yay. I am not sure however that this is the best fix. It looks and smells like a hack, but I got it to work. I am sure it can be done a better way. Thanks again for interaction and feedback.
i'm having problem. i have a survey form, in this form i used also the ajax to call some of the data. when user click cancel, i want it to navigate to other page where it display the list of data in listview using ajax. for the clicking and navigation part, i've succeed to bring it to the page that i want, but the problem is, it does not display anymore the list of data. I used the same way as i did for other page but for this i can't get..any help? i've gone through my code several times but i can't get what makes it wrong. this is my code for the page survey form:
$('#MrateCourse').live('pageinit', function(){
var rowInput = "1";
var pageInput = "1";
var idInput = "${courseId}";
var regNoInput = "${regNo}";
$.ajax({
url: '${pageContext.request.contextPath}/getRegisteredClassesDetails.html',
data: ( {rows: rowInput, page: pageInput, courseId: idInput, regNo: regNoInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul></ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(courseId) {
html = ' Course Name :
+ '<b>' + json_results.rows[courseId].courseName + '</b>';
html += '</br> Registered Person :
+ '<b>' + json_results.rows[courseId].fullName + '</b>';
listItems.append(html);
});
$('#list ul').listview();
}
});
});
$(function() {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes;
$('#dateTime').html("<b>" + month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + suffix + "</b>");
});
<form id="" action="${pageContext.request.contextPath}/MRegisteredClasses.phone" method="POST">
<table>
<tr>
<td>Date:
<span id="dateTime"></span><br/></td>
</tr>
<tr>
<td>Company:</td>
<td><input type="text" value=""/><br/></td>
</tr>
<tr>
<td><b>Based on your experience in this course, please answer<br>the following questions:
<br>1 = Strongly Disagree, 5 = Strongly Agree</b></td>
</tr>
<tr>
<td>The web-based training media used was of high quality.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>I had enough time to learn the subject matter covered in the course.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>My knowledge and/or skills increased as a result of this course.</td>
<td><select>
<option value=""></option>
<option value="5">5</option>
<option value="5">4</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
</select><br/></td>
</tr>
<tr>
<td>Additional comments or ideas to improve this course:</td>
</tr>
<tr>
<td><textarea rows="3" ></textarea></td>
</tr>
<tr>
<td>What additional topics would you like to see addressed in a future online course?</td>
</tr>
<tr>
<td><textarea rows="3"></textarea></td>
</tr>
<tr>
<td align="left">
<input type="submit" data-inline="true" id="submit" value="Submit This Survey" class="ui-btn-right"
onClick="confirm( 'Thanks for filling the survey' )"/>
<a href="${pageContext.request.contextPath}/MRegisteredClasses.phone" class="ui-btn-right"
data-role="button" data-inline="true">Cancel</a>
</td>
</tr>
</table>
</form>
and this is my code for the page that it need to navigate.
<div data-role="page" id="MregisteredClasses">
<div data-role="content">
<h3>Courses Name</h3>
<p id="note">*Click at the courses to view the details</p>
<h1></h1>
<div id="courseName">
<ul data-role="listview" data-inset="true" id="list"></ul>
<script type="text/javascript">
$('#MregisteredClasses').on('pageinit', function(){
var rowInput = "1";
var pageInput = "1";
$.ajax({
url: '${pageContext.request.contextPath}/getRegisteredClassesData.html',
data: ( {rows : rowInput , page : pageInput}),
type: 'POST',
success: function(json_results){
$('#list').append('<ul data-role="listview" data-inset="true" data-split-icon="gear"</ul>');
listItems = $('#list').find('ul');
$.each(json_results.rows, function(key) {
html = '<li <h3><a href="${pageContext.request.contextPath}/MRegisteredClassesDetail.phone?courseId='
+ [json_results.rows[key].courseId] + '®No=' + [json_results.rows[key].regNo] +
'"rel="external">' + json_results.rows[key].courseName+ '</a></h3>'
+ '<a href="${pageContext.request.contextPath}/MRateCourse.phone?courseId='
+ [json_results.rows[key].courseId] + '®No=' + [json_results.rows[key].regNo] +
'"rel="external">RATE THIS COURSE</a>';
listItems.append(html);
});
$('#list ul').listview();
},
});
});
</script>
</div>
</div><!-- /content -->
I got it already.. I add data-ajax="false" to my form.
New to Razor, trying to convert the following:
<select id="Province" name="Province" style="width: 235px; background-color: #FFFFCC;">
<%
string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName;
if (Model != null && !String.IsNullOrEmpty(Model.Province))
selectedProvinceName = Model.Province;
else
selectedProvinceName = ConfigData.DefaultProvinceName;
foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName ? " selected=\"selected\"" : String.Empty;
%>
<option value="<%= anEntry %>" <%= selectedTextMark %>>
<%= anEntry %></option>
<%
}
%>
</select>
</td>
The Razor:
<select id="Province" name="Province" style="width: 235px; background-color: #FFFFCC;">
#string[] provinces = ViewBag.ProvincesForSelectedCountry;
string selectedProvinceName;
if (Model != null && !String.IsNullOrEmpty(Model.Province))
selectedProvinceName = Model.Province;
else
selectedProvinceName = ConfigData.DefaultProvinceName;
foreach (var anEntry in provinces)
{
string selectedTextMark = anEntry == selectedProvinceName ? " selected=\"selected\"" : String.Empty;
<option value="#anEntry" #selectedTextMark>
#anEntry</option>
}
</select>
</td>
I get this error:
Invalid expression term 'string' in #string[] provinces = viewBag.ProvincesForSelectedCountry;
Thanks in advance.
You need
#{
string[] provinces = ViewBag.ProvincesForSelectedCountry;
and then a closing } before the </select> tag.
I have a drop down list will retrieve all product category from database and populate, another drop down list will show the product name based on the category selected by user.I am able to populate category but I was stuck at the product part
<p>
<label for="pcategory">Product Category</label>
<select name="pcategory" size="0" onchange="get_product(this.selectedIndex);">
<%
Category cat = new Category();
java.util.ArrayList<Category> catList = cat.retrieveCategory();
for (int i = 0; i < catList.size(); i++) {
%>
<option value="<%=(i + 1)%>"><%=catList.get(i).getCatname()%></option>
<%
}
%>
</select>
</p>
<jsp:include page="data.jsp"/>
function get_product(category){
$.ajax({
type: "GET",
url: "data.jsp",
data: "category=" + category,
success: function(msg){
}
});
}
This is for data.jsp
<p>
<label for="pname">Product Name:</label>
<select name="state" id="state">
<%
if (request.getParameter("category") != null) {
%>
<option value="1">1</option>
<option value="2">2</option>
<% } else {
%>
<option value="1">2</option>
<option value="2">3</option>
<% }%>
</select>
my data.jsp will populate the product name. By default will populate the first category from database if user never change the category drop down list.
I was able to do the following simple example using a servlet to get product names based on a product category. You'll need to modify it a little bit to fit into your particular scenario. Let me know if this is helpful and puts you down the right path...
The HTML page:
<html>
<head>
<SCRIPT SRC="jquery.js" TYPE="text/javascript"></SCRIPT>
</head>
<body>
<p>
<label for="pcategory">Product Category</label>
<select name="pcategory" id="pcategory" size="0">
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
</p>
<p>
<label for="pname">Product Name:</label>
<select name="state" id="state">
<option value="1">Product Name 1 For Category 1</option>
<option value="2">Product Name 2 For Category 1</option>
<option value="3">Product Name 3 For Category 1</option>
</select>
</p>
</body>
<script type="text/javascript">
$category = $('#pcategory');
$category.change (
function() {
$.ajax({
type: "GET",
url: "GetProductName",
data: {category: $category.attr("selectedIndex") },
success: function(data){
$("#state").html(data)
}
});
}
);
</script>
</html>
The servlet which will give you the product names...
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class GetProductName extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
int category = Integer.parseInt(request.getParameter("category"));
switch (category) {
case 1:
out.print(
"<option value='1'>Product Name 1 For Category 2</option>" +
"<option value='2'>Product Name 2 For Category 2</option>" +
"<option value='3'>Product Name 3 For Category 2</option>"
);
break;
case 2:
out.print(
"<option value='1'>Product Name 1 For Category 3</option>" +
"<option value='2'>Product Name 2 For Category 3</option>" +
"<option value='3'>Product Name 3 For Category 3</option>"
);
break;
default:
out.print(
"<option value='1'>Product Name 1 For Category 1</option>" +
"<option value='2'>Product Name 2 For Category 1</option>" +
"<option value='3'>Product Name 3 For Category 1</option>"
);
break;
}
} catch (Exception ex) {
out.print("Error getting product name..." + ex.toString());
}
finally {
out.close();
}
}
}