What the difference between 2 name of input ?
OK, Normal i usually use this format name="xxxxxx"
<input type="text" name="xxxxxx"/>
But, today i see name format that i not understand name="xxxxx[]"
<input type="text" name="xxxxxx[]"/>
what is [] in name="xxxxx[]"
With this format xxxxx[] the variable $_POST['xxxxx'] is an Array when form is posted.
For example, is possible to iterate by the $_POST['xxxxx']:
<?php
$data = filter_input(INPUT_POST, 'xxxxx');
if(is_array($data)) {
foreach($data as $value) {
echo $value;
}
}
?>
In HTML5, the name attribute is just a string (without any special syntax). The only thing that can have a special meaning are the _charset_ and isindex strings. Thus square brackets themselves are nothing special.
However, the authors of programming languages or libraries that interact with HTML forms some times decide to define special syntaxes. That's the case of the PHP server-side language, where paired brackets in form element names are used by the language to automatically define variables of array type. See How do I create arrays in a HTML ? for further details.
(It's possible that other langs make use of similar conventions but I don't really know.)
Nothing, it just another name, may be something auto generated or someone use for a purpose in mind.
This is mainly done because of server side frameworks.
With PHP, for instance, if you had
<input type="text" name="address[firstline]">
and
<input type="text" name="address[secondline]">
and submitted the form, in your PHP code on the server you'd retrieve a single address object from the request and it would have the keys firstline and secondline on it.
you can still query using jQuery:
$('input[address\\[\\]=firstline]')
The reason for needing two backslashes is because a single backslash is interpreted as a JavaScript string escape character, so you need two to specify a literal backslash, which provides the escape character to the selector...
Related
I'm sure someone will mark this as a duplicate question but no other answers worked for me.
I am using ruby and passing a variable into my html page. Let's say my variable "camp_name" is equal to "abc'd"
<%=camp_name%>
This outputs "abc'd" which is what I want.
<input type="text" class="form-control" name="campaign_name" required value='<%=camp_name%>'>
The value in the field is now "abc" because of the single apostrophe. How do i get it to ignore apostrophes? Thanks.
You can escape the variable to html entities:
camp_name.gsub("'", "'")
You should do that for other characters as well, because, as mentioned by a comment, the user could simply insert an HTML tag in your page with your current script. Probably the most important ones are the following:
camp_name.gsub("<", "<")
camp_name.gsub(">", ">")
If you're using Rack (which would definitely be in use if you're using Rails or Sinatra, and it might be there even if you're not), there is a builtin for escaping HTML for just this kind of thing. Calling Rack::Utils#escape_html will replace ampersands, brackets, and quotes with their HTML entities (e.g. ' instead of ').
In your case, you'd want the following code:
<input type="text" class="form-control" name="campaign_name" required value='<%= Rack::Utils.escape_html(camp_name) %>'>
This would evaluate to:
<input type="text" class="form-control" name="campaign_name" required value='abc'd'>
which is the proper way of displaying an apostrophe in HTML.
Just as a side note, displaying user-submitted text without escaping on a website is a very bad idea, because malicious users can add arbitrary Javascript that could render your site useless, add advertisements, and more. You should definitely get into the habit of escaping any text that users can submit before displaying it, either by gsubing manually or using a helper method like this.
I am trying to validate a username field. The field must have numbers, letters and no special chars.
This pattern="[A-Za-z0-9]" stands for username with numbers and letters.
What the pattern should be?
Your pattern stands for a single uppercase-char, lowercase-char or number.
The pattern you want looks like this:
/^[a-z\d]+$/i
Explained:
^ - from the start of the string (or line with the m flag)
[ - start character class
a-z - range of characters from a to z
\d - the same as 0-9 (any digit)
] - close character class
+ one or more
$ - end of string (or line with the m flag)
Then we have the flags outside the actual regexp // itself.
We're using the i flag which stands for case insensitive.
Cheatsheets / Tools
http://regexr.com/
http://rubular.com/
try this
<input type="text" class="form-control" name="username" onkeyup="if (/[^|a-z0-9]+/g.test(this.value)) this.value = this.value.replace(/[^|a-z0-9]+/g,'')">
I don't know if this can be done in raw HTML (doubt it), so you'll need some javascript. You can have a function called on the "onchange" attribute if you like, so the element would be like:
<input id="username" type="text" onchange="validate()" name="name" value=""/>
The javascript function would then just access the element, get the value, and check what is in it, like so:
function validate() {
var name = document.getElementById("username").value;
//do checking here however you like (regex, iteration, etc.)
}
BUT, this needs to be done server side. You can do it client-side if you really want to, but it MUST be done on the server side, in any case. I assume you meant on the client side since you tagged the question with HTML, rather than a server side language.
This should work to test a string for only characters and numbers with javascript.
/^[a-zA-Z0-9]+$/
I've always used single quotes when writing my HTML by hand. I work with a lot of rendered HTML which always uses double quotes. This allows me to determine if the HTML was written by hand or generated. Is this a good idea?
What is the difference between the two? I know they both work and are supported by all modern browsers but is there a real difference where one is actually better than the other in different situations?
The w3 org said:
By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39). Single quote marks can be included within the attribute value when the value is delimited by double quote marks, and vice versa. Authors may also use numeric character references to represent double quotes (") and single quotes ('). For double quotes authors can also use the character entity reference ".
So... seems to be no difference. Only depends on your style.
I use " as a top-tier and ' as a second tier, as I imagine most people do. For example
Click Me!
In that example, you must use both, it is unavoidable.
Quoting Conventions for Web Developers
The Short Answer
In HTML the use of single quotes (') and double quotes (") are interchangeable, there is no difference.
But consistency is recommended, therefore we must pick a syntax convention and use it regularly.
The Long Answer
Web Development often consists of many programming languages. HTML, JS, CSS, PHP, ASP, RoR, Python, etc. Because of this we have many syntax conventions for different programming languages. Often habits from one language will follow us to other languages, even if it is not considered "proper" i.e. commenting conventions. Quoting conventions also falls into this category for me.
But I tend to use HTML tightly in conjunction with PHP. And in PHP there is a major difference between single quotes and double quotes. In PHP with double quotes "you can insert variables directly within the text of the string". (scriptingok.com) And when using single quotes "the text appears as it is". (scriptingok.com)
PHP takes longer to process double quoted strings. Since the PHP parser has to read the whole string in advance to detect any variable inside—and concatenate it—it takes longer to process than a single quoted string. (scriptingok.com)
Single quotes are easier on the server. Since PHP does not need to read the whole string in advance, the server can work faster and happier. (scriptingok.com)
Other things to consider
Frequency of double quotes within string. I find that I need to use double quotes (") within my strings more often than I need to use single quotes (') within strings. To reduce the number of character escapes needed I favor single quote delimiters.
It's easier to make a single quote. This is fairly self explanatory but to clarify, why press the SHIFT key more times than you have to.
My Convention
With this understanding of PHP I have set the convention (for myself and the rest of my company) that strings are to be represented as single quotes by default for server optimization. Double quotes are used within the string if a quotes are required such as JavaScript within an attribute, for example:
<button onClick='func("param");'>Press Me</button>
Of course if we are in PHP and want the parser to handle PHP variables within the string we should intentionally use double quotes. $a='Awesome'; $b = "Not $a";
Sources
Single quotes vs Double quotes in PHP. (n.d.). Retrieved November 26, 2014, from http://www.scriptingok.com/tutorial/Single-quotes-vs-double-quotes-in-PHP
If it's all the same, perhaps using single-quotes is better since it doesn't require holding down the shift key. Fewer keystrokes == less chance of repetitive strain injury.
Actually, the best way is the way Google recommends. Double quotes:
https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Quotation_Marks#HTML_Quotation_Marks
See https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Validity#HTML_Validity
Quoted Advice from Google: "Using valid HTML is a measurable baseline quality attribute that contributes to learning about technical requirements and constraints, and that ensures proper HTML usage."
In HTML I don't believe it matters whether you use " or ', but it should be used consistently throughout the document.
My own usage prefers that attributes/html use ", whereas all javascript uses ' instead.
This makes it slightly easier, for me, to read and check. If your use makes more sense for you than mine would, there's no need for change. But, to me, your code would feel messy. It's personal is all.
Using double quotes for HTML
i.e.
<div class="colorFont"></div>
Using single quotes for JavaScript
i.e.
$('#container').addClass('colorFont');
$('<div class="colorFont2></div>');
I know LOTS of people wouldn't agree, but this is what I do and I really enjoy such a coding style: I actually don't use any quote in HTML unless it is absolutely necessary.
Example:
<form method=post action=#>
<fieldset>
<legend>Register here: </legend>
<label for=account>Account: </label>
<input id=account type=text name=account required><br>
<label for=password>Password: </label>
<input id=password type=password name=password required><br>
...
Double quotes are used only when there are spaces in the attribute values or whatever:
<form class="val1 val2 val3" method=post action=#>
...
</form>
I had an issue with Bootstrap where I had to use double quotes as single quotes didn't work.
class='row-fluid' made the last <span> fall below the other <span>s, rather than sitting nicely beside them on the far right. class="row-fluid" worked.
It makes no difference to the html but if you are generating html dynamically with another programming language then one way may be easier than another.
For example in Java the double quote is used to indicate the start and end of a String, so if you want to include a doublequote within the String you have to escape it with a backslash.
String s = "a Link"
You don't have such a problem with the single quote, therefore use of the single quote makes for more readable code in Java.
String s = "<a href='link'>a Link</a>"
Especially if you have to write html elements with many attributes.(Note I usually use a library such as jhtml to write html in Java, but not always practical to do so)
if you are writing asp.net then occasionally you have to use double quotes in Eval statements and single quotes for delimiting the values - this is mainly so that the C# inline code knows its using a string in the eval container rather than a character. Personally I'd only use one or the other as a standard and not mix them, it looks messy thats all.
Using " instead of ' when:
<input value="user"/> //Standard html
<input value="user's choice"/> //Need to use single quote
<input onclick="alert('hi')"/> //When giving string as parameter for javascript function
Using ' instead of " when:
<input value='"User"'/> //Need to use double quote
var html = "<input name='username'/>" //When assigning html content to a javascript variable
I'm newbie here but I use single quote mark only when I use double quote mark inside the first one. If I'm not clear I show You example:
<p align="center" title='One quote mark at the beginning so now I can
"cite".'> ... </p>
I hope I helped.
Lots of great insightful replies here! More than enough for anyone to make a clear and personal decision.
I would simply like to point out one thing that's always mattered to me.
And take this with a grain of salt!
Double quotes apply to strings that have more than a single phase such as "one two" rather than single quotes for 'one' or 'two'. This can be traced as far back as C and C++.
(reference here or do your own online search).
And that's truly the difference.
With this principle (this different), parsing became possible such as "{{'a','b'},{'x','y'}} or "/[^\r\n]*[\r\n]" (which needed to be space independent because it's expressional) or more famously for HTML specific title = "Hello HTML!" or style = "font-family:arial; color:#FF0000;"
The funny thing here is that HTML (coming from XML itself) commonly adopted double quotes due to expressional features even if it is a single character (e.g. number) or single phase string.
As NibblyPig pointed out quite well and straightforward:
" as a top-tier and ' as a second tier since "'a string here'" is valid and expected by W3 standards (which is for the web) and will most likely never change.
And for consistency, double quotes is wisely used, but only fully correct by preference.
In PHP using double quotes causes a slight decrease in performance because variable names are evaluated, so in practice, I always use single quotes when writing code:
echo "This will print you the value of $this_variable!";
echo 'This will literally say $this_variable with no evaluation.';
So you can write this instead;
echo 'This will show ' . $this_variable . '!';
I believe Javascript functions similarly, so a very tiny improvement in performance, if that matters to you.
Additionally, if you look all the way down to HTML spec 2.0, all the tags listed here;
W3 HTML DTD Reference
(Use doublequotes.) Consistency is important no matter which you tend to use more often.
Double quotes are used for strings (i.e., "this is a string") and single quotes are used for a character (i.e., 'a', 'b' or 'c'). Depending on the programming language and context, you can get away with using double quotes for a character but not single quotes for a string.
HTML doesn't care about which one you use. However, if you're writing HTML inside a PHP script, you should stick with double quotes as you will need to escape them (i.e., \"whatever\") to avoid confusing yourself and PHP.
I frequently see, in particular in the PHP world, the following writing if you want to create a FORM array.
<input name="MyArray[]" />
<input name="MyArray[]" />
with the square brackets []. Nevertheless, the submit operation just passes the same key entry twice. It appears that the [] is just conventional that maps nicely to the PHP world array, but you would obtain the same result with just the following
<input name="MyArray" />
<input name="MyArray" />
Indeed, in django I get a list of two entries, regardless of the style used.
Is this true ? Are the [] just conventional, or there's actually a real meaning into it from the HTML and HTTP key/value info ?
They address a limitation of PHP, which doesn't generate an array automatically if multiple values with the same name are submitted, for example from a set of checkboxes or a multiple select. (IIRC it only returns the last value.)
Personally I've always thought it to be a pretty shoddy workaround. Even Classic ASP could cope with that without requiring client-side additions to markup. The server-side platform has no business imposing markup requirements on the client in this way.
It's just conventional.
The W3C states:
Let the form data set be a list of name-value-type tuples
and for each input element, on submit:
Append an entry to the form data set with name as the name, the value of the field element as the value, and type as the type.
The W3C does not mention the use of [] or uniqueness of the name attribute.
I need to post multi-line data via a hidden field. The data will be viewed in a textarea after post. How can I post a newline/carriage return in the html form?
I've tried \r\n but that just posts the actual "\r\n" data
<input type="hidden" name="multiline_data" value="line one\r\nline two" />
Is there a way to do this?
Instead of using
<input type="hidden">
Try using
<textarea style="visibility:hidden;position:absolute;">
While new lines (Carriage Return & Line Feed) are technically allowed in <input>'s hidden state, they should be escaped for compatibility with older browsers. You can do this by replacing all Carriage Returns (\u000D or \r) and all Line Feeds (\u000A or \n) with proprietary strings that are recognized by your application to be a Carriage Return or New Line (and also escaped, if present in the original string).
Simply character entities don't work here, due to non-conforming browsers possibly knowing
and
are new lines and stripping them from the value.
Example
For example, in PHP, if you were to echo the passed value to a textarea, you would include the newlines (and unescaped string).
<textarea>Some text with a \ included
and a new line with \r\n as submitted value</textarea>
However, in PHP, if you were to echo the value to the value attribute of an <input> tag, you would escape the new lines with your proprietary strings (e.g. \r and \n), and escape any instances of your proprietary strings in the submitted value.
<input type="hidden" value="Some text with a \\ included\r\nand a new line\\r\\n as submitted value">
Then, before using the value elsewhere (inserting into a database, emailing, etc), be sure to unescape the submitted value, if necessary.
Reassurance
As further reassurance, I asked the WHATWG, and Ian Hickson, editor of the HTML spec currently, replied:
bfrohs Question about <input type=hidden> -- Are Line Feeds and Carriage Returns allowed in the value? They are specifically disallowed in Text state and Search state, but no mention is made for Hidden state. And, if not, is there an acceptable HTML solution for storing form data from a textarea?
Hixie yes, they are allowed // iirc // for legacy reasons you may wish to escape them though as some browsers normalise them away // i forget if we fixed that or not // in the spec
Source
Depends on the character set really but
should be linefeed and
should be carriage return. You should be able to use those in the value attribute.
You don't say what this is for or what technology you're using, but you need to be aware that you can't trust the hidden field to remain with value="line one
line two", because a hostile user can tamper with it before it gets sent back in the POST. Since you're putting the value in a <textarea> later, you will definitely be subject to, for example, cross site scripting attacks unless you verify and/or sanitize your "multiline_data" field contents before you write it back out.
When writing a value into a hidden field and reading it back, it's usually better to just keep it on the server, as an attribute of the session, or pageflow, or whatever your environment provides to do this kind of thing.