Interference between dropdownlists - c#

In my view I have a code like
<div id="DDLs">
<p>Begin: #Html.DropDownListFor(model => model.ItemID, Model.items, new { #id = "list1" })</p>
</div>
...
<script type="text/javascript">
$(document).ready(function () {
$("#list1").change(function () {
var countrySelected = $("select option:selected").first().text();
$.get('#Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>
That works as expected.The problem is when I add another dropdownlistfor like this:
<div id="DDLs">
<p>Begin: #Html.DropDownListFor(model => model.ItemID, Model.items, new { #id = "list1" })</p>
<p>Options: #Html.DropDownListFor(model => model.Option, #ViewBag.Options as SelectList, new { #id = "list2"})</p>
</div>
After adding it, change event is sometimes fired with selected value of the added dropdownlist, not the one that I expect it would. I have no idea why.
Edit:
Thanks to dansasu11 answer, I've figuired out that the problem was in line:
var countrySelected = $("select option:selected").first().text();
I changed it to:
var countrySelected = $(this).val();
Now everything works - of ocurse insted of reciving Text of selected item I'm getting its value, which is also fine.
Perhaps I should have spent more time learning jQuery.

try
<script type="text/javascript">
$(document).ready(function () {
$("#list1").change(function () {
var countrySelected = $(this).find("option:selected").text();
$.get('#Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>
or if you want to be able to select any of the dropdown and get the selected option then change to
<script type="text/javascript">
$(document).ready(function () {
$("select").change(function () {
var countrySelected = $(this).find("option:selected").text();
$.get('#Url.Action("MyAction")',
{ id: countrySelected }, function (data) {
$("#apendedInfo").html(data);
});
});
});
</script>

Related

How to display the value in dropdown using jquery?

i have a dropdown, where i can select AgencyName, with that selected AgencyName, i tried to display its AgentName in the next dropdown. But my code does'nt display the AgentName in the next dropdown.
i have my view page like:
<span class="LabelNormal">Agency</span>
#Html.DropDownListFor(m => m.LightAgencies.agencykey, new SelectList(Model.LightAgencies.Agency, "Key", "Value"), "", new {#id = "OwnerAgency" })
<span class="LabelNormal">Agent</span>
#Html.DropDownListFor(m => m.LightOwnerAgent.au_key, new SelectList(""), "", new { #id = "OwnerAgent" })
And i have my jquery like,
$(document).ready(function () {
$("#OwnerAgency").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgent").html(procemessage).show();
var url = "/Index/GetOwnerAgent/";
// Get agency key
var OwnerAgency = $("#OwnerAgency :selected").val();
// Get agent
var OwnerAgent = $("#OwnerAgent :selected").val();
$.ajax({
url: url,
data: { agencykey: OwnerAgency },
cache: false,
type: "POST",
success: function (data) {
var OwnerAgent = $("#OwnerAgent :selected").val();
alert(OwnerAgent);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
where my controller "/Index/GetOwnerAgent/" giving the exact value for OwnerAgent. As iam the beginner i dont know how to do this, Kindly tell me.
In your code, you display the selected value in the dropdownlist as soon as the controller responds. I think you want to select the result from the controller in the dropdown.
Assuming that the data returned from the controller is a value that exists in the dropdownlist, you should be able to use:
...
success: function (data) {
$("#OwnerAgent").val(data);
}
...

i can not use jquery select2 with json

i MVC4 and i want to add a select box that retrieve data (Product code) from my database the problem is that i have a message from select2.js telling select2 touppercase of undefined.
*all the JS file are uploaded.
here is my Jquery function:
<script>
$(document).ready(function () {
$('#Product_cd').select2({
minimumInputLength: 2,
ajax: {
url: '#Url.Action("AutoComplete")',
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
});
</script>
here is my controller AutoComplete
public JsonResult AutoComplete(string q)
{
Mydb db = new Mydb();
var Code = from c in db.Products
where c.Product_code.Contains(q)
select c.Product_code;
var result = Code.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
}
and here is part of the view:
<div class="col-md-2">
<div>#Html.DisplayNameFor(x => x.Product_cd )</div>
<div> #Html.TextBoxFor(x => x.Product_cd)<i class="fa fa-search"></i></div>
</div>
can any one tell me what is the problem

how to add javascript to an Asp.net MVC app

I am building an Asp.net MVC app and would like to add a datepicker.
I have this code in my form in the view
#Html.LabelFor(b => b.Date)
#Html.EditorFor(b => b.Date, new {id = "news_date"})
and I would like to add this javascript to it to enable to datapicker:
$(document).ready(function () {
$("#news_date").datepicker({ dateFormat: 'dd/mm/yy' });
});
however when the application is run it shows the above code as text on the page.
How do I get it to recognize it as javascript?
Use script tag
#Html.LabelFor(b => b.Date)
#Html.EditorFor(b => b.Date, new {id = "news_date"})
<script type="text/javascript">
$(document).ready(function () {
$("#news_date").datepicker({ dateFormat: 'dd/mm/yy' });
});
</script>
wrap your code with script tags
<script type="text/javascript">
$(document).ready(function () {
$("#news_date").datepicker({ dateFormat: 'dd/mm/yy' });
});
</script>

mvc ajax dropdownlist value problems

So I'm having problems with dealing with cascading dropdownlists. Everytime I would pick a value on the 1st dropdown the 2nd dropdown will be populated but "with the selected value from the first" at the top of the 2nd dropdown. Does that make sense? Following are the codes. I'm not sure if it's appending correctly, can't seem to find anything on firebug.
Any advice is appreciated.
Thanks!!
the view:
<script type="text/javascript">
$(function () {
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId("1stLevel") %>').change(function () {
$.ajax({
url: '<%: Url.Action("Index","2ndLevelDetails") %>?1stLevelId=' + $(this).val(),
success: function (data) {
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId("2ndLevelId") %>').html(data);
},
async: false
});
});
});
</script>
<div class="dropdown">
<%: Html.DropDownList("1stLevelDetails", new SelectList(Model.1stLevel, "1stLevelId", "1stLevelDescription"))%>
</div>
<div class="dropdown">
<%: Html.DropDownListFor(model => model.2ndLevelId, new SelectList(Model.NTEESecondaryCodes, "2ndLevelId", "2ndLevelDescription", Model.2ndLevelId))%>
</div>
the controller 2ndlevel that returns the list of options
public string Index(int 1stLevelId)
{
var ntee = new System.Text.StringBuilder();
foreach (2ndLevelDetails code in 2ndLevelDetails.Find2ndLevelIds(ArgentDb, 1stLevelId))
{
ntee.AppendFormat("<option value=\"{0}\">{1}</option>", code.2ndLevelId, code.Description);
}
return ntee.ToString();
}
Try using jquery's live binder ..
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId("1stLevel") %>').live('change', function () {
// ... code here
I've had to use live to bind to the change event since I can remember.. I don't know why.

Can java script add the contents below to a table aswell

Can java script add the contents below to a asp table aswell at the same time (with html tags)
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
return false;
});
});
</script>
<textarea style="border: 0" cols="77" rows="2">Write Something....</textarea>
<button>Post Message</button>
<div id="test1"></div>
</asp:Content>
something like:
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
//$save append aswell to Table1
return false;
});
});
</script>
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
var newdiv = $("<div></div>").html(x).attr('id','test');
$('#test1').append(newdiv);
$('#Table1').append(newdiv);
//$save append aswell to Table1
return false;
});
});
</script>
It seems like you are using jquery here.
Have you got your jquery framework loaded & tried your code to see if it works??
It is running fine on jsfiddle.net here
Updates
If your Table1 is on the same page.
All you need to do is to get hold of the DOM element.
if you have a table
<table id="Table1">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
You can add after your code
$('#test1').append('<div id="test">' + x + '</div>');
this code
$('#Table1 tr:last').after('<tr><td>'+ x +'<td></tr>');
Hope you find this helpful

Categories