script that checks text field do not work with chrome - javascript

I have a form and java script that checks if text filed was not empty. problem is, code works with IE and Firefox but do not work with chrome.
<form action="editor.php?id=<?=$id_book?>" method="post" name="form1" onsubmit="return check_form(this)" >
<script language="javascript">
function check()
{
if ((document.all.title.value==""))
{
alert("Отсутствует название книги!");
}
if ((document.all.price.value==""))
{
alert("Отсутствует цена книги!");
}
if ((document.all.descrip.value==""))
{
alert("Отсутствует описание книги!");
}
else
{
document.all.form1.submit();
}
}
</script>
<div class="list-group">
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Название:</div></span>
<input type="text" name="title" class="form-control" value="<?=$value['title']?>">
</div><br />
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Цена:</div></span>
<input type="text" name="price" class="form-control" value="<?=$value['price']?>">
</div><br />
<div class="input-group input-group-lg">
<span class="input-group-addon"><div class="inp_width">Описание</div></span>
<textarea type="text" name="descrip" class="myform-control" rows="5"><?=$value['descrip']?></textarea>
</div><br />
<?php endforeach; ?>
<div class="col-md-12">
<div class="col-md-2"><button type="button" value="Submit" class="btn btn-primary" onclick="check()">Редактировать</button>
</form>
</div>
any ideas? More problem is that if I have just one filed check in chrome, scripts works fine. Submit button do not work only if I need to check several fields.
UPDATE: sorry guys... everything works fine... copy-paste will kill me... type button should be "Submit" instead of "button"... next time I'll should be more careful coping code:)

Your IF statements look incorrect. Only the last IF statement will stop the submit from happening, as that is the only call that the "else" step is associated with. For javascript please try the following format:
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}
additionally, if you want to check multiple values and if any of the values don't exist you should try some sort of flag. Example:
If (document.all.title.value==""){
message += "Title is missing";
}
If (document.all.price.value==""){
message += "Price is missing";
}
If (message == ""){
document.all.form1.submit();
}else{
alert(message)
}

Markup errors aside (see my comment), document.all is IE/MSHTML-proprietary and now deprecated (for some reason Mozilla adopted it a few years ago). Your code should look as follows when standards-compliant:
<form … onsubmit="return check_form(this)">
<script type="text/javascript">
function check_form (form)
{
var elements = form.elements;
if (elements["title"].value == "")
{
window.alert("Отсутствует название книги!");
return false;
}
if (elements["price"].value == "")
{
window.alert("Отсутствует цена книги!");
return false;
}
if (elements["descrip"].value == "")
{
window.alert("Отсутствует описание книги!");
return false;
}
}
</script>
…
<button type="submit" value="Submit" class="btn btn-primary">Редактировать</button>
</form>
Note that the function returns false if there is an error, preventing the form from being submitted because the return value is returned to the onsubmit event handler (which I presume was the intention; you called, but did not define the check() function there). You should not bother the user with several alert()s if there are several errors, but at most collect the error messages for one alert(). You can use an Array of string values for that.
However, given that new Firefox versions prevent the user from seeing the document while the alert() is displayed, you should avoid alert() and display the error messages in the document instead. A common approach is to highlight the erroneous fields using scripted CSS, and put the message that says what is wrong with the particular field either in a box for the entire form or next to the offending control. Also consider HTML5 form validation.

Related

Form submits multiple times

