I have the following text inside a form on a jsp page:
<td id="seltb71b" style="display: none">
<input type="text" id="tb73Parametro" name="tb73Parametro" value="${varTb73Parametro}" />
</td>
Now, this text doesen't always appear on the page, it appears only when a select is selected. On java side, i have the class Form with all validators and one of them is raised when the text is empty.
#UseValidators({
#UseValidator(value = StringLength.class, args = { "1", "50" }, error = "tb71Validator")
#UseValidator(value = NotNull.class, error = "tb71Validator")
})
public String tb71;
The question is: how can i call the form error validator using javascript? (client side).
I can't add the error validator on java (server side) because if the text doesen't appear the error is however called and this is no good.
The validator must rise only when the text appears AND is empty.
Related
Hello after searching and trying a lot , i am not able to find the issue so that I am seeking your help to solve my issue.
Here I have a form while clicking on submit button it should call the javascript function and should not redirect or refresh the page .
Here I want to send mail using SMTPJS with attachments by filling the form and choosing the image once the form submitted it should call the sendEmail() function and mail should be send, but when i click on the submit button it's refreshing the page and it's not working accordingly.
<form onsubmit="sendEmail(); reset(); return false">
<div class="col-md-12">
<div class="form-floating">
<input type="file" class="form-control" id="fileupload" required>
<label for="phone">Upload file</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary w-100 py-3" type="submit" style="background-color: #0e2e50;">Upload</button>
</div>
</div>
</form>
<script>
function sendEmail() {
var file = event.srcElement.files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function () {
var dataUri = "data:" + file.type + ";base64," + btoa(reader.result);
Email.send({
Host: "smtp.elasticemail.com",
SecureToken :"************"
To: 'mail#mail.com',
From: "mail#mail.com",
Subject: "Form Enquiry",
Body : "Sending file:" + file.name,
Attachments : [
{
name : file.name,
data : dataUri
}]
}).then(
message => alert(message)
);
};
}
</script>
I think the issue is in this line 'var file = event.srcElement.files[0];' because from this line it's refreshing the page and a Question mark (?) is coming in the URL. ex.page.html?
One more thing if i am calling the sendEmail() function in the onchange event of the input type file then it's working fine, why so?
You have two problems.
Typo
The first is a typo and is highlighted by the browser telling you:
Uncaught SyntaxError: missing } after property list note: { opened at line 24, column 19
This exception is preventing the function from being created, so the onsubmit function errors when it calls it, and you never reach the return false that prevents the form submission.
Read the error messages in the console in the browser developer tools.
You are missing a comma between SecureToken :"************" and To: 'mail#mail.com'.
Forms don't have files
You said:
var file = event.srcElement.files[0];
Which gets the element that triggered the event (since it is a submit event, that is the <form>) and you try to read the files property from it.
The browser tells you this:
Uncaught TypeError: event.srcElement.files is undefined
Read the error messages in the console in the browser developer tools.
The files property can be found on <input type="file">, not on the <form>.
You need to find the correct element:
var file = event.srcElement.querySelector('[type="file"]').files[0];
Asides
To generally make life easier and avoid these sorts of issues:
Use a linter, like ESLint, and an editor that can use it as a plug in
Use a code formatter to indent code and help locate syntax errors
Don't use intrinsic event attributes (like onsubmit); do use addEventListener
Pay attention to what your debugging tools are telling you
Just change it a little bit:
<form onSubmit="sendEmail(event)">
...
</form>
function sendEmail(event) {
event.preventDefault();
...
}
So basically I have problem uploading some photo using Selenium Python
input element seems to be hidden in the page so the .sendkeys method at still I run into some errors.
this is html code of the input element
<div data-react-class="ImageUploadForm" data-react-props="{}" data-react-cache-id="ImageUploadForm-0">
<input class="hidden" type="file" accept="image/jpeg, image/jpg, image/png, image/gif">
<button class="btn btn-lemonfrog text-lg" type="button">Upload photo</button>
</div>
base_path = Path(file).parent
filepath = (basepath / "../core/attachments/clientstackphoto.jpeg").resolve()
hiddenuploaderinput.sendkeys(filepath)
right now after running above code I'm getting type error :
value = (PosixPath('........./core/attachments/clientstackphoto.jpeg'),)
def keys_to_typing(value):
"""Processes the values that will be typed in the element."""
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = str(val)
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
E TypeError: object of type 'PosixPath' has no len()
../../venv/lib/python3.7/site-packages/selenium/webdriver/common/utils.py:150: TypeError
I expect to upload photo successfully, maybe some js injection will help ?
Based on your error message, I'm not entirely convinced the error message is caused by the hidden file input. If it were, I would expect an ElementNotVisibleException.
However, I do see that the input is hidden, so we should run some JS to reveal the input and perhaps we can rule that out as a potential issue.
Code to show image input
fileInput = driver.find_element_by_xpath("//input[#type='file']")
# display file input so we can send keys
driver.execute_script("arguments[0].style.display = 'block';", fileInput)
Alternatively, you may need to execute script on the class attribute instead:
driver.execute_script("arguments[0].setAttribute('class', 'visible')", fileInput)
Once you execute JS to make the file input visible, you can just send_keys to it like any other input:
fileInput.send_keys("PATH/TO/FILE/HERE")
I have a popup modal that displays on page load that has the following form in it:
<form class="enterForm">
<label class="modalFields" id="userName" style="display: none;">
<span>user Number :</span>
<input type="text" name="userNum" placeholder="User Number" required/>
</label>
</form>
<label>
<span> </span>
<input type="submit" value="Submit" class="submitButton">
<input type="hidden" id="hiddenInput">
</label>
And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like:
{
"results":[
{
"person":{
"firstName":"John",
"lastName":"Smith"
},
"userNumber":"12345"
}
]
}
If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. How could I go about achieving this?
Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution).
Solution
JavaScript
//On form submit
$('#enterForm').submit(function(){
var userNum = $('[name="userNum"]').val();
//AJAX call to your API
$.ajax({
url: 'myAPICall.php',
/* data: {userNumber: userNum}, //If necessary */
success: function(data) {
// Note: this code is only executed when the AJAX call is successful.
if(data.results.userNumber == userNum){
$('#navBarFirstName').text(data.results.person.firstName);
}
},
error: function (err) {
//If the AJAX call fails, this will be executed.
console.error(err);
}
dataType: 'JSON'
});
return false; //Prevents the page refresh if an action is already set on the form.
});
Explanation
You use jQuery to bind a function (event listener) to the submit event of your form.
When the submit event is triggered, the function runs:
It gets the value of your DOMElement with the name attribute "userNum"
It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not)
On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response.
Including jQuery
You can integrate jQuery by including the script within your HTML page. You can either download it or use a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>
<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
/* Your actual script */
</script>
Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work.
I'm beginner in HTML and I wanted to know, how I can make a paragraph in the HTML-Body equal to a text that the user has written into a textbox in the HTML-Body using a JavaScript function. Are there any ways to do that? And another question: What is happening, when the user clicks on a "Submit" button? Does HTML write all the input of the user into variables?
(EDIT) So, here's my code (HTML):
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<div class="input-text">
<input type="user-answer" id="uA1">
<p id="paragraph"></p>
<input type="button" onClick="inp.input();" value="Write Text">
</div>
</body>
</html>
JavaScript:
var inp = document.getElementById('uA1');
var p = document.getElementById('paragraph');
inp.addEventListener('input', function() {
p.textContent = inp.value;
});
It still doesn't work.
When clicking 'submit' button browser serialise content of the containing that button form to url-encoded string (name1=value1&name2=value2&etc=etc) and perform the http request described in the form tag (action and method attributes). It will not create any variables or save its. All values already saved in properties of form elements (nodes of DOM tree).
To sync your input with paragraph you have to add event listener to that input that will listen if user insert any text there and then use inputs value as text content of the paragraph.
var inp = document.getElementById('myArea');
var p = document.getElementById('myP');
inp.addEventListener('input', function(){
p.textContent = inp.value;
});
See it on jsFiddle.
You can see that in this example I used the property value of the textarea DOM node (selected by it's id). That's the place where the data of the form is stored but until you click 'submit' button.
For the question about what happens when user click on "submit" button, generaly all the information included in your input are stored in php variable. I don't think you want to work with php, but this is as easy as it :
<form method = "post" action = "next.php">
<div>
<input id = "id" name = "id" placeholder = "your id here..." />
<input id = "pass" name = "pass" placeholder = "your pass here..." />
</div>
<div>
<input id = "btn_valid" value = "Valid information" />
</div>
</form>
In this example, I made a short form, with two input to let user type his id and his password. If you specified the "name" tag (like I did in the two input "id" and "pass"), you will be able to get them in your php "next.php" file like this (in another page, in this case in the page "next.php") :
<?php
$id = $_POST['id'];
$pass = $_POST['pass'];
?>
Because you specified to go to "next.php" in the form parameters, you will be able to get these data by calling "$_POST['name-of-the-input']". And it works for all kind of element which can have a "name" tag !
Last information, a php file can contains html, javascript, or php code ! But you need to execute it via a server (like Xampp).
I have a text field, I need to send these text value to the same page which is in jsp .
I just want to assign javascript value to jsp variable.
You can't. JSP runs on the server, Javascript runs on the client, so when Javascript runs the JSP variable doesnt exist anymore.
Consider using AJAX.
You could set a hidden field.
Put this in your JSP form:
<input type="hidden" id="foo" name="foo" />
Execute this script whenever you want to fill the field:
document.getElementById("foo").value = "some value";
When you submit the form, it'll be available as follows in the servlet:
String foo = request.getParameter("foo"); // "some value"
// ...
See also:
Communication between Java/JSP/JSF and JavaScript