I am trying to limit the decimal places of the value outputted - tofixed

What I have at the moment is a script that out puts a value after adding together different input fields.
<script type="text/javascript">
$(function() {
$("#addAll").click(function() {
var add = 0;
$(".amt").each(function() {
add += Number($(this).val());
});
$("#para").html("$<input size="18" name="salestax" class="amt" readonly type="text" value=" + add + " />");
});
});
</script>
I am trying to limit the decimal place of this output to only 2 decimal places.
What do I need to add? I assume its the toFixed() but I have tried that in numerous places. Where should it be placed?

You should always avoid reducing the precision of your floating point values until as late as possible. In your case, you want to apply toFixed() in the line that constructs the display HTML. Also, you are missing quote marks around the value attribute. Your code should look something like this:
$("#para").html("$<input size="18" name="salestax" class="amt" readonly type="text" value="" + add.toFixed(2) + "" />");
I'm not sure that " is really necessary, I think you could just use apostrophes instead (').

Related

Is there a way to stop manual input in a type=number but still allow changes with the "up/down" buttons?

I have an input:
<input type="number" name="amount" min="4" max="6" step="2" value="4" id="amount" />
And I don't have a normal submit button to submit the info (uses javascript).
type=number works fine, but users can still type in any number they want, I would like to stop users from being able to type in the input, but still allow for changes using the "up/down" arrows that appear with type=number. I have tried researching but cannot find anything. Is this even possible?
Is there any reason you are avoiding using a drop down select tag?
This will give the user a very limited choice of numbers (set to your preference).
You could even populate the <option> fields with numbers 1 through 100 (or whatever you choose) using PHP or JavaScript so you didn't have to manually type each number in the HTML code.
<select>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
Edited to block copy/paste:
<script type="text/javascript">
document.getElementById('amount').onkeypress = function(e) { e.preventDefault(); };
document.getElementById('amount').onkeydown = function(e) {
if(e.keyCode != 38 && e.keyCode != 40)
e.preventDefault();
};
if(document.addEventListener)
document.getElementById('amount').addEventListener('contextmenu',function(e) { e.preventDefault();
},false);
</script>
http://jsfiddle.net/Wh5Ms/2/
Then you could add a <noscript> tag for users with JavaScript turned off and show them a <select> element, etc.
The user is expected to be able to type in the field, as one option. Although it is possible to prevent this in part (namely when JavaScript is enabled and event handlers in your code cover the ways that the user might use), there is no point in using the element when you specifically do not want to get its basic functionality.
If you only want to allow the two values 4 and 6, as it seems from your example, and you want to prevent the user from simply typing one of them, then you should use a select element or a set of two radio buttons.
Although I am not sure as to what the step attribute does but pretty sure that you can find a way to use it as per your requirements in below code
The Code below makes sure that the allowed values are between min and max attribute specified only
The Code is using jquery 1.10 onwards.
var prevVal = 0;
$("input[type=number]").on("keydown", function(e){
prevVal = Number($(this).val());
});
$("input[type=number]").on("keyup", function(e){
var minVal = $(this).attr("min");
var maxVal = $(this).attr("max");
var step= $(this).attr("step");
var currentVal = $(this).val();
if(!(currentVal<=maxVal&&currentVal>=minVal)){
$(this).val(prevVal)
}
});
Try it dude, my problem was solved
var prevVal = 0;
$("input[type=number]").on("keydown", function(e){
prevVal = Number($(this).val());
});
$("input[type=number]").on("keyup", function(e){
var minVal = $(this).attr("min");
var maxVal = $(this).attr("max");
var step= $(this).attr("step");
var currentVal = $(this).val();
if(!(currentVal>=1)){
$(this).val(1)
}
});

ASP.NET MVC3 Obtaining Auto-generated Form Element Id's

