I have a form which has fields pre-filled with a default value, like this:
<input type=text name=first value="First Name" class="unfilled" />
When the textbox is clicked, the class unfilled is removed from the textbox, and the textbox is made blank so the user can type in his/her own info.
The problem is that when the form is submitted, its getting submitted with these default values, which is messing up the server side validation. How can I do it so that when the form is submitted, all the fields which have a default value are made blank, so the server side validation would throw the error: 'Please fill in this field'?
I'm trying the following code which isn't working:
$("#myForm").submit(function()
{
$(".unfilled").val('');
}
);
This does make the fields blank, but the server still receives them with their previous default values.
I think you simply have a syntax error. You're missing the closing parenthesis on your submit method.
I just whipped this up and it works fine
<!DOCTYPE html>
<html>
<body>
<?php
var_dump($_POST);
?>
<form action="test.php" method="post">
<input type="text" name="first" value="First Name" class="unfilled">
<input type="submit">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('form').submit(function() {
$('.unfilled').val('');
});
});
</script>
</body>
</html>
You need to stop the form execution first, change the values, and then manually submit the form.
$("#myForm").submit(function(e)
{
// Stop the form submit
e.preventDefault();
$(".unfilled").val('');
$(this).submit();
}
You have to return true; if you want the form to submit, or false, if you don't.
The problem with this approach is that the fields will 'blink' before posting the values, thus creating a bit of unprofessional feel.
It is better to use hidden values and set them in submit() event.
I think you need the .click() function of JQuery.
Example:
$(function () { // shorthand for document.ready
$('.unfilled').click(function () {
$(this)
.val('')
.removeClass('unfilled');
})
});
UPDATE
Sorry, i missunderstand you, thought you need a feature like a placeholder.
Of couse you can do it with return false;, but this cancel the submitting. Or like GreenWebDev says to use e.preventDefault();.
Related
Require attribute on the input field doesn't work when i implement google recaptcha. When the input is empty, the form is supposed not to be submitted. But the form gets submitted when input is empty. I followed google's guide to implement that in its simplest form.
<?php if (isset($_POST['code']) && ($_POST['code'] == "whatever")) //do stuff?> ?>
What i want to do is to make the recaptcha execute only when the input is not empty, else prevent form submit and recaptcha execution.
<form id="form1" method="post" >
<input name="code" type="text" required>
<button data-sitekey="xxx"
data-callback='onSubmit' type="submit" class="g-recaptcha" >Let me in</button>
</form>
</div>
<script>
function onSubmit(token) {
document.getElementById("form1").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Looking over the documentation you linked to, you are probably better off getting rid of the required attribute and adding a check to your script to not submit the form if the I put field is null.
So JavaScript would be checking if the field is empty and then give a validation alert or however works best for your situation.
The reason it submits is your JavaScript function is calling submit directly, which is bypassing the HTML5-only validation. The submit button being a type of 'submit' will do the submission for you automatically so you don't need it.
I'm using the jquery.form.js from here: http://www.malsup.com/jquery/form/. I want to validate the text of the text input from the form before submitting. Validation goes to
'search_validate.php'. This part works fine. If validation passes, the form action's is changed. That works too.
Getting the form to submit normally after changing the action attribute doesn't work. The browser never goes to the '/videos/search/' page. It stays on the same page. I see the '/videos/search/' page loading in Firebug over and over though.
<form id="search" method="post" action="">
<input type="text" id="query" />
<input type="image" id="searchmag" src="blah.jpg" ?>
</form>
<script>
$(function(){
$('#searchmag').click(function(){
$('#search').attr('action','/search_validate.php');
$('#search').ajaxForm(function(data, textStatus){
if ((data.indexOf('letters & numbers only')>-1)) {
$('#query').css('color','#FF0000').val(data);
$("#query").unbind("click").click(function(){
$('#query').css('color','#848484').val('');
});
} else {
$('#search').attr('action','/videos/search/' + $('#query').val());
$('#search').submit();
}
});
});
});
</script>
This always works for me:
$("#myForm").on("submit", function(event) {
event.preventDefault();
// Validate form, returning on failure.
$(this).off("submit");
this.submit();
});
I hope this helps!
I'm having a strange behaviour with this code:
<script type="text/javascript">
function get()
{
alert("gggg");
jQuery.get (
"http://localhost:8080/c/portal/json_service",
{
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : document.getElementById("nombre")
}
);
}
</script>
<div>
<form>
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="button" value="Submit" onClick="javascript:get()"/>
</form>
</div>
Liferay portal gets blocked when the button "Submit" is pressed. The pop-up with the message "gggg" is showed, but after click ok on it, the page becomes blocked.
If I remove the line 'param : document.getElementById("nombre")', it doesn't block.
Can anyone explain me where is the error, or the reason of this behaviour?
Thanks in advance,
Rafa
The problem is that you're trying to pass an entire DOM element as the value for param, which jQuery isn't going to like. What type of element has ID nombre, and what property from that element do you want? If it's some kind of input, you likely want the value property, so you'd do:
param : document.getElementById("nombre").value
Updated Answer:
Thinking this through a little more, you should probably do this in a different way altogether. You're sending the data when the user clicks on the submit button, but remember if a user hits enter while typing in the input text box the form will submit but your code will not catch that.
A more robust solution would be to do it this way instead:
<div>
<form id="nombre_search">
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="submit" value="Submit"/>
</form>
</div>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#nombre_search").submit(function(){
$.get("http://localhost:8080/c/portal/json_service", {
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : $("#nombre").val()
});
return false;
});
});
</script>
Changes to your code:
Added an id to the form.
Made the submit button a submit button instead of just a button.
Placed code inside $(document).ready block.
Code runs when form is submitted not when button is clicked.
Hope this helps,
Sandro
I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows
<form>
<input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">
function validateAndSubmit(){
//do some validation and then submit
}
</script>
In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?
use this syntax:
<form onsubmit="return validateAndSubmit()">
...
if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13
Try this method:
<form onsubmit="return validateAndSubmit(this);">
<input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">
function validateAndSubmit(form_obj){
if(some_variable == 'correct_value') {
form_obj.submit();
return true;
} else {
alert('Wrong value');
return false;
}
//do some validation and then submit
}
</script>
I'm not sure if there's a standard regarding this or not.
Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit action on the form, rather than an onclick action for the button. I almost never use buttons in forms; having to do so for yours would only throw me off, and that's not good for users.
So anyway. Form onsubmit is the way to go. And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :)
Probably something stupid I'm doing. I want to populate a hidden DIV with values of a form on submit.
The DIV does open with correct data, but then resets after the page is finished loading. What am I doing wrong?
Here's my test:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content=
"text/html; charset=us-ascii" />
<title>Test</title>
<script type="text/javascript">
function test(){
var usr = document.getElementById('user').value;
var pwd = document.getElementById('passwd').value;
document.getElementById('out').innerHTML = usr + " " + pwd;
document.getElementById('out').style.display = "block";
return true;
}
</script>
</head>
<body>
<form action="" onsubmit="return test()">
<input type="text" id="user" name="user" />
<input id="passwd" type="text" name="passwd" />
<p><input type="submit" value="Go" /></p>
</form>
<div id="out" style="display:none;">
</div>
</body>
Short answer:
Change this
return true;
to this
return false;
Long answer:
Forms are designed to load a new page when they are submitted. However, with scripting we can prevent this behavior by stopping the submit event. This can be achieved in many ways, but for your example, simply returning "false" from your handler will cancel the event, but only if the onsubmit attribute also has a return statement (which you already had).
The onsubmit function is submitting the form back to the page. You need to cancel the event to prevent it from submitting the data and reloading the page. The easy way to do this is to have your test() function return false. If you still want the form to submit and display the data in a div you'll want to submit the form via AJAX or in an iFrame.
Try replacing "return true;" at the end of your function with "return false;". My reasoning is, because you have the action attribute specified but value, it may think that the current page is the value and since you're not cancelling the event the page reloads.
You need to return false
You see, the return value of onsubmit is used to decide whether to continue to submit the form. So if it's true, the page will reload and the values will be lost. If its false, it won't!
This line is probably your problem:
<form action="" onsubmit="return test()">
The blank action attribute causes the page to bounce to itself (reload) when the form is submitted. You can prevent this by making sure test() returns false rather than true, which will keep the form from submitting at all.
When you post the form, the data will be lost. You could stop the form from posting by setting return true to return false, or you could add some logic to print out the user and passwd fields in the DIV id="out" and set the display to block if user and passwd fields have a value.
As an alternativ you can use a link which do the job without submittig the form.
Do
Your problem is on the line
you should fill the action with the name of the page or with php code to directing to the page itself:
i have tested.