Repeated values VS document.querySelector - javascript

On the same page, I'm using Play repeated values and a document.querySelector.
To give a minimal example:
#helper.form(action = routes.MyController.myAction()) {
<input type="search" id="input[0]" />
<input type="search" id="input[1]" />
<input type="search" id="input[2]" />
}
<script language="JavaScript">
var input = document.querySelector('#input[1]');
something(input);
</script>
The issue is that Play uses that format input[i] to map repeated fields but the JavaScript engine does not accept it:
SyntaxError: An invalid or illegal string was specified
Is there a simple workaround on one side or the other?

In a CSS selector, square brackets are used to select an attribute. If you want to match it literally, you have to escape them.
var input = document.querySelector('#input\\[1\\]');
You could also use getElementById, which doesn't parse the ID.
var input = document.getElementById('input[1]');

Related

querySelectorAll doesn't select select boxes with name

I have a form that has multiple select boxes and inputs with a array like name.
So I have multiple select boxes with a name personroom[]. I would like to get these using this
var personroom=document.querySelectorAll("input[name='personsroom[]']");
alert(personroom.length)
it gives me null ("0"). But with the same way I can select all input (text) fields. Strange. Can anyone help me?
The issue seemed to have been related to the exact target of the selector.
the original selector "input[name='personsroom[]']" didn't work but according to OP comments dropping the input worked "[name='personsroom[]']"
A note on escaping [] characters. In this specific case, that was not the issue as the query string used inline single quotes ► "[name='personsroom[]']"
Using this "input[name=personsroom[]]" , with no single quotes, you need to escape the [] like this "input[name=personsroom\\[\\]]"
// The below will fail with "Uncaught SyntaxError..." during execution
//var personroom = document.querySelectorAll("[name=personsroom[]]");
//The below works as we are escaping the special characters
var personroom = document.querySelectorAll("[name=personsroom\\[\\]]");
console.log("1.) personroom.length", personroom.length);
//Also, when using inline quotes, you do not need to escape any characters
var personroom = document.querySelectorAll("[name='personsroom[]']");
console.log("2.) personroom.length", personroom.length);
<input type='textbox' name='personsroom[]' />
<input type='textbox' name='personsroom[]' />
<input type='textbox' name='personsroom[]' />
<input type='textbox' name='personsroom[]' />
If you are using select boxes, then you are using <select></select>, correct? Change input to select in your query:
var personroom=document.querySelectorAll("select[name='personsroom[]']");
alert(personroom.length)

HTML5 + JavaScript, type of input

When I declare JS.
var test = $("#test").val();
Then the "number validaion" is not working on the browser side.
<input type="number" id="test" name="test" required>
Is there any chance to declare $("#test") and use HTML5 in input validation as well (such as required, number validation etc.)? Or I have to to do it on JS side.
It have to be declared to use it later in my AJAX post scipt.
Thanks :)
Use parseInt("stringOfNumber") to get integer from string. When inputting data, you write strings, not numbers.
This is how you use the input type number in HTML5:
<input type="number" name="cost">
Here is a working example of the http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_number.
If you want to add validation try this:
<input type="number" pattern="[0-9]*" name="cost">
Here is a working example of the pattern attribute http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_pattern
Note: Both the input type number and the pattern attribute have limited browser support.
You can check if it's Not a Number, and then invert it.
if(!isNaN(test))
{
// Is a number
}
If you use jQuery, you could use
if($.isNumeric(test))
{
// Is a number
}
Don't rely on Client Side validation though, as it can be easily avoided and some browsers don't support it. E.g: JavaScript validation can be avoided by disabling JavaScript.

Even the most basic Javascript is failing on me - but WHY?

