I tried pass the content of an entire div in form action url using JS. but on servlet side when i try to get this request param as String, i am getting it as [object Object].
This is my form and JS
<div id="paraContent">
Content in jsp
</div>
<form id="form1" action="/sendEmail.email.send.html" method="post">
<input type="hidden" id="contentValue1" name="contentValue1"/>
<input type="button" value="place order" onClick="formSubmit()"/>
</form>
<script type="text/javascript">
var divContent = $('#paraContent');
$("#contentValue").val(divContent);
function formSubmit() {
var form = document.getElementById("form1");
var str = "/sendEmail.email.send.html?contentValue=" + $('#paraContent');
form.action = "/sendEmail.email.send.html?contentValue=" + $('#paraContent');
form.submit();
}
</script>
You could copy the div's content into a div when the form is subbmitted.
<form id = "form1" action="/sendEmail.email.send.html" method="post">
<input type="hidden" id="contentValue1" name="contentValue1"/>
<c:Set var="contVal" value="ddd"/>
<input type="button" value="place order" onClick="formSubmit()"/>
</form>
<script type="text/javascript">
function formSubmit() {
$("#contentValue1").val($("#paraContent").text());
var form = document.getElementById("form1");
var str = "/sendEmail.email.send.html?contentValue=" + $(paraContent);
form.action = "/sendEmail.email.send.html?contentValue=" + $(paraContent);
form.submit();
}
</script>
try by changing the
$(paraContent) to $("#paraContent"); and also
$("contentValue").val(divContent); to $("#contentValue").val(divContent);
Well you can use ajax post in order to send data from div to your servlet
<div id="paraContent">
Content in jsp
</div>
<script>
$(document).ready(function (){
var data=$("#paraContent").text();
$.ajax({
url: "YOUR SERVLET",
type: "POST",
data: { "data": data},
success: function(data) {
console.log(data);
}
});
});
</script>
In your servlet
String datafromdiv=request.getParameter("data");
Try this instead on a button click function .....
Related
Hi everyone
So there is my code :
HTML :
<html>
<body>
<form enctype="multipart/form-data" method="post" name="image">
<input onchange="test();" type="file" accept="image/*" capture="camera" name="file" id="camera">
<input id="go" type="submit" value="Stash the file!" style="display: none;" />
</form>
<div id="output"></div>
</body>
<script src="./script.js"></script>
</html>
JS :
var form = document.forms.namedItem("image");
form.addEventListener('submit', function(ev) {
var
oOutput = document.getElementById("output"),
oData = new FormData(document.forms.namedItem("image"));
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "./upload.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
function test() {
document.getElementById("go").click()
}
My problem is it's totaly functional but litlle... dirty.
I try to submit the form with JS document.forms.namedItem("image").submit(); but the EventListener dont catch it.
And i dont want to add JQuery to my project just for that (for those who have an answer who use JQuery).
The solution is certainly right before my eyes but i dont find an other way to do it.
Thanks all in advance.
I think you can simplify like this :
function pleaseUpload() {
console.log('upload fonction ...');
}
<html>
<body>
<form enctype="multipart/form-data" method="post" name="image">
<input onchange="pleaseUpload();" type="file" accept="image/*" capture="camera" name="file" id="camera">
</form>
<div id="output"></div>
</body>
<script src="./temp.js"></script>
</html>
Your confusing form.submit() with submit button click.
There is no need for a hidden submit button.
var output = document.getElementById("output");
var form = document.querySelector("form[name='image']");
form.addEventListener('submit', function(ev) {
ev.preventDefault();
var oOutput = document.getElementById("output")
var oData = new FormData(document.forms.namedItem("image"));
oData.append("CustomField", "This is some extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "./upload.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
}
};
oReq.send(oData);
}, false);
function test() {
form.submit();
output.textContent = "form submitted!";
}
<form enctype="multipart/form-data" method="post" name="image">
<input onchange="test();" type="file" accept="image/*" capture="camera" name="file" id="camera">
</form>
<div id="output"></div>
I have a Login form that working fine. I tried to extend login action for adding extra features.
First I prevent the form to be submit when the submit button is clicked, I perform ajax request and finally if everything is correct I submit the form, but my form is not submitted until the submit button is clicked twice. What am I doing wrong?
HTML Part:
<div id="loginFormDiv">
<form class="form-horizontal" method="POST" action="index.php">
<input type="hidden" name="module" value="Users">
<input type="hidden" name="action" value="Login">
<div class="group"><input id="username" type="text" name="username" ><span class="bar"></span><label>Username</label></div>
<div class="group"><input id="password" type="password" name="password" ><span class="bar"></span><label>Password</label></div>
<div class="group"><button type="submit" class="button buttonBlue">Sign in</button></div>
</form>
</div>
JS Part:
jQuery.Class("ParsSecureLogin_Js", {}, {
checkLogin: function () {
var thisInstance = this;
var checkUserLogin = function (e) {
e.preventDefault();
var username = $('#username').val();
var user_pass = $('#password').val();
var theForm = $(this);
var url = 'index.php?module=ParsSecureLogin&parent=Settings&action=CheckLogin&_user=' + username + '&_pss=' + user_pass;
jQuery.ajax({
url: url
}).done(function (data) {
if (data == '' || data == 'undefined') {
alert('Unknown error. Please contact admin to check!');
return false;
} else {
theForm.unbind('submit').submit();
return true;
}
});
}
jQuery('#loginFormDiv').on("submit", checkUserLogin);
},
registerEvents: function () {
var thisInstance = this;
thisInstance.checkLogin();
}
});
jQuery(document).ready(function () {
var ParsSecureLogin = new ParsSecureLogin_Js();
ParsSecureLogin.registerEvents();
});
It is because #loginFormDiv is a <div> not a <form> change the selector to:
jQuery('#loginFormDiv form').on("submit", checkUserLogin);
I want to have a form that asks the user their name, then welcomes them to the website with that name without redirecting to a different page or reloading. So basically replace a form with "Welcome NAME" after submit is clicked.
My code:
<div id="welcomeText">
<form onsubmit="changeText()" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById(welcomeForm).fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
You need to give a name to the form before trying to access it, something like this:
//create the name attribute for the form
<form onsubmit="changeText()" method="post" name="myForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<script>
function changeText() {
//access myForm using document object
var name = document.name.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<div id="welcomeText">
<form onsubmit="changeText()" method="post" id="welcomeForm">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
function changeText() {
var name = document.getElementById("welcomeForm").fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="welcomeText">
Name: <input type="text" name="fname" id="name">
<input id="submit" type="submit" onclick="changeText()" onsubmit="changeText()">
</div>
<script>
function changeText() {
var name = document.getElementById("name").value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
document.getElementById("name").style.display = "none";
document.getElementById("submit").style.display = "none";
}
</script>
</body>
</html>
Try this it will display "welcome user" and also make button and input disappear. In this case you don't even need a form. You can access the name directly from the input without ever submitting the form.
Here we are:
<div id="welcomeText">
<form id="myform" method="post">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</div>
<script>
var form = document.getElementById("myform");
form.addEventListener('submit', function (e) {
e.preventDefault(); // This will prevent submitting the form
var name = form.fname.value;
var welcome = "Welcome, " + name;
document.getElementById("welcomeText").innerHTML = welcome;
});
</script>
I can't execute this jquery function properly. When I click on submit's form, only shows the two first alerts and then the page reloads. So I click again on the form's submit with the page reloaded and then shows the rest of the alerts (beginning by the third one) and then the function works fine.
In conclusion: I need to click on the form's submit two times instead of one to execute the function.
Any idea? Thank you.
JS Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
alert("enters script");
$(function () {
alert("enters jquery function");
$(".submit").click(function () {
alert("enters click submit function");
var name = $("#name").val();
var date = $("#date").val();
var dataString = 'name=' + name + '&date=' + date;
alert("saved variables");
if (name == '' || date == '') {
alert("enters if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
alert("enters else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function () {
alert("enters success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresh();
}
});
}
return false;
});
});
</script>
HTML Code:
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
use the event.preventdefault to stop the submission of the page
http://api.jquery.com/event.preventdefault/
Your problem is using submit buttons, they have some default behaviors other than what you add as a event to it.
replaced this:
<input type="submit" value="Submit" class="submit" />
with:
<input type="button" value="Submit" class="submit" />
this you working DEMO
other than changing the submit button to a regular button, you can fix your code by disabling that default behaviors, adding onsubmit to your form node:
<form method="post" name="form" onsubmit="return false;">
<!--your stuff-->
</form>
Try this:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function(){
alert("entra en la funcion del clic del submit");
var nombre = $("#nombre").val();
var fecha = $("#fecha").val();
var dataString = 'nombre='+ nombre + '&fecha=' + fecha;
alert("variables guardadas");
if(nombre=='' || fecha=='')
{
alert("entra en el if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
alert("entra en el else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
alert("entra en el success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresca();
}
});
}
return false;
});
});
First of all, thank you to everybody for your help.
Finally the main problem comes from other part of the code. I was using pjax (https://github.com/thybag/PJAX-Standalone) to replace the form with other html document (in this case page1.html) after doing the mysql insert through "join.php". And I'm not calling the jquery function properly.
Explanation: You begin in page1.html, then click on "Go To Page 2" (This replace the div "content" with the body of page2.html). Then complete the form and submit it. When you click on submit, activates the jquery function (join.php mysql insert inside) and finally replace again the div "content".
Solution (this works):
page1.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pjax-standalone.js"></script>
<script type="text/javascript">
pjax.connect({
'container': 'content',
'beforeSend': function(){console.log("before send");},
'complete': function(){console.log("done!");
if($("#button_pg_2").length)
{
$( document ).ready(function()
{
$(".submit").click(function()
{
var nombre = $("#name").val();
var fecha = $("#date").val();
var dataString = 'name='+ name + '&date=' + date;
if(name=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax(
{
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
replace();
}
});
}
return false;
});
});
}
}
});
</script>
<script type="text/javascript">
function replace()
{
pjax.invoke('page1.html', 'content');
}
</script>
</head>
<body>
<div id="header">
This div never changes
</div>
<div id="content">
Go To Page 2
</div>
</body>
</html>
page2.html
<html>
<body>
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="button" id="button_pg_2" value="submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
</body>
</html>
I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>