To update a text box on onother textbox keypress MVC 4 - c#

I am new to MVC and I have 2 text boxes,On 1 text box I need to type the numbers based on the number it should get the data from a lookup table(where MyAge is the lookup table) based on the number that I enter in one text box
#foreach (var pa in Model[i].MyAgeTable)
{
if (TextboxAge.trim() == pa.Trim())
{
....
}
}

You can use jQuery to do this. For using jQuery you need to add the following in your head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
and then the following code will do what you want:
<script type="text/javascript" >
$(document).ready(function (){
$("#textBox1").keypress(updateTextBox2());
function updateTextBox2() {
// code to get update another textbox
}
});
</script>
Documentation for .keypress()
There are different ways of writing the code to get the data from look up table. For instance you can make an ajax request to the server.
Documentation for jQuery.ajax()

Related

JQuery ajax post works only the first time

Edit (I have solved this):
I have figured this out - I was returning a string (integer.ToString("C")) in the JSON data which I then placed into my textbox. Upon clicking the submit button, it was trying to parse the currency (now: "£2.99") into an integer (currentAmount is an integer in my bid object), which of course became 0, which resulted in my bid form not being able to serialise this data.
Currently I have an Ajax request through JQuery which performs a postback on my BID controller method. The method returns some JSON which lets me update my HTML with current values, such as Current Price, Bid Count, and the Next Recommended Bid Price.
My problem is, once I click the submit button, the ajax makes the post and correctly returns the data I expect. However, when I click the Submit button a second time, the bid passed pass through to my controller from my View doesn't have my form data (amount is now 0, when I can see it isn't on the page)
Why is this? I am using entity framework to save my auction and bid.
Here is my code:
Controller BID Post
[HttpPost]
public ActionResult Bid(Bid bid)
{
var db = new AuctionsDataContext();
var auction = db.Auctions.Find(bid.AuctionId);
bid.Username = User.Identity.Name;
auction.Bids.Add(bid);
auction.CurrentPrice = bid.Amount;
db.SaveChanges();
return Json(new
{
CurrentPrice = bid.Amount.ToString("C"),
BidCount = auction.BidCount,
Number = (bid.Amount + 1).ToString("C")
});
}
My BID form on Auction.cshtml
<p>
#using (Html.BeginForm("Bid", "Auctions"))
{
var lowestBidAmount = auction.CurrentPrice.GetValueOrDefault(auction.StartPrice) + 1;
<span>
Bid: $#Html.TextBox("amount", lowestBidAmount)
#Html.ValidationMessage("amount")
</span>
#Html.Hidden("auctionId", auction.Id)
<input class="post-bid" type="submit" value="Bid" />
}
</p>
My Ajax script
#section Scripts{
<script type="text/javascript">
$(function () {
$('.post-bid').on("click", function () {
var form = $(this).parent("form");
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize()
})
.success(function (data) {
var template = $('#current-price-template').clone().html();
var html = template
.replace('{{CurrentPrice}}', data.CurrentPrice)
.replace('{{BidCount}}', data.BidCount);
$('.current-price').replaceWith(html);
$('#amount').val(data.Number);
})
.error(function () {
alert("Your big has been rejected");
});
return false;
});
});
</script>
I can't see the content of the template but my guess would be that you are replacing the content to which to click event is attached and so when you replace the dom element you lose the click event binding. This type of binding is called directly bound.
To achieve the type of functionality you want you need to use the delegated style of binding where the click event handler is bound to a parent element or higher and a selector parameter in the binding call identifies which elements to process the click event for. This type of event binding is called delegated. When the content is replaced the handler remains and is available to handle the events from the child elements identified by the selector.
In your case something like.
form.on('click', '.post-bid',eventHandler);
For a more detailed description please the documentation for the jquery .on statement
http://api.jquery.com/on/
I have figured this out - I was returning a string (integer.ToString("C")) in the JSON data which I then placed into my textbox. Upon clicking the submit button, it was trying to parse the currency (now: "£2.99") into an integer (currentAmount is an integer in my bid object), which of course became 0, which resulted in my bid form not being able to serialise this data.

Onclick event using jQuery Autocomplete combined with a handler

I have the following textbox
<asp:TextBox ID="typeSearch" runat="server"/>
Also, I have the following javascript code within my head
<script type="text/javascript">
$(document).ready(function () {
$("#<%=typeSearch.ClientID%>").autocomplete('Handler1.ashx');
});
</script>
In Handler1.ashx, I have the code to retrieve from a database all the related values depending on what the user writes within the TextBox "typeSearch".
What I want to achieve is when the user clicks within the textbox to view all the values. How can I achieve that combined with my handler ?
Hope this code help you!
$("#<%=typeSearch.ClientID%>").keyup(function() {
var textValue = $(this).val();
Search(textValue);
});
function Search(keyword){
//call ajax for result search here
.....
}

How to set Textbox's Text as an querystring argument for LinkButton without having codebhind file?

I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>

How can I change another page's dropdown in aspx?

I had a form which is called contact.aspx and it has a dropdown which includes user list.
I add below line to add user.
New User
and the javascript of insertUser is below:
<script type="text/javascript">
function insertUser() {
var win = window.open('stackoverflow.aspx?t=1', 'User Insert', 'width=800,height=600');
}
</script>
And when I click "New User", stackoverflow.aspx is opened and I want to enter new user data and click save.
After clicking save buton, how can I close stackoverflow.aspx and only refresh dropdown at the contact.aspx?
You can use the following Javascript code to close child window and refresh parent(ref):
window.close();
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
or you can do partial refresh. see here
you must stored variable in session , db or ...
and use this link.
http://forums.asp.net/t/1606853.aspx/1
Don't do this on different page, because you can't update your field from an other page. You can make ajax requests from the contact.aspx by intervals, and you can check the DB if there is a new user, and refresh it. But it's not a nice solution. So I suggest to make this registration (which is on stackoverflow.aspx) on contact.aspx, inside an iframe or just inside a div. You can hide each content in each action (when you are registering, hide the rest of content just display the registration fields, if you are done refresh the dropdownlist reset your registration fields and hide them, display the dropdownlist).With this approach you can refresh your dropdownlist, when you are done with registration.
To refresh dropdownlist make an ajax call, where you can get the new values from the db (there can be multiple new values submitted by different user at the same time) and then you cen refresh dropdown (wich is a select with options in HTML) But if you do this, you can get an eventvalidation error, which is a built in asp.Net feature (defends against xss attack). So the solution can be to make a full postback after registration, and refresh the values by server code, or don't use server control to dropdownlist, only html select, and fill it on document ready, and refresh it async by javascript or jQuery.
mmm, On the stackoverflow.aspx after user clicks save, it posts to the server, creates a new user and get a JSON representation of the object. then register a script to close the window and pass the json to the opener.
private btnSave_Click(object sender, EventArgs args)
{
//Save data
...
string objectJson = GetJSON(); // {"userId": 100, "name": "John Smith"}
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> window.opener.appendObject(" + objectJson + ") </");
cstext1.Append("script>");
cs.RegisterStartupScript(this.GetType(), "RefreshScript", cstext1.ToString());
}
On the contacts.aspx have the following script:
<script type="text/javascript">
function appendObject(json) {
var obj = JSON.parse(json); //convert json to object
//Add item to the drop down list.
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = obj.name;
try
{
// for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
</script>
Didn't test it but I think it works.

How to initialize textbox to hide for first display and still have jquery work

So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command

Categories

Resources