I tried to get the string put in a form from one html (testinput) and when the form is validated, get it to redirect to another html (testoutput) with the data displayed only using js, but never works.
edit (rephrasing) : I created 2 html pages (testinput and testoutput) and in the testinput page, i put an input bar. When the user fills the form and press enter, i want it to redirect to the testoutput page, with what he filled in displayed
This is the method i found in another post but didnt work.
code in testinput :
<form method="get">
<input type="text" name="q">
</form>
code in testoutput :
<body>
<div id="here"></div>
</body>
code in js file :
var result = $("input[name=q]").val();
$("#here").text(result);
You can avoid the form to be submitted and afterwards validate the form to display the html in any given div
let my_form = document.querySelector('#my_form');
let output = document.querySelector('#output')
function showHTML(e){
e.preventDefault();
let html = my_form.querySelector('textarea').value;
output.innerHTML = html;
}
my_form.addEventListener('submit', showHTML);
#output {
border: 1px solid #d3d3d3;
min-height: 200px;
margin-top: 20px;
}
textarea {
width: 100%;
}
<form action="" id="my_form">
<textarea name="" id="" cols="30" rows="10"></textarea>
<input type="submit" value="Send">
</form>
<div id="output">
</div>
To get a submitted value, you can parse location's search parameter.
Example:
let q = location.search.match(/q=([^&])/);
if(q.length > 1)
$('#here').text(q[1]);
Related
// What I am Trying to do is to use php and insert my subscribers of Websites In A database first here is
// my html code
<center>
<form action="members.php" method="post">
<h1 class="title-4">Subscribe For Our Latest Updates</h1>
<input type="text" name="name" id="name" placeholder="Enter Your Full Name">
<div class="error-name" style="display:none">
<p>Please Enter Your Name </p>
</div>
<input type="email" name="email" id="email" placeholder="Enter Your E-mail" >
<div class="error-email" style="display:none">
<p>Please Enter a Password Password must be greater than 7 characters </p>
</div>
<input type="submit" name="submit" id="sub" class="name-sub email-sub" value="Subscribe">
</form>
</center>
<div class="sub-pop">
<center>
<h1 class="title-5">
★Thanks For Subscribing ★
</h1>
</center>
</div>
<script src="home.js"></script>
// here is the php Code in members.php
if(isset($_POST['submit'])) {
$connection=mysqli_connect('localhost','root','','lolovers');
$name = $_POST['name'];
$email = $_POST['email'];
$query = "INSERT INTO subscribers(name,email)";
$query .= "VALUES ('$name','$email')";
$subscribe=mysqli_query($connection,$query);
header('Location:home.php');
}
// This is the code to insert my user name and emails in my data base php admin
// here is my javascript that I use to validate my information
// Pop up form for subscribers javascript code
const popUp = document.querySelector('.title-5');
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const subscribe = document.querySelector('#sub');
const errorName = document.querySelector('.error-name')
const errorEmail = document.querySelector('.error-email')
subscribe.addEventListener('click',subscription());
function subscription(e) {
if(name.value==="") {
errorName.style.display = "block"
}
else if (email.value==="") {
errorEmail.style.display = "block"
}
else if (name.value && email.value==="") {
errorName.style.display = "block"
errorEmail.style.display = "block"
e.preventDefault()
}
else {
popUp.style.display="block"
}
}
// The reason why I am using php and javascript is because I have a hard time to display an error message
in php so instead of validating using php I use javascript to validate my form information and I use php
insert the data in php myadmin. The error messages I want to display is in
<div class="error-name" style="display:none">
<p>Please Enter Your Name </p>
</div>
// I want to use javascript so that when some one does not enter his name this div section display under
the form
<div class="error-email" style="display:none">
<p>Please Enter a Password Password must be greater than 7 characters </p>
</div>
// the same thing above I want this div section to display when some one does not enter his email
//somehow my javascript does not work properly when i try to refresh the page my div sections display
automatically even though I did not enter any information it just displays. it even display my thank you
section
<div class="sub-pop">
<center><h1 class="title-5">
★Thanks For Subscribing ★
</h1></center>
</div>
// I also want my php code to not insert the data in the database when the information is not valid
you unnecessarily complicate the task, html5 natively offers this kind of control, without having to add any line of additional code unless you want to customize them.
Just add the required attribute on these fields
form {
display: table;
margin: 1em auto; /* horizontal centering */
padding: .7em;
border: 1px solid grey;
}
input, button {
display: block;
margin:.5em;
float: left;
clear: both;
}
<form action="members.php" method="post">
<h4>Subscribe For Our Latest Updates</h4>
<input type="text" name="name" placeholder="Enter Your Full Name" required >
<input type="email" name="email" placeholder="Enter Your E-mail" required >
<button type="submit">Subscribe</button>
</form>
there is many tutorials on the web to explain this.
You also get precise information on MDN -> https://developer.mozilla.org
So I'm trying to submit a form using Ajax in order to prevent it from opening a new tab upon submition (Which gets very annoying when creating several images, since a new tab would be generated with every image)
This will submit the form, and function properly, however it will open a new tab.
// Submits form
$("#image-base-edit").submit();
However I tried #abc123 suggestion on this post and I modified his code to look like the snippet below, however by submitting it this way, the image isn't actaully created.
/* attach a submit handler to the form */
$("#image-base-edit").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term1 = $form.find('input[name="id"]').val(),
term2 = $form.find('input[name="title"]').val(),
term3 = $form.find('input[name="image_file"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
name: term1,
title: term2,
image_file: term3
});
/* Prints Done */
posting.done(function(data) {
console.log("done");
});
});
// Submits form
$("#image-base-edit").submit();
Here is the HTML form:
<!--Image Create FORM-->
<form name="edit_form" method="post" enctype="multipart/form-data" class="enableUnloadProtection enableAutoFocus enableFormTabbing enableUnlockProtection d-none" action="" id="image-base-edit" target="_blank">
<fieldset id="fieldset-default" class="formPanel" style="display: block;">
<legend id="fieldsetlegend-default" style="visibility: hidden; font-size: 0px; padding: 0px; height: 0px; width: 0px; line-height: 0;">Default</legend>
<input name="id" value="image.2018-05-10.9629264509" originalvalue="image.2018-05-10.9629264509" type="hidden">
<div class="field ArchetypesStringWidget kssattr-atfieldname-title" data-fieldname="title" data-uid="0fd3d162687e4bd8917bc9830d616043" id="archetypes-fieldname-title">
<input name="title" class="blurrable firstToFocus" id="title" value="" size="30" maxlength="255" placeholder="" type="text">
</div>
<div class="field ArchetypesImageWidget kssattr-atfieldname-image" data-fieldname="image" data-uid="0fd3d162687e4bd8917bc9830d616043" id="archetypes-fieldname-image">
<div id="appendInputhere">
</div>
</div>
</fieldset>
<div class="formControls">
<input name="form.submitted" value="1" originalvalue="1" type="hidden">
<input class="context" name="form.button.save" value="Save" type="submit">
</div>
</form>
And the content that gets appened into the "appendInputhere" looks like this.
<input size="30" name="image_file" id="image_file" type="file">
If there is an easier way to do this, that I may be overlooking please let me know. Basically I want the form to function the exact same way it currently does, other than opening a new tab, or loading a new page in the users window, I want the user to not have to see a change.
So while reading around more, and trying to find a way to do the original method I wrote about above, I learned that it is possible to set the target of a form to an iframe. So to solve my issue above, created this iframe...
<iframe name="formSubmitFrame" name="formSubmitFrame" tile="Holds Submitted form data" rel="nofollow" class="d-none"></iframe>
and had it set to not display anywhere. Then, I set the target of my iframe to "formSubmitFrame".
This ultimately achieved my goal of submitting a form without the user seeing any window or tab changes.
At the moment I'm just trying to post their comment to the comment div, commentsbox1.
HTML:
<form id="commentform" name="commentform" onsubmit="submitComment();">
<input id="commenttext" type="text" placeholder="Leave a comment..." name="commenttext">
<input type="submit" style="position: absolute; left: -9999px"> <!-- submit by pressing enter -->
</form>
Javascript:
function submitComment(){
var commenttext = $('#commenttext').val();
$('#commentsbox1').append(commenttext);
};
Currently it seems to do nothing at all. It says the function is unused too.
Try this:
<form id="commentform" name="commentform" onsubmit="submitComment(event);">
and in the function:
function submitComment(e){
e.preventDefault();
var commenttext = $('#commenttext').val();
$('#commentsbox1').append(commenttext);
};
This will prevent refresh of the page.
It works, but before you see the result, the page is refreshed.
function submitComment(){
var commenttext = $('#commenttext').val();
$('#commentsbox1').append(commenttext);
return false;
};
When you submit the form you should override the normal behaviour of the button:
$('#myBtn').on('click',function(event) {
event.preventDefault();
//do what you want to do
});
dynamically i generate a formular into a defined div-container and i would like grab the send-action for sending with ajax.
The generate HTML:
<div class="mhuntform">
<form action="/wp-admin/admin-ajax.php" method="POST">
<h2>Title</h2>
<p>A text</p>
<div id="form" style="padding: 5px 0px;">
<p>
<label for="email" style="display: inline-block; margin-right: 10px;">E-Mail</label>
<input type="email" name="email" id="email" placeholder="E-Mail" style="width: 60%;">
</p>
<p>
<button name="mhskl_send" id="mhskl_send">Anmelden</button>
</p>
</div>
</form>
</div>
The Formular is defined by the admin into the wordpress-page. In Javascript (jQuery) i know only the classname of the div-container (here .mhuntform). So in Javascript i try to catch the event:
// mhuntskl.options.container = '.mhuntform'
$(mhuntskl.options.container).find('form').submit(function(ev){
ev.preventDefault();
var email = $(mhuntskl.options.container).find('input[type="email"]').val();
var res = $.ajax(mhuntskl.options.ajaxurl,{async:false,data:{action:'subscribe',email:email},dataType:'json',type:'POST'}).responseText;
res = $.parseJSON(res);
if (res.success) {
$(mhuntskl.options.container).hide();
}
return false;
}
But unfortunately the submit-event will not catch and if i prints the containter with find into the console console.log($(mhuntskl.options.container).find('form')) it will received an empty object only.
What i make wrong here?
If console.log($(mhuntskl.options.container).length); is 1 and console.log($(mhuntskl.options.container).find('form').length); is 0 then there is only one possible reason. Your form is still not inside the .mhuntform div when you execute the code. Is that form generated by another javascript. If not, then is the js code wrapped in $(document).ready.
For instance, I know that it is possible to do something in Javascript that allows users to update text based on user text input:
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' onclick='changeText2()' value='Change Text'/>
View the above code in action at: tizag.com/javascriptT/javascript-innerHTML.php
However, instead of the above code, I would like to know if it's possible to do something similar for a url link. Below I've placed a step by step example of what I would like to happen upon the user inputing text:
Original Link:
http://www.google.com/search?q=
User Input in Text Field:
espn
User clicks button to submit text in text field
Final Link:
http://www.google.com/search?q=espn
Thanks for your help...BTW...if you can't tell I'm a bit of a novice so detail is appreciated.
Here's one in plain JS that updates as you type:
<a id="reflectedlink" href="http://www.google.com/search">http://www.google.com/search</a>
<input id="searchterm"/>
<script type="text/javascript">
var link= document.getElementById('reflectedlink');
var input= document.getElementById('searchterm');
input.onchange=input.onkeyup= function() {
link.search= '?q='+encodeURIComponent(input.value);
link.firstChild.data= link.href;
};
</script>
Note:
no inline event handler attributes (they are best avoided);
assigning both keyup and change, to try to get keyboard updates as they happen and ensure that all other updates get caught eventually;
the use of encodeURIComponent(), necessary in case the search term has any non-ASCII or URL-special characters in;
setting the search property of a Location (link) object to avoid having to write out the whole URL again;
setting the data of the Text node inside the link to reflect the full URL afterwards. Don't set innerHTML from user input as it may have HTML-special characters like & and < in.
#1: you need some forms
#2: you need to catch when the form is submitted
#3: based on the form's submission change the url
Here is a demo: http://jsfiddle.net/maniator/K3D2v/show/
here is the code: http://jsfiddle.net/maniator/K3D2v/embedded/
HTML:
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>
JS:
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e){
location = "http://jsfiddle.net/maniator/K3D2v/show/#"
+ encodeURIComponent(theInput.value);
return false;
}
I'd suggest using a cross browser library such as jQuery rather than straight JavaScript. With jQuery, you'd add a click handler for your button, grab the value of the input, build your URL, and set window.location to go to the new url
jsFiddle
HTML
<input type="text" id="q" />
<input type="button" id="submit" value="submit" />
JavaScript
$(function () {
$('#submit').click(function() {
var url = "http://www.google.com/search?q=";
url += $('#q').val();
window.location = url;
});
});
You could try this;
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
</script>
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' value='Enter Search String Here' />
<input type='button' onclick='changeText2()' value='Change Link'/>
Check it out here
This is the solution I deviced in a matter of seconds:
<input type="text" name="prog_site" id="prog_site" value="http://www.edit-me.com" />
Open URL
No complex javascript, no extra quotes nor functions required. Simply edit the ID tag to your needs and it works perfectly.
I think this might be useful:
.btn {
border: none;
outline: 0;
display: inline-block;
padding: 10px 25px;
color: black;
background-color: #ddd;
text-align: center;
cursor: pointer;
}
.btn:hover {
background-color: #555;
color: white;
}
.textinput {
line-height: 2.5em;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css' integrity='sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm' crossorigin='anonymous'>
</head>
<body>
<form action='#' method='post'>
<label for='ytid'>Please enter your YouTube Video ID:</label>
<br>
<br>
<iframe
href='#'
width='287.5'
height='250'
frameborder='0'
allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture'
allowfullscreen
src='https://www.youtube.com/embed/'
id='ytvid'
></iframe>
<br>
<br>
<input
type='text'
class='textinput'
size='50'
id='ytid'
name='ytid'
placeholder='m4jmapVMaQA'
minlength='1'
maxlength='11'
onchange='document.getElementById("ytvid").src = "https://www.youtube.com/embed/" + this.value'
>
<br>
<br>
<button type='submit' class='btn'>Generate Subtitles »</button>
</form>
</body>
</html>
WARNING:
This code snippet might not run well in Stack Overflow.
This way, the video updates every time there is a change in the text input.
I'm actually making a YouTube Video subtitle generator, so I just copy pasted my code here.
www.google.com/search?q=<br>
<input type="text" id="userInput" value="Enter your text here"><br>
<input type="button" onclick="changeText2()" value="change text">
<script>
function changeText2()
{
var input=document.getElementById('userInput').value;//gets the value entered by user
//changing the href of tag <a> by concatenatinng string "www.google.com/search?q=" and input (user input)
document.getElementById("link").href = "www.google.com/search?q="+input;
//changing the text from "www.google.com/search?q=" to "www.google.com/search?q=" + user input
document.getElementById("link").innerHTML = "www.google.com/search?q="+input;
}
Clicking the button calls the function changeText2. Which performs the task.