I'm struggling with some very basic Javascript here (not a big fan or expert in Javascript at all!), and I just cannot wrap my head around why this fails....
I have some very basic HTML markup:
Value 1: <input type="text" id="int1" /> <br />
Value 2: <input type="text" id="int2" /> <br /><br />
<input type="button" name="add" value="Add" onclick="add();" />
and then some Javascript:
<script type="text/javascript">
onerror = unhandled;
function unhandled(msg, url, line) {
alert('There was an unhandled exception');
}
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
From my (Pascal- and C#-based) understanding, the add method should read out the values from the input elements with ID's int1 and int2 and add those values and then show the result.
Seems basic and harmless enough......
But even if I do enter two valid integers (like 10 and 20) into those two textboxes, I keep getting an There was an unhandled exception and I just cannot understand what is going wrong here.
Can someone enlighten me??
$.val() returns a string value. you need to convert both returned strings to numbers and then add the values.
try this
function add() {
alert(parseFloat($('#int1').val()) + parseFloat($('#int2').val()));`
}
You have a few different issues going on here.
Firstly, if you're using jQuery, it would be best to use a click event instead of an inline function call.
Second, the values are returned as strings from the inputs, so you must convert them by using parseInt()
Also, your error handler is useless if you're not alerting the error message, the msg argument in this case.
onerror = unhandled;
function unhandled(msg, url, line) {
alert(msg);
}
$("input[name=add]").click(function() {
var int1 = parseInt($("#int1").val());
var int2 = parseInt($("#int2").val());
alert(int1 + int2);
});
Fiddle: http://jsfiddle.net/9bepJ/
Well firstly, .val() will return a string. The addition operator won't add the numeric values of those strings, it will just concatenate the strings.
But that's not causing your exception. Get rid of the everything but the add function. It should work then.
<script type="text/javascript">
function add() {
alert($("#int1").val() + $("#int2").val());
}
</script>
This is, of course, assuming you included the jQuery library since that's where the $() function comes from.
Try using binding onclick event instead writing it inline.
I have made fiddle for you. Check it out
UPDATE:
http://jsfiddle.net/rkhadse_realeflow_com/FhL9g/7/
<script>
function add() {
var int1 = parseInt(document.getElementById("int1").value);
var int2 = parseInt(document.getElementById("int2").value);
alert(int1 + int2);
}
</script>
Value 1:
<input type="text" id="int1" />
<br />Value 2:
<input type="text" id="int2" />
<br />
<br />
<button onclick="add()">Add</button>
As it looks like you're using $(..) functions, be sure you're including jQuery on the page, before you use those functions.
Aside from that, I always have scope issues when I put my event handlers in HTML attributes. Try putting them in your code, which has the added benefit of being unobtrusive JavaScript (a new pattern for cleaner, more maintainable code).
Also, add an id to your button:
<input type="button" name="add" value="Add" id="myButton" />
Add event handler in code and remove onclick attribute from your button
document.getElementById('myButton').onclick = add;

Get textbox value in Javascript (single/multiple fields)

I have a field in my page named as "myField"
Now this is dynamic So there are 2 cases i.e. it can be just 1 field as;
<input type="text" name="myField" />
OR there can be 2 fields as below;
<input type="text" name="myField" />
<input type="hidden" name="myField" />
I use the following code to access the value in JS;
document.forms[0].myField[0].value
However, this does not work if there is only 1 field (as in the first case)
How do I write dynamic JS code to handle the same?
It should be cross browser compatible.
Yes, because in the first case you should use document.forms[0].myField.value.
I'd suggest to retrieve elements with getElementsByName() method:
var val = document.getElementsByName("myField")[0].value;
better way is to give a unique ID to each element and then get it with
document.getElementById(id).value
Have a look at JQuery, and here's some information on how to get the value out.
provided there is at least one element name "myField"
var count = document.forms[0].myField.length;
for(var i=0; i < count; i++){
// do something with document.forms[0].myField[i].value
console.log(document.forms[0].myField[i].value);
}
fiddle : http://jsfiddle.net/HtrrT/

Javascript Array in Class = How to make it valid

I am using this jQuery validation library on my website. It requires me to put the validation rules in the class part of the input tag. ie <input class="validate[required,custom[onlyLetter],length[0,100]]" name="firstname" type="text" />
Now this causes me to end up with code in mine that looks similar such as:
<input type="text"
id="charfname"
name="charfname"
value=""
style="width: 300px;"
class="validate[required,length[3,20],custom[noSpecialCaracters]]" />
Which as you see has a [ and ] in the class name. So when I run the page through a validator I get the error:
character "[" is not allowed in the value of attribute "class"
How do I fix this to make it valid but still have the library work?
Thanks
Use some other method for initialization or use another script? Use an alternate attribute and a custom DTD for example. Or throw away the attribute based init system and use something else. Either way you have to modify the plugin's code. You cannot use "[" and "]" characters in a class name and any other combination implying them, period.

Categories

Resources