Dynamically adding pattern and title attributes to input control - javascript

I have a HTML input control as follows:
<input type="text" value="<%= this.CustomerAcctNumber %>" name="CustomerAcctNumber" id="CustomerAcctNumber" maxlength="19" onkeyup="CustomerAcctNumberChange()" required >
on body onload I am adding a pattern and title attributes to this input control
var CustomerAcctNumber = document.getElementById("CustomerAcctNumber");
CustomerAcctNumber.setAttribute("pattern","\d{2}-(?:\d{4}-){3}\d{1}");
CustomerAcctNumber.setAttribute("title","xx-xxxx-xxxx-xxxx-x");
When i submit this web page, with valid pattern, it gives me error :
Input control was rendered as expected as follows :
<input type="text" value="" name="CustomerAcctNumber" id="CustomerAcctNumber" maxlength="19" onkeyup="CustomerAcctNumberChange()" pattern="d{2}-(?:d{4}-){3}d{1}" title="xx-xxxx-xxxx-xxxx-x" required="">
Any suggestions or comments will be appreciated!!

I figured out the problem. You are passing the pattern value from JavaScript, so it escapes all your \ symbols which is needed to be generated in HTML. currently you're HTML generates pattern="d{2}-(?:d{4}-){3}d{1}" which is incorrect. So you need to provide another escape character next to each of the existing \ which will result to double \\ so you're HTML generates pattern="\d{2}-(?:\d{4}-){3}\d{1}". So the line in your JS would become as shown below:
CustomerAcctNumber.setAttribute("pattern","\\d{2}-(?:\\d{4}-){3}\\d{1}"); //renders to '\d{2}-(?:\d{4}-){3}\d{1}' in HTML
Rest all are fine. Let me know if this worked.

Related

Form using Javascript exclusively

I have an assigment, I don't understand it as i'm beginner.
Create a javascript script which will modify the DOM of a web-page.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?".
Thank you in advance.
I need to use only Javascript for this and I can only find answers
that use HTML
Web applications use HTML to contain, render and display elements in the viewport (browser window).
Where do you intend to render the form and capture user input?
You can build the DOM structure using JavaScript alone, however, there will still be a HTML file, which will contain the HTML elements created using javascript.
Please provide clarity as to your desired goal and what type of application this is being used for.
My gut feeling, for simplicity, is that you will require to use HTML as your template file, and JavaScript for interactivity and manipulation of the HTML file.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?". That's it.
This is a start, just to try to help you to understand the concepts.
I do, however, implore you to go and explore with confidence - you won't break anything, just give it a try!
I recommend you try taking a look at some of these articles, have a look at my (very rudimentary) code below, and feel free to ask any questions you have!
JS:-
W3 Schools JS and HTML reference
HTML:-
W3 Schools: HTML Forms
W3 Schools: Label Tag
W3 Schools: Text Area Tag (This has been left out of the solution on purpose - give it a try!!)
(function divContent() {
//Create a 'div' as a container for our form
var div = document.createElement('div');
// Perhaps you could style it later using this class??
div.className = 'row';
// I have used backticks to contain some more normal looking HTML for you to review, it's not complete though!!
div.innerHTML = `<form action="javascript:" onsubmit="alert('Your message here, or, run a function from your JavaScript file and do more stuff!!')">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="Mickey Mouse">
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="mickey#mouse.co.uk">
<br><br>
<input type="submit" value="Submit">
</form> `
// Get the body of the document, and append our div containing the form to display it on page
document.getElementsByTagName('body')[0].appendChild(div);
}());
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="CoderYen | Wrangling with 0s & 1s Since The Eighties">
</head>
<body>
</body>
</html>

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)

Regex to strip html tag with certain attribute

I have some invalidly-nested HTML like:
<form class="form1" method="get">
<div>
<input name="field1">
</form>
<form class="form2" method="get">
<input name="field1">
</form>
</div>
Yeah, it's a mess, don't ask. The invalid nesting is causing problems somewhere else. jQuery I think is expecting a closing </div>, and only finding it at the last one. It's then treating the second <form> tag as invalid, and also discarding the closing </form> immediately above it, and assuming everything between lines 1 and 9 are one form.
If I output these to the console:
$('.form1).html() - all of line 1 - 9
$('.form2).html() - undefined
So what I'm trying to do is treat the whole thing as a string, and use regex to strip out form2. I'm expecting a regex something like:
formText.replace(/(<form\b[^>]*>)[^<>]*(<\/form>)/gi, "");
but I'm not sure how to reference the specific form with class=form2.
There's also a problem with it being a multi-line string.
Update: added more detail, outlining why jQuery's remove() method isn't working. jQuery only thinks there's one form unfortunately.
Don't use regex to parse HTML. Since you're using jQuery, just use .remove():
$(function() {
$(".form2").remove();
});
JSFiddle
I ended up using:
formText = formText.replace(/(<form\b[^>]*form2+.*>[\s\S]+<\/form>)/gi, "");
The [\s\S] matches all characters including \n and \r to cover the newlines.
I could probably have made the part of the regex dealing with the class name more specific so I knew it was the class and not some other random form with a similar, but in practice it didn't matter (there was only one instance of the 2nd form, with a very specific class name).

Issue with the single quote with passing a string to the javascript function

I'm using a custom tag to get the title of a field from a template. In this case, there's a field "customerEmailTitle" that has the string "Riot Team's Email". I'm passing it within the javascript function checkEmailAddress (as seen below):
<input onBlur="checkEmailAddress(this, 'The input is an invalid <getName:getField fieldKey="customerEmailTitle"/> address')" />
But the single quote in Riot Team's Email seems to be throwing the page off and won't process the javascript properly. I tried escaping the single quotes and the double quotes in the input tag but nothing seems to be working. Anyone has a better idea as to how to handle this?
It may helpful for you. As you can set the data/string on data attribute of input element.
<html>
<body>
<input data-message="'The input is an invalid <getName:getField fieldKey='customerEmailTitle'/> address')" onblur="checkEmailAddress(this)" type="text" />
</body>
<script>
function checkEmailAddress(elm){
alert(elm.dataset['message']);
}
</script>
</body>
</html>

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