I am using a Wordpress theme that unfortunately is duplicating the header HTML for desktop, mobile and tablet. As a result, a login form I have appears to be submitting multiple times even though "Login" is only clicked once.
Here is the HTML for the form:
<div id="user-login">
<div class="com_row">
<div class="com_panel_body">
<div id="error_message91" class="com_alert com_alert_danger" style="display: none;">
</div>
<form method="post" id="validation_form83">
<input type="hidden" name="login_form_flag" value="1">
<div class="login-username">
<label for="email" class="main_label">Email Address</label>
<input id="email68" type="email" name="email" required="required">
</div>
<div class="login-password">
<label for="password" class="main_label">Password:</label>
<input id="password82" type="password" name="password" required="required">
</div>
<ul class="login-links" style="margin-top:-30px"><li>Forgot Password?</li></ul>
<div class="login-submit" style="margin-top:-20px">
<input type="submit" value="Login"></div>
<div style="padding-top:20px"><a class="button green small borderd-bot" href="/client_account">Register</a></div>
</form>
</div>
</div>
</div>
Here is the relevant JS:
$("[id^='validation_form']").each(function(i) {
//necessary because there are 3 form duplicates on the page, so this button works on all
jQuery(document).on("submit", this, SubmitValidationForm);
});
function($) {
SubmitValidationForm = function (event) {
event.preventDefault();
var formk = "#"+event.target.id;
var k = $(formk).serialize();
k += "&action=wcap_requests&what=validate_login";
jQuery("input[type=email]",formk).prop("disabled", true);
jQuery("input[type=password]",formk).prop("disabled", true);
jQuery("input[type=submit]",formk).prop("disabled", true).val(WCAP_Working_text);
var childf = $(formk).closest('div','.com_alert').children( ".com_alert");
$(childf).hide();
var login_form_flag = jQuery("input[name=login_form_flag]",formk).val();
jQuery.post(wcap_ajaxurl, k, function (data) {
data = JSON.parse(data);
console.log(data);
if (data.status === "OK") {
//== if client login through wcap login form
if (login_form_flag === '1'){
window.location.href = client_area_url;
}
else {
if (redirect_login !== "0") {
window.location.href = redirect_login;
} else {
window.location.reload();
}
}
}
else {
jQuery("input[type=email]",formk).prop("disabled", false);
jQuery("input[type=password]",formk).prop("disabled", false);
jQuery("input[type=submit]",formk).prop("disabled", false).val('Login');
$(childf).html(data.message).show();
}
});
};
};
The problem is because there are 3 duplicate forms on the page HTML (with only 1 visible to the user), the SubmitValidationForm function is called 3 times every time. The issue is pronounced when there is a valid login submitted, but the error box still appears saying invalid email after a few seconds (even though the login is actually correct and the user gets automatically redirected properly to the client area ). This error seems caused by the fact the SubmitValidationForm function is called 2 subsequent times after the first 'valid' submission which makes it think it's invalid, when it's not... the interesting thing is it doesn't seem caused by the other duplicate forms in the HTML, as the form ID attribute that I display in browser console shows only the 'valid' form being submitted (albeit multiple times -- perhaps because of the jquery.on() for each function).
Any ideas how to fix?
Thanks!
I figured out the issue. If anyone else is looking at this in future the issue was with respect to the 'on' function, it was referencing the 'document' before instead of 'this'. So it should be changed to:
$("[id^='validation_form']").each(function(i) {
jQuery(this).on("submit", this, SubmitValidationForm);
});

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

How to get the input type submit ID and apply javascript

I am using below jsp' form to submit the data. Before submitting I want to apply javascript.
<form name="inventory" method="post" action="<%=request.getContextPath() %>/Tdata_Main" class="form-light mt-20" role="form" onsubmit="return validate(this)">
Now, I have three input tags of 'Submit' type
<input type="submit" name="submit" class="btn btn-two" value="Update Inventory">
<input type="submit" name="submit" class="btn btn-two" value="Add Empty Row">
<input type="submit" id="submitDelete" name="submit" class="btn btn-two" value="Delete Row">
After adding three new columns and filling in the data one by one, I added forth one as shown below. Now, I am in no need of this forth empty row hence I want to delete it. But the javascript code is getting applied here too and asking me to fill in the blank fields.
Below is the javascript code that is getting executed on the onSubmit event initiated from form.
<script type="text/javascript">
function validate(form) {
//alert(form.id);
if(form.id != "submitDelete"){ // NOT WORKING
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].type == "text"){
if(form.elements[i].value.length == 0 || form.elements[i].value.length == "null"){
alert('No value entered in '+form.elements[i].name+'.');
form.elements[i].focus();
return false;
}
}
}
}
if (confirm("Would you like to proceed!") == true) {
return true;
}
else{
return false;
}
}
</script>
How could I avoid getting this javascript code being applied on Delete using Javascript. Kindly suggest.
Your code works fine. Only one thing you should remove the action attribute from your form element and post that data using javascript only.
Also your delete button is disabled. Enable it and it will work fine

Onsubmit still submits when returning false