Using #Html.TextBoxFor(m => m.MyField) will (normally?) result in <input id="MyField" name="MyField" type="text" value="" /> and if I want to access that element in jquery I do so as follows $("#MyField"). Is there a way to avoid manually typing the ID into the jquery selector? It seems clunky to me to do it this way as I'm coming from a classic asp.net background where you would pull the id of the element using the ClientID property. Therefore if the renderer changed how it generated the ID ones code automatically kept up-to-date. In the above example if I change MyField to MyNewField the compiler will remind me to change all the strongly typed references, but nothing will remind me to change my jquery selector.
Write a simple method that get a property and return it's name with reflection and use it like this:
static string GetVariableName<T>(Expression<Func<T>> expression)
{
var body = expression.Body as MemberExpression;
return body.Member.Name;
}
$('#' + #(GetVariableName(() => Model.MyField)))
Should work.

Way to update css properties on-the-fly based on form content?

I have a form on a website, in which one of the inputs is to be used to enter hexadecimal colour codes to be entered into a database.
Is there any way for the page to dynamically update itself so that if the user changes the value from "000000" to "ffffff", the "colour" CSS property of the input box will change immediately, without a page reload?
Not without Javascript.
With Javascript, however...
<input type='text' name='color' id='color'>
And then:
var color = document.getElementById('color');
color.onchange = function() {
color.style.color = '#' + this.value;
}
If you are going to go the Javascript route, though, you might as well go all out and give them a color picker. There are plenty of good ones.
CSS properties have corresponding entries in the HTML DOM, which can be modified through Javascript.
This list is somewhat out of date, but it gives you some common CSS pieces and their corresponding DOM property names.
Granted, a JS lib like like jQuery makes this easier...
You can use Javascript to achieve that.
As an example:
Your HTML:
<input type="text" id="test" />
Your JS:
var test = document.getElementById('test');
test.onchange = function(){
test.style.color = this.value;
};
But this doesn't check the user's input (So you would have to extend it).

Getting a substring of text containing HTML tags

Getting a substring of text containing HTML tags
Assume that you want the first 10 characters of the following:
"<p>this is paragraph 1</p>this is paragraph 2</p>"
The output would be:
"<p>this is"
The returned text contains an unclosed P tag. If this is rendered to a page, subsequent content will be affected by the open P tag. Ideally, the preferred output would close any unclosed HTML tags in reverse of when they were opened:
"<p>this is</p>"
I want a function that returns a subtring of HTML, making sure that no tags are left unclosed
You need to teach your code how to understand that your string is actually HTML or XML. Just treating it like a string won't allow you to work with it the way you want to. This means first transforming it to the correct format and then working with that format.
Use an XSL stylesheet
If your HTML is well-formed XML, load it into an XMLDocument and run it through an XSL stylesheet that does something like the following:
<xsl:template match="p">
<xsl:value-of select="substring(text(), 0, 10)" />
</xsl:template>
Use an HTML parser
If it's not well-formed XML (as in your example, where you have a sudden </p> in the middle), you'll need to use a HTML parser of some kind, such as HTML Agility Pack (see this question about C# HTML parsers).
Don't use regular expressions, since HTML is too complex to parse using regex.
You can use the next static function. For a working example check: http://www.koodr.com/item/438c2e9c-62a8-45fc-9ca2-db1479f412e1 . You can also turn this into a extensionmethod.
public static string HtmlSubstring (string html, int maxlength) {
//initialize regular expressions
string htmltag = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>";
string emptytags = "<(\\w+)((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?></\\1>";
//match all html start and end tags, otherwise get each character one by one..
var expression = new Regex(string.Format("({0})|(.?)", htmltag));
MatchCollection matches = expression.Matches(html);
int i = 0;
StringBuilder content = new StringBuilder();
foreach (Match match in matches)
{
if (match.Value.Length == 1
&& i < maxlength)
{
content.Append(match.Value);
i++;
}
//the match contains a tag
else if (match.Value.Length > 1)
content.Append(match.Value);
}
return Regex.Replace(content.ToString(), emptytags, string.Empty); }
Your requirement is very unclear so most of this is guesswork. Also, you have provided no code which would help to clarify what it is you want to do.
One solution could be:
a. Find the text between the <p> and the </p> tags. You can use the following Regex for this or use a simple string search:
\<p\>(.*?)\</p\>
b. In the found text, apply a Substring() to extract the required text.
c. Put back the extracted text between the <p> and the </p> tags.
You could loop over the html string to detect the angle brackets and build up an array of tags and whether there was a matching closing tag for each one. The problem is, HTML allows for non closing tags, such as img, br, meta - so you'd need to know about those. You would also need to have rules to check the order of closing, because just matching an open with a close doesn't make valid HTML - if you open a div, then a p and then close the div and then close the p, that isn't valid.
try this code (python 3.x):
notags=('img','br','hr')
def substring2(html,size):
if len(html) <= size:
return html
result,tag,count='','',0
tags=[]
for c in html:
result += c
if c == '<':
intag=True
elif c=='>':
intag=False
tag=tag.split()[0]
if tag[0] == '/':
tag = tag.replace('/','')
if tag not in notags:
tags.pop()
else:
if tag[-1] != '/' and tag not in notags:
tags.append(tag)
tag=''
else:
if intag:
tag += c
else:
count+=1
if count>=size: break
while len(tags)>0:
result += '</{0}>'.format(tags.pop())
return result
s='<div class="main">html <code>substring</code> function written by <span>imxylz</span>, using python language</div>'
print(s)
for size in (30,40,55):
print(substring2(s,size))
output
<div class="main">html <code>substring</code> function written by <span>imxylz</span>, using python language</div>
<div class="main">html <code>substring</code> function writte</div>
<div class="main">html <code>substring</code> function written by <span>imxyl</span></div>
<div class="main">html <code>substring</code> function written by <span>imxylz</span>, using python</div>
more
See code at github.
Another question.

Passing hidden field from one page to another in querystring

I want to pass a query in a hidden filed from 1 page to another by querystring.
Can anyone help me out with the logic?
It's worth taking the time to learn jQuery. It's not very complicated, and it makes writing javascript much easier. There are also many jQuery plugins, such as jquery.url.
Also, as other posters have suggested, you may not wish to put the hidden field's value in the query string if you care about it being displayed to the user. However, if the data is present in a hidden field it will always be possible for a user to find it if they care to look.
If you really do want to put the hidden field in the query string and then extract it via non-jQuery javascript:
hiddenFieldPage.aspx
This form will take the user to processingPage.aspx?datum=someValue when it is submitted. You could probably also just use an ordinary link if nothing else needs to be submitted at the same time.
<form method="GET" action="processingPage.aspx">
<input type="hidden" name="datum" value="someValue">
<input type="submit">
</form>
or, inserting the value from code-behind:
RegisterHiddenField("datum", "someValue");
processingPage.aspx
This script will pop-up an alert box with the value of "datum" from the URL - assuming the form's method is set to "GET":
<script type="text/javascript">
function getUrlParam( key ) {
// Get the query and split it into its constituent params
var query = window.location.search.substring(1);
var params = query.split('&');
// Loop through the params till we find the one we want
for( var i in params ) {
var keyValue = params[i].split('=');
if( key == keyValue[0] ) {
return keyValue[1];
}
}
// Didn't find it, so return null
return null;
}
alert( getUrlParam("datum") );
</script>
If the form's method was set to "POST" (as it usually would be in ASP.NET), then "datum" won't be in the query string and you'll have to place it on the page again:
RegisterHiddenField( "datum", Request.Form["datum"] );
To retrieve the hidden value on the second page:
var datum = document.Form1.item("datum").value;
alert( datum );
You can easily submit a form on one page that points to another page using the action parameter. For instance, inside of page1.aspx put the following:
<form action="page2.aspx" method="GET">
<input type="hidden" name="username" value="joenobody" />
<input type="submit" />
</form>
Since you're using "GET" as the method instead of "POST", you could potentially use Javascript to parse the URL and get the value that was passed. Alternatively, you could use ASPX to store the value of the "username" field somewhere else on the page. I don't know ASPX (or ASP, or anything Microsoft really), but if you can find a way to output something like the following (and are using jQuery), it may do what you require. Honestly though, it sounds like you are going about something all wrong. Can you modify your question to be a bit more specific about what the general object is that you are attempting to accomplish?
<div id="some_div"><%= Request.form("username") %></div>
<script type='text/javascript'>
var value_needed = $('#some_div').html();
</script>
<form method="get">
Assuming you mean hidden in the HTML form sense, your field will be submitted along with all the other fields when the form is submitted. If you are submitting via GET, then your "hidden" field will show up in plain text in the URL. If you don't want the data in the hidden field to be accessible to users, don't put an understandable value in that field.
If you are using aspx, you do not need to parse the query string using JavaScript, or even use <form method="GET" ...>. You can POST the form to the second aspx page, extract the value in C# or VB then write it to a client-side JavaScript variable. Something like this:
page1.aspx:
<form method="POST" action="page2.aspx">
<input type="hidden" name="myHiddenServerField" value="myHiddenServerValue">
<input type="submit">
</form>
page2.aspx:
<script type="text/javascript">
var myHiddenClientValue = '<%= Request.Form['myHiddenServerField']; %>';
</script>
The above would set the client-side JavaScript variable called myHiddenClientValue to a value of 'myHiddenServerValue' after the POST.
This can be a bad idea because if myHiddenServerField contains single quotes or a newline character, then setting it on the client in page2.aspx can fail. Embedding ASP.NET Server Variables in Client JavaScript and Embedding ASP.NET Server Variables in Client JavaScript, Part 2 deals with specifically these issues, and solves them with a server-side class that ensures values being written to the client are escaped correctly.
If you use method="get" on an HTML form then any hidden inputs in that form will be converted to query parameters.
See also Jeremy Stein's answer.

Resources