Submitting the closest form without a submit button? - javascript

I have page with many forms consisting of only a textarea and a hidden field with an id
I am trying to use jQuery to submit the form each time the user enters some text and hits command+enter on the keyboard.
For that I am using
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
That part works fine, but then when I try to submit my form the script stops execution. I am sure I am doing some mess with the closest('form') submit.
Here is my full code
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
$('textarea').closest('form').submit(function() {
$.post("someurl.php", $(this).serialize(), function(data) {
alert(data);
});
});
};
});
When I debug it never enters inside the $('textarea').closest('form').submit(function() {
Any idea how can I pass the content of the form for which command+enter was entered to my processing URL?
Any tips will be appreciated,
Thanks
UPDATE
HTML code for the forms
<form action="#">
<div class="col-xs-1">
<textarea class="form-control" rows="5" placeholder="Enter your answer"></textarea>
<input type="hidden" name="idval" value="xxxx">
</div>
</form>
EDIT 2
While debugging the code I see that the parameters are correctly passed but at one point jquery loses the values.
What is even stranger is that the fiddle posted below works fine in fiddle, but when I download the code and test it on my localhost it doesn't.
Here is the code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style type="text/css">
</style>
<title> by b</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
// e.preventDefault();
$.post($(this).closest("form").attr("action"), { html: $(this).closest("form").serialize()}, function(data) {
alert(data);
});
}
});
}//]]>
</script>
</head>
<body>
<form action="#">
<textarea name="area1"></textarea>
</form>
<form action="#">
<textarea name="area2"></textarea>
</form>
</body>
</html>
any clues?

You shouldn't define an event handler inside another event handler. You should just post the current form.
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
$.post($(this).closest("form").attr("action"), $(this).closest("form").serialize(), function(data) {
alert(data);
});
}
});

Related

How do I connect the javascript file to the html?

Hello I am making a login website and i just want to have the javascript with the password and username in an different file just to make it a little bit harder to find(its just a school project). But my problem is that it wont verify and redirect to my Main.html code after you click the login button.
As you can see in the code i have tried to connect it with the code.
<script src="Login.js"></script>
Here is the html code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>kjedelig AF</title>
<link rel="stylesheet" href="Login.css">
</head>
<body oncontextmenu="return false;">
<form class="box" action="Login.html" method="post" name="login">
<div class="login">
<h1>Kjedelig AF</h1>
<input type="text" name="usrname" placeholder="Username">
<input type="password" name="pswrd" placeholder="Password">
<input type="submit" onclick="return check(this.form)" value="Login">
</div>
</form>
<script src="Login.js"></script>
</body>
</html>
And here is my javascript code witch i have problems connecting to the html code:
<script language="javascript">
function check(form){
if(form.usrname.value == "dd" && form.pswrd.value == "dd") {
window.location.href= "Main.html";
return false;
}
else
{
alert("Iks dette er kjedelig AF :)")
}
return true;
}
</script>
First of all, include your JS file at the <head>. there is no good reason not to.
To fix your issue remove <script language="javascript"></script> from your .js file
you should use <script language="javascript"></script> when inside .html file not .js
Two reasons:
The script link to the JS file should be anywhere within the
<head></head> tags
The JS file shouldn't have the <script language="javascript"></script>, all that the JS file needs to have is:
function check(form){
if(form.usrname.value == "dd" && form.pswrd.value == "dd") {
window.location.href= "Main.html";
return false;
}
else
{
alert("Iks dette er kjedelig AF :)")
}
return true;
}
Hope this helps.

Change HTML for Spanish Site