I'm having a problem with a simple html login page I made, where when I submit the login form with invalid credentials the form still submits, even though my validation method is executing the "return false" command. I know that this question has been asked a multitude of times here, but none of the answers to those questions have helped me.
My html form is as follows:
<form onSubmit="return validateForm();" method="get" action="TestPage.html">
<div id="centralPoint" class="frame">
<select id="centralPointSelect" data-inline="true" data-mini="true" data-native-menu="false" name="centralPoint"></select>
</div>
<div id="credentialsFrame" class="frame">
<input id="userField" type="text" name="Username" />
<input id="passField" type="password" name="Password" />
</div>
<div id="errorMsg"></div>
<input id="loginBtn" type="submit" value="Login" />
<div id="rememberMe" class="frame">
<input type="checkbox" id="checkbox-1" class="custom" data-mini="true" name="rememberMe" />
<label for="checkbox-1">Keep me signed in</label>
</div>
<div id="forgotPassFrame">
<input id="forgotPass" type="button" data-mini="true" value="Forgot password?" />
</div>
</form>
And here is my javascript method. Note that even if the only line of code in here is "return false;" the form still submits. I've also checked in firebug to make sure that the method is actually being called and that it is indeed returning false, and it all checks out.
function validateForm()
{
var usernameTxt = $("#userField").attr("value");
var passwordTxt = $("#passField").attr("value");
if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
{
$("#errorMsg").html("Please enter a username and password.");
return false;
}
}
Is there something really obvious that I'm missing? I'm not binding the onsubmit event in any way other than what you can see in the html form tag, nor am I assigning any click handler to the submit button.
It might be relevant that I'm using JQuery mobile, is it possible that this is doing something with my form?
If you want to handle form submission on your own, you will need to add the data-ajax="false" attribute to the <form> tag so jQuery Mobile leaves it alone.
To prevent form submissions from being automatically handled with
Ajax, add the data-ajax="false" attribute to the form element. You can
also turn off Ajax form handling completely via the ajaxEnabled global
config option.
Source: http://jquerymobile.com/demos/1.1.0/docs/forms/forms-sample.html
Here is a demo of your form but with the above attribute added: http://jsfiddle.net/XtMw9/
Doing this means that you will have to manually submit your form:
function validateForm()
{
var usernameTxt = $("#userField").val();
var passwordTxt = $("#passField").val();//notice the use of .val() instead of .attr()
if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
{
$("#errorMsg").html("Please enter a username and password.");
return false;
}
var $form = $('form');
$.ajax({
url : $form.attr('action'),
type : $form.attr('method'),
data : $form.serialize(),
success : function (response) { ... },
error : function (a, b, c) { console.log(b); }
});
}
Explanation
This works because by default jQuery Mobile will attempt to submit any form via AJAX. Using the data-ajax="false" attribute we can tell jQuery Mobile to leave a specific form alone so we can submit it on our own.
In validateForm() function, you've used two undefined variables(userLbl and passLbl).
Define value for the variables and check.

jQuery .submit doesn't get called?

I have the following function that is meant to get called after a form I submitted (this method is in my application.js folder in my rails app):
var addToTopics = function() {
var result = "";
var checkedTopics = $(".topic-checkbox:checked");
$.each(checkedTopics, function(i, topic) {
if(i == 0) {
result = result + $(topic).attr('value');
}
else {
result = result + ", " + $(topic).attr('value');
}
});
return result;
};
$("#new_comment").submit(function() {
var ListOfTopics = addToTopics();
$('#comment_topics').val(ListOfTopics);
alert($('#comment_topics').val());
return true;
});
HTML
<form method="post" id="new_comment" class="new_comment" action="/comments" accept-charset="UTF-8"><div style="margin:0;padding:0;display:inline"><input type="hidden" value="✓" name="utf8"><input type="hidden" value="8vLhtuco+TAkeB+9kQ0gERvA54BD/BnjJuguWxuXWHQ=" name="authenticity_token"></div>
<div class="field">
<label for="comment_comment">Comment</label>
<br>
<textarea rows="20" name="comment[comment]" id="comment_comment" cols="40"></textarea>
</div>
<div class="field">
<input type="hidden" value="28" name="comment[review_id]" id="comment_review_id">
</div>
<div class="field">
<input type="hidden" value="1" name="comment[user_id]" id="comment_user_id">
</div>
<div class="field">
<input type="hidden" value="" name="comment[topics]" id="comment_topics">
</div>
<div class="actions">
<input type="submit" value="Create Comment" name="commit" id="comment_submit">
</div>
</form>
But this dosen't seem to be getting called as the alert dosent even go off when I submit my form.
Any idea why? Thanks
You need to ensure the code attaching the listener runs after the form has been rendered to the dom. this is one way of doing it:
$(function() {
$("#new_comment").submit(function() {
var ListOfTopics = addToTopics();
$('#comment_topics').val(ListOfTopics);
alert($('#comment_topics').val());
return true;
});
});
has an element with the id new_comment been added to the dom prior to you running $("#new_comment").submit(function(){...});
If not, then $("#new_comment") will return no selections and jquery will silently 'fail'.
i had this same issue yesterday, my issue was an unrelated javascript error on the page
add a simple alert above this line
$("#new_comment").submit(function() {
to check (or check your browser js console)
Try changing $("#new_comment").submit(function() to $("#comment_form").submit(function(), from what I'm seeing in your code those two selectors are not matching. Hope it helps. Cheers
And since you have an action attribute in your form "action='/Comment'" either remove it if you do not have a valid reason why you have it there or prevent the default behavior which will force the form to redirect to your current url + /Comment
So the code will look like :
$("#comment_form").submit(function(evt) {
evt.preventDefault();
// rest of function below
});

Categories