function duplicateWithLines()
{
var datefield = jQuery("#lineItemDate").val();
if ( !( datefield && datefield.match( /^\d{1,2}[/]\d{1,2}[/]\d{4}$/ ) ) ) alert("Date is required");
else {
//DO blah blah
}
}
---
---
<input type='button' class='duplicate_button' name='duplicateWithLines' value='Duplicate Line Items:' onClick='duplicateWithLines()'/>
<hsi:calendar name="lineItemDate" size='10' maxlength='10' />
At Line var datefield = jQuery("#lineItemDate").val(); value is coming as undefined I think. Because of that it failing to enter else block.if condition is satisfying so alert msg printed. But it has to enter else block.
And there date format would be entered as dd/mm/yyyy.
What is the way to get in to else block.
Addressing the val()-problem: you are trying to find an element with id lineItemDate. But your element has no id. It does have a name, so $('[name=lineItemDate]').val() should work.
If the formatting is fixed (dd/mm/yyyy), try modifiyng the if part this way to avoid the ugly and expensive matching:
var dateFromValue = new Date(
$('[name=lineItemDate]').val().split('/').reverse().join('-')
);
if (!isnNaN(dateFromValue)) {
/* it's a date! */
} else {
/* don't bother */
}
While we're at it, don't use inline handlers. Every activation of an inline handler spawns a new javascript interpreter. In your scripting use:
$('[name=duplicateWithLines]').on('click', duplicateWithLines);
It may be wise to rename your function, to avoid name clashes.
jQuery doesn't know how to retrieve the value from the hsi:calendar element. You need to find the html element that contains the data value in order to use jquery to fetch it.
Related
I have a form which contains an input field and a submit button. The whole program depends on the submission of the form to continue. Each function can only perform one task as follows:
Get input value
Output the value
allEvents();
//output(name)
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
<form id="formOne">
<input type="text" id="name" required>
<input type="submit" id = "inputText">
</form>
How do I access the value of name after the form has submitted in the main program, so that I can pass it to function output().
Note: Function inputText() can only return the input name.
You stated that you want each function to do different things. This is a good idea, but then take a look at this function:
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
Is this getting the input value only? Nope, it is preventing the default behavior of e as well. But you will want to get the input value later as well. This is not only getting the value, but setting it as well. Now, first things first, let's define a prototype for this purpose.
function InputOutput() {
var inputs = {}; //This will contain key-value pairs.
this.setInputValue = function(name, val) {
inputs[name] = val;
};
this.getInputValue(name) {
return inputs[name];
}
this.getNames() {
var result = [];
for (var key in inputs) result.push(key);
return result;
}
}
Now, lets instantiate this and use it:
//output(name)
function allEvents(){
document.getElementById('formOne').addEventListener('submit',function(e) {
e.preventDefault(); //Are you sure you do not want to execute the submit?
let tag = document.getElementById('inputText');
let name = tag.name;
let value = tag.value;
inputOutput.setInputValue(name, value);
});
}
var inputOutput = new InputOutput();
allEvents();
and later you can get the names by using getNames, like this:
function output(name) {
consolge.log(inputOutput.getInputValue(name));
}
and calling it like this:
output(inputOutput.getNames()[0]);
EDIT
Of course you can avoid the usage of global variables, by wrapping a lot of things into a function which will be the value of onload of your body tag, but that's a different question.
Because getInputValue() returns the name, you can pass it directly to output(name) .
allEvents();
function allEvents(){
document.getElementById('formOne').addEventListener('submit',output(getInputValue))
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
You would have to declare the variable name outside of the function scope.
let name
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function getInputValue(e){
e.preventDefault()
name = document.getElementById('inputText').value;
return name;
}
function output(n){
console.log(n)
}
output(name)
However, why not just call your output function from within your getInputValue value?
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
function output(n){
console.log(n)
}
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
output(name)
return name;
}
Jiminy Cricket. Reading through all of this "stuff", I couldn't decide which was more messed-up. The question, or the answers !
Looking at the Question:
function allEvents(){
document.getElementById('formOne').addEventListener('submit',getInputValue)
}
Why would anyone be adding an Event Listener to formOne ? What does the form have to do with anything ? It's useless.
And continuing with the Question,
function getInputValue(e){
e.preventDefault()
let name = document.getElementById('inputText').value;
return name;
}
Why would anyone be getting an Element by ID of inputText ? Seriously. What does that have to do with anything ? That is essentially the "Submit" button. You aren't going to find anyone's name in the interior of a button.
And then there was the Note that he added underneath his question ... Sorry, but there is no Function called inputText().
And now for the first Answer ( the one that has 2 up-votes ); Is that supposed to be JavaScript ? I typed it in, and it doesn't run. It basically has an error on every line.
And for the second answer ( with one up-vote ), I typed that one in too. It doesn't run either.
I hope the original poster is willing to make a modification to his HTML. Because I tried running his code in Internet Explorer and Chrome, and they don't treat his HTML structure the same, because his "Submit" button does not include the value attribute. So each Browser has to take a guess about what value to insert.
So if he will scrap his "pseudo-Submit" button, and replace it with a real Submit button :
<button type="submit" id="inputText">Submit</button>
And also, allow me to add an HTML paragraph tag to print the results in, because I think console.log ought to be banned.
<p id="outputIDname" ></p>
Then here is some code that actually runs. ( And I have also included the console.log statements for the people who need it. )
allEvents( ) ;
// output(name)
function allEvents( ) {
document.querySelector( "#inputText" ).addEventListener( "click", output ) ;
}
function output( e ) {
e.preventDefault() ;
let tempName = getInputValue( ) ;
console.log( "name Inside of Output Function = " + tempName ) ;
document.querySelector( "#outputIDname" ).innerHTML = tempName ;
}
function getInputValue( ) {
let name = document.getElementById( 'name' ).value ;
console.log( "name Inside of Input Function = " + name ) ;
return name ;
}
Here is the modified HTML :
<form id="formOne">
<input type="text" id="name" required>
<button type="submit" id="inputText">Submit</button>
</form>
<p id="outputIDname" ></p>
Here is the output:
// name Inside of Input Function = John
// name Inside of Output Function = John
// And the here is the output that is printed inside of the
// Paragraph Tag that I added to his HTML structure:
// John
And if you want to see just how much the Browsers hated his "Submit" button, just try replacing my "Submit" button with the one that he had. The Java Script will no longer work.
And one final note: Internet Explorer is so dumb, that ( if you replace my "Submit" button with the one that he had ), Internet Explorer doesn't even realize that the Java Script is not working. If you look in console.log, you will see that Internet Explorer just happily prints out 'John' and 'John', as if there is nothing wrong. But the Paragraph Tag ( that I added to the page ) remains empty. Just one of many reasons to ban console.log
this is my .js function
function validateSNo(inputtxt,elem){
var SNoFormat = /^\d{6}$/;
if (SNoFormat.test(inputtxt)){
document.getElementById(elem).innerHTML = "";
return true;
}
else {
document.getElementById(elem).innerHTML = "This should only contain 6 numbers XXXXXX";
return false;
}
this is the html code
<label>Student No.</label>
<input type="text" name="sNo" size="6" maxlength="6" onblur="return validateSNo(document.FormStuReg.sNo.value,sNo-validation)" autofocus><span class="errorMsg">*</span>
<br>
<span class="errorMsg" id="sNo-validation"></span>
i want to display the validation message in the span area when an invalid input is detected.this code doesn't work..It works fine without the parameters when the function is written like this.
function validateSNo(){
var SNoFormat = /^\d{6}$/;
if (SNoFormat.test(document.FormStuReg.sNo.value)){
document.getElementById("sNo-validation").innerHTML = "";
return true;
}
else {
document.getElementById("sNo-validation").innerHTML = "This should only contain 6 numbers XXXXXX";
return false;
}
}
I have to use the same validation in few other places so its better if i can pass the values as parameters to single function or else i have to write the same function over n over again with different element id's.
Look at the onblur attribute in your HTML.
onblur="return validateSNo(document.FormStuReg.sNo.value,sNo-validation)"
Notice that sNo-validation is not in quotation marks. That means that it's interpreted as two variables: sNo and validation, which are undefined, and the - is interpreted as a minus sign. Subtracting two undefined variables doesn't make sense, so that's why you get an error.
Just add quotation marks. Since it's already inside quotation marks because it's an HTML attribute, use single quotes.
onblur="return validateSNo(document.FormStuReg.sNo.value, 'sNo-validation')"
BTW, since you are using a scheme like sNo and sNo-validation then you don't need to pass the ID. I'll guess that document.FormStuReg.sNo.value is the input that the listener is on, so you can just pass a reference to the element using this:
<input ... name="sNo" ... onblur="return validateSNo(this)" ... >
And then in the function:
// element will reference the input
function validateSNo(element){
var SNoFormat = /^\d{6}$/;
if (SNoFormat.test(element.value)){
// Use the element name to get the message element
document.getElementById(element.name + "-validation").innerHTML = "";
return true;
}
else {
document.getElementById(element.name + "-validation").innerHTML = "This should only contain 6 numbers XXXXXX";
return false;
}
}
and the if..else can use the conditional ? : operator:
document.getElementById(element.name + "-validation").innerHTML = SNoFormat.test(element.value)? '' : 'This should only contain 6 numbers XXXXXX';
Returning true or false from the listener has no effect whatever.
If you take this one step further, you can define the validation to run in a class value or data- attribute, then you don't need to pass anything. Just validate all form controls based on their class or data- values.
Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});
so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.
I'm dealing with some legacy HTML/JavaScript. Some of which I have control over, some of which is generated from a place over which I have no control.
There is a dynamically generated form with hidden fields. The form itself is generated via a Velocity template (Percussion Rhythmyx CMS) and JavaScript inserts additional hidden form fields. The end result is hidden form fields generated with the same 'name' attribute. The data is being POSTed to Java/JSP server-side code about which I know very little.
I know that form fields sharing the same 'name' attribute is valid. For some reason the POSTed data is not being recognized the back end. When I examine the POST string, the same-name-keys all contain no data.
If I manipulate the code in my dev environment such that only a single input field exists for a given name, the data IS POSTed to the back end correctly. The problem is not consistent, sometimes, it works just fine.
Is there something I can do to guarantee that the data will be POSTed? Can anyone think of a reason why it would not be?
I should really update my answer and post code here, because POST requests without
variable strings indicates the problem is on the client side.
How about this:
<script type="text/JavaScript">
function disableBlankValues()
{
var elements = document.getElementById("form1").elements;
for (var i = 0; i < elements.length; i++)
{
if (elements[i].value == "")
elements[i].disabled = true;
}
}
</script>
<form action="page.php" method="POST" onsubmit="disableBlankValues()" id="form1">
<input type="hidden" name="field1" value="This is field 1."/>
<input type="hidden" name="field1" value=""/>
</form>
EDIT
I now realize the actual problem (multiple variables with the same name should be passed to JSP as an array) and my solution is probably not what the OP is looking for, but I'm leaving it here just in case it happens to help someone else who stumbles upon this post.
you could use something like:
var form = document.getElementById('yourformid');
var elements = form.getElementsByName('repeatedName');
var count = 0;
for(var item in elements){
elements[item].name += count++;
}
this way you will get each hiddenfield with the names:
name0
name1
name2
...
I've worked out a brute-force solution. Note that I'm pretty aware this is a hack. But I'm stuck in the position of having to work around other code that I have no control over.
Basically, I've created an ONSUBMIT handler which examines the form for the repeated hidden fields and makes sure they are all populated with the correct data. This seems to guarantee that the POST string contains data regardless of how the form gets rendered and the Java back end appears to be happy with it as well.
I've tested this in the following situations:
Code generates single instances of the hidden fields (which does happen sometimes)
Code generates multiple instances of the hidden fields
Code generates no instances of the hidden fields (which should never happen, but hey...)
My 'else' condition contains a tiny bit of MooTools magic, but it's otherwise straight-forward stuff.
Maybe someone else will find this useful one day...
Thanks for the help!
<form method="post" name="loginform" id="loginform" action="/login" onsubmit="buildDeviceFP(this);">
<script type="text/javascript">
function insertFieldValues( fields, sValue )
{
if ( 'length' in fields )
{
// We got a collection of form fields
for ( var x = 0; x < fields.length; x++ ) {
fields[x].value = sValue;
}
}
else
{
// We got a single form field
fields.value = sValue;
}
}
function buildDeviceFP( oForm )
{
// Get the element collections for Device Fingerprint & Language input fields from the form.
var devicePrintElmts = oForm.elements.deviceprint;
var languageElmts = oForm.elements.language;
// 'devicePrintElmts' & 'languageElmts' *should* always exist. But just in case they don't...
if ( devicePrintElmts) {
insertFieldValues( devicePrintElmts, getFingerprint() );
} else if ( oForm.deviceprint ) {
oForm.deviceprint.value = getFingerprint();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'deviceprint', 'value':getFingerprint()} )
);
}
if ( languageElmts) {
insertFieldValues( languageElmts, getLanguage() );
} else if ( oForm.language ) {
oForm.language.value = getLanguage();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'language', 'value':getLanguage()} )
);
}
}
</script>