I'm using Divi and I can't seem to update the email that shows up in the topbar in the header on the Spanish version of the site. My JS is a little rusty.
The URL is domainofclient.com/es/inicio
The element is <span id="et-info-email">sales#domainofclient.com</span> which needs to change to <span id="et-info-email">ventas#domainofclient.com</span>
What I've tried
<script type="text/javascript">
if(document.URL.indexOf("/es/inicio/") >= 0){
document.getElementById('et-info-email').innerHTML = 'ventas#domainofclient.com'
}
</script>
I've also tried the following JQ
<script type="text/javascript">
if(window.location.href === "https://domainofclient.com/es/inicio/") {
jQuery('#et-info-email').text('ventas#domainofclient.com');
}
</script>
You are almost there. I would although try to first of all wrap the code into a function and run it only when the page is ready.
function replaceEmail() {
if(document.location.pathname.indexOf("/es/inicio") !== -1){
document.getElementById("et-info-email").innerHTML = "ventas#domainofclient.com"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="author" content="Author">
<title>#[[$Title$]]#</title>
</head>
<body onload="replaceEmail()">
<span id="et-info-email">sales#domainofclient.com</span>
</body>
</html>
I figured it out!
<script type="text/javascript">
jQuery(document).ready(function() {
if(window.location.href === "https://domainofclient.com/es/inicio/") {
jQuery('#et-info-email').text('ventas#domainofclient.com');
}
});
</script>

Ajax `appendTo` replaces the existing element

I am trying to submit some form data to Servlet using JQuery and retrieve the Servlet response from the same JQuery. Please have a look at the below code.
<%--
Document : index
Created on : Feb 23, 2015, 8:18:52 PM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var form = $('#customItemForm');
function formSubmit(){
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data);
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
</script>
</head>
<body>
<form method="get" action="SampleServlet" id="customItemForm" onsubmit="formSubmit(); return false;">
Name <input type="text" name="name">
<button>Submit</button>
</form>
<br>
<div id="results"></div>
</body>
</html>
In the above code in JQuery section, I am trying to read the value I got from servlet, create a Text Input in a DIV. My expectation was if I click the "Submit" button twice, then 2 text boxes; if I click the submit button thrice, then 3 text boxes and so on. Unfortunatly it is not happening here. Only one text box appear, all the time, replacing the previous one.
How can I fix this?
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data); //replace with $("#results").append(data)
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
you need to make the change above as .text() replaces the existing data in the div (so the previous run you did gets over-written)

firebug and chrome console both have disappearing console.log messages

I am writing my first site from scratch - I have a form and a function that acts when the form is submitted:
application.js
$(document).ready(function() {
$("#signupform").submit(function(e) {
var name = document.getElementById("pname").value;
var email = document.getElementById("email").value;
var userArray = [];
var user = {
name: name,
email: email
};
console.log(user.email, user.name);
e.preventDefault;
});
});
The message gets logged to the console correctly...but it is only a blip - it disappears right away. Also...any errors I was getting while writing the above code also only showed up as short blips in the console. Just barely long enough to read.
Here is my index.html file...incase it is relevant:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>it IT</title>
<link rel="stylesheet" type="text/css" href="application.css" />
<script src="jquery.js"></script>
<script src="application.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>it IT</h1>
<div id="signup">
<form id="signupform">
Name: <input type="text" name="pname" id="pname"><br>
Email: <input type="text" name="email" id="email"><br>
<input type="submit" value="sign up">
</form>
</div>
<div id="signin"></div>
<div id="content"></div>
</body>
</html>
preventDefault is a method, you need:
e.preventDefault();
In your question code, the form was submited so console was refreshed.
Actually e.preventDefault is not correct, you need to do this:
$(document).ready(function () {
$("#signupform").submit(function (e) {
e.preventDefault(); // Missing () for preventDefault method
var userArray = [];
var user = {
name: $('#pname').val(), // also, you can get the values here only
email: $('#email').val() // no need to use extra variables for it
};
console.log(user.email, user.name);
});
});
In your browser console go to settings (on the top-right corner) and check the preserve log option. That should prevent the page from reloading.

window.location.assign("link"), is not working

Here is the javascript code.
<script type="text/javascript">
function myfunc()
{
var filmName = document.getElementById("mysearch-text").value;
alert(filmName);
if(filmName == "parker")
 window.location.assign("http://www.google.com");
else
alert("hello");
}
</script>
If I enter any other string I get an "hello" alert and If I enter "parker" the page "http://www.google.com" wont get loaded. Why is this happening?
EDIT:
Ok as someone mentioned I did remove "http://www.google.com" and added "http://stackoverflow.com" but it did not resolve my problem. And I cant even load local html pages that are in the same directory
if(filmName == "parker")
window.location.assign("index.html"); // also "./index.html" or ./index/html
Even this is not working. What's wrong
I also have jquery libraries: that is Jquery UI and Jquery
This question needs more of info I think. Here are the final edits
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- Other style and js libraries, including Jquery Ui and regular jquery -->
<script>
$(document).ready(function() {
$(".youtube").fancybox();
}); // end ready
</script>
<script>
$(document).ready(function(e) {
$('.tooltip').hide();
$('.trigger').mouseover(function() {
/* Rest of it, which is not necessary here */
</script>
<script type="text/javascript">
function myfunc()
{
var filmName = document.getElementById("mysearch-text").value;
alert(filmName); // for debugging
if(filmName == "parker")
 window.location.assign("index.html");
else
alert("hello");
}
</script>
</head>
<body>
<div id='mysearch-box'>
<form id='mysearch-form'>
<input id='mysearch-text' placeholder='' type='text'/><!-- Input here guys -->
<button class = "none" id='mysearch-button' onclick = "myfunc()">Search</button>
<!-- press this button after entering "parker" -->
</form>
</div>
<!-- Rest of the HTML page -->
</body>
</html>
I assume you are using a form onsubmit event to call myfunc, if so you have to prevent the default behavior by return false; (for example)
HTML:
<form id="form">
<input type="text" id="mysearch-text">
<input type="submit" value="Submit">
</form>
JS:
<script>
window.onload = function () {
document.getElementById("form").onsubmit = function () {
var filmName = document.getElementById("mysearch-text").value;
alert(filmName);
if (filmName == "parker") window.location.href = "http://www.w3fools.com";
else alert("hello");
return false; //prevent the default behavior of the submit event
}
}
</script>
I have tested the following solution and it works perfectly:
setTimeout(function(){document.location.href = "page.html;"},500);

Categories