JQuery replacing form elements with text - javascript

I am in a situation, where I need to convert my form filled data to a text before submitting.
Like for example, the form may have a name field and an email field. I will fill the form with details, then when I click export as text, I need to get the contents of the html in text format
name = <input type="text" name="name" /> <!-- user enters "john" -->
email = <input type="text" name="email" /> <!-- user enters a#b.com -->
when I export I need
name = john
email = a#b.com
Currently, I am using this code to convert. But the problem is, once I convert I am not able to get back to previous state.
$("#btn").click(function(){
$('.replace').replaceWith(function(){
return this.value
});
});
So, what I thought was, I will display the output in a div tag. But if I try
document.getelementByID("parentdiv").value
I am unable to get the form values.
Any suggestions please?
Update:
serialize is not working as expected. The above one is a small example. The form is so complex and I need to visually render the form values to its labels.

$x = $('form').serialize();
This will give you a string of elements and values which you can easily work with, it's intended to use as JSON, however for your intended purpose it should be fairly easy to fiddle around with.
It will give you an output similar to
name=John&x=y

try like this using serializeArray():
$("#btn").click(function(){
var x = $('form').serializeArray();
console.log(x);
var str="";
$.each(x, function( index, val ) {
str=str+val.name+":"+val.value+"<br>";
});
$('#textFrom').html(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
name =<input type="text" name="name" /> <!--user enters "john"-->
email =<input type="text" name="email" /> <!--//user enters a#b.com-->
</form>
<button id="btn">click</button>
<div id="textFrom"></div>

Use jQuery serialize function :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").text($("form").serialize());
});
});
</script>
</head>
<body>
<form action="">
Name: <input type="text" name="name" value="Tina" /><br>
Email: <input type="text" name="LastName" value="tina#yopmail.com" /><br>
</form>
<button>Export Values</button>
<div></div>
</body>
</html>
Output will be : name=Tina&LastName=tina%40yopmail.com

Related

How to populate input with jquery on-click

I want to populate an input field on click with jquery, currently am able to populate a normal html field but not an input field, the reason i want to achieve this is to enable submissions because currently the data populated on html field is not being submitted, I beleive that populating this data in an input field will enable possible submissions.
I am currently using the following code to achieve this:
function populatethefield() {
document.getElementById("populatethisfield").innerHTML = "data to be populated to the field";
}
The field html
< p id="populatethisfield"><p>
This works, but i want to populate an input field, rather than a paragraph field.
When trying to change the value of an input field, you have to access the value property because inputs do not have an innerHTML, but a value instead. See code below for a demonstration:
<input type="text" id="target" placeholder="test" />
<script>
document.getElementById('target').value = "Value Updated.";
</script>
Hope this is what you are looking for
$('.populate').click(function(e){
var data = 'Some Content'
$("#populatethisfield").html('<input value="'+data+'">')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<p id="populatethisfield"></p>
<button class="populate">Populate Input</button>
If you want a pure jquery solution use the val() method for input fields.
$('.populate').on('click', function() {
$('#target').val("data to be populated to the field");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="text" id="target" placeholder="test" />
<button class="populate">Populate Input</button>
You can try this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<script>
function changeValue(value){
document.getElementById("input").value= "Hello World";
}
</script>
<body>
<input type="button" onclick="changeValue(2)" value="Button">
<input type="text" id="input" value="">
</body>
</html>

Please use POST resquest when sending form with JS

What i'm missing here to print 'user_input' to display paragraph ?
is myform.submit required? Because actually I can access the variable and make an alert with it..
<script language="JavaScript">
function getData(input) {
var input = document.getElementById("user_input").value;
// alert(input)
document.myform.submit()
$('.display').text("The URL is : " + input)
}
</script>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.js"
integrity="sha256-tA8y0XqiwnpwmOIl3SGAcFl2RvxHjA8qp0+1uCGmRmg="
crossorigin="anonymous"></script>
<form id="myform">
<label><b>Enter a URL</b></label>
<input type="text" name="message" id="user_input">
<input type="submit" id="submit" onclick="getData()"><br/>
<p id="display"><span></span></p>
</form>
Don't mix java-script/jQuery into each-other.
Since you are using jQuery library then do it in a better way like below:-
Working example:-
$(document).ready(function(){ // when document is rendered completely
$('#submit').click(function(e){ // on click of submit button
e.preventDefault(); // prevent the form submit
var input =$("#user_input").val(); // get input value
$('#display').text("The URL is : " + input); // add it as a text to paragraph
});
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.js" integrity="sha256-tA8y0XqiwnpwmOIl3SGAcFl2RvxHjA8qp0+1uCGmRmg=" crossorigin="anonymous"></script>
<form id="myform">
<label><b>Enter a URL</b></label>
<input type="text" name="message" id="user_input">
<input type="submit" id="submit"><br/><!-- no need of onclick-->
<p id="display"><span></span></p>
</form>
You must do what the response is actually asking you to do which simply is adding the method attribute to the form element: <form method="POST">
Working DEMO

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I am doing a web application using javascript and html that has a form containing a text field, button. When I enter a number in that text field and submit by clicking on that button, text areas are generated dynamically. Once my form is submitted some text areas are created but if I am not satisfied with existing text areas then again I enter some value with out refreshing page. But the text field value entered previously prevails showing the new text areas below the existing text areas on the page.
So, how do I clear the value with out refreshing the page.
<div>
<html>
<input type="text" name = "numquest" id ="numquest" value="" size="5" style="" disabled>
<input type="button" value="submit" onclick="getFields();">
</div>
</html>
<javascript>
var num_q=document.getElementById('numquest').value;
//code for dynamic creation
</javascript>
try this:
Using jQuery:
You can reset the entire form with:
$("#myform")[0].reset();
Or just the specific field with:
$('#form-id').children('input').val('')
Using JavaScript Without jQuery
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
function submitForm() {
// Get the first form with the name
// Hopefully there is only one, but there are more, select the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit
frm.reset(); // Reset
return false; // Prevent page refresh
}
You can set the value of the element to blank
document.getElementById('elementId').value='';
Assign empty value:
document.getElementById('numquest').value=null;
or, if want to clear all form fields. Just call form reset method as:
document.forms['form_name'].reset()
you can just do as you get that elements value
document.getElementById('numquest').value='';
<form>
<input type="text" placeholder="user-name" /><br>
<input type=submit value="submit" id="submit" /> <br>
</form>
<script>
$(window).load(function() {
$('form').children('input:not(#submit)').val('')
}
</script>
You can use this script where every you want.
It will clear all the fields.
let inputs = document.querySelectorAll("input");
inputs.forEach((input) => (input.value = ""));
HTML
<form id="some_form">
<!-- some form elements -->
</form>
and jquery
$("#some_form").reset();
I believe it's better to use
$('#form-id').find('input').val('');
instead of
$('#form-id').children('input').val('');
incase you have checkboxes in your form use this to rest it:
$('#form-id').find('input:checkbox').removeAttr('checked');
.val() or .value is IMHO the best solution because it's useful with Ajax. And .reset() only works after page reload and APIs using Ajax never refresh pages unless it's triggered by a different script.
I had that issue and I solved by doing this:
.done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
I added this code after my script as I used jQuery. Try same)
<script type="text/JavaScript">
$(document).ready(function() {
$("#feedback").submit(function(event) {
event.preventDefault();
$.ajax({
url: "feedback_lib.php",
type: "post",
data: $("#feedback").serialize()
}).done(function() {
$(this).find("input").val("");
$("#feedback").trigger("reset");
});
});
});
</script>
<form id="feedback" action="" name="feedback" method="post">
<input id="name" name="name" placeholder="name" />
<br />
<input id="surname" name="surname" placeholder="surname" />
<br />
<input id="enquiry" name="enquiry" placeholder="enquiry" />
<br />
<input id="organisation" name="organisation" placeholder="organisation" />
<br />
<input id="email" name="email" placeholder="email" />
<br />
<textarea id="message" name="message" rows="7" cols="40" placeholder="сообщение"></textarea>
<br />
<button id="send" name="send">send</button>
</form>
You can assign to the onsubmit property:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit

Alert box shows form data when clicking button

I am looking to create a button at the bottom of a form that will create an alert box that will show the form data entered. Form includes:
First Name
Last Name
Address 1
Address 2
City
State
Zip
Phone
Fax
Once the form is completed, the button is clicked and an alert box pops up showing the form data entered.
Does anyone know how to accomplish without the form actually being submitted or validated? There is no database for the form data to be submitted to, so there is no database to pull the information from.
Any help would be greatly appreciated.
I have not included the form code due to its length, but the current code I am working with for the Alert Box looks like this:
<script>
function display_alert()
{
alert("");
}
</script>
<body>
<input type="button" onclick="display_alert()" value="Display alert box">
</body>
If I get it right you need something like this:
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById('send').onclick = function(e){
alert(document.getElementById("name").value);
return false;
}
}
</script>
</head>
<body>
<form method="post">
<input type="text" name="name" id="name" />
<input type="submit" name="send" id="send" value="send" />
</form>
</body>
</html>
I don't really get what you mean with a database to pull the information from, but the example uses a click event to get the data from the form field and shows it in an alert without a submit.
html code:
<html>
<SCRIPT SRC="PR8_4.JS"></SCRIPT>
<body>
<form name=details>
<table>
<tr><td>ENTER FRIST NAME:<input type=text name=fname></td></tr>
<tr><td>ENTER LAST NAME:<input type=text name=lname></td></tr>
<tr><td>ENTER PHONE NUM :<input type=text name=phnum></td></tr>
</table>
<input type="button" value="Click Me" onclick="display();">
</form>
</body>
</html>
javascript code:
function display()
{
var x=document.details.fname.value;
var y=document.details.lname.value;
var z=document.details.phnum.value;
alert("FIRST NAME:"+x+" "+"LAST NAME:"+y+" "+"PHONE NUMBER:"+z);
}
To stop a form submitting you can create an onsubmit event within the tag and return false - e.g. ...form elements.... This has the benefit of working when someone submits the form by pressing the enter key as well as pressing the submit button.
Thus, to achieve what you desire you could create a function (lets call it formAlert) and call it from the onsubmit event e.g. ...form elements...
The formAlert function would look something like:
function formAlert() {
alert_string = '';
alert_string = alert_string + document.getElementById('first_name').value;
alert_string = alert_string + ' ';
alert_string = alert_string + document.getElementById('last_name').value;
alert(alert_string);
}
and this would correspond to a form looking like:
<form id="foo" onsubmit="formAlert(); return false;">
<p><label for="first_name">First Name<label><input type="text" id="first_name" value="fred" /></p>
<p><label for="last_name">Last Name<label><input type="text" id="last_name" value="blogs" /></p>
<p><input type="submit" value="click me" /></p>
</form>
Note1, this won't be a pretty modal box - it'll simply display "fred blogs" in a Javascript alert box.
Note2, if there is a Javascript error your form will still submit (although in the example here it'll submit to itself).
Here is a JS Fiddle demonstrating the above code: http://jsfiddle.net/D59su/
I think this might be what you're looking for:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="javascriptform.css">
</head>
<body>
<form name= "details"><div class="box1"><div id="a"><input type="text" name="lastname" placeholder="LAST NAME"></div><br>
<div id="b"><input type="text" name="firstname" placeholder="FIRST NAME"></div><br>
<div id="c"><input type="e-mail" name="email" placeholder="E-MAIL"></div><br>
<div id="d"><input type="password" name="password" placeholder="PASSWORD"></div><br>
<div id="sub-button"><button onclick="getdetails();">submit</button></div></form>
</div>
<script>
function getdetails()
{
var a = document.forms["details"]["lastname"].value;
var b = document.forms["details"]["firstname"].value;
var c= document.forms["details"]["email"].value;
alert("Your name is "+a+" "+b+". Your e-mail is "+c);
}
</script>
</body>
</html>
It Is Very Simple
Using .value will help.
HTML:
<form onsubmit="return myFunction()>
<input type="text" id="name>
<input type="submit" value="SEND">
Use return before your function
Javascript:
function myFunction () {var name = document.getElementById("name").value; alert("Hi " + name)}
After Submitting It Will Show As (If I Write Alex and Submit It)
Hi Alex
Hope it will work

i am trying to write a simple textbox (for people to type url in it) with a button in html

i am trying to write a simple textbox (for people to type url in it) with a button in html.
when the button is clicked, it will send the url of the current website that I am browsing to the url that is listed in the textbox using the POST method. is it possible?
i have been looking on forums but don't really know which is the right one cos it seems that there are various way of doing it and i don't really know how to edit them.
my current code:
<html>
<head>
<title>YouTube</title>
<script type="javascript/text">
function handleButtonEnterClick(tab) {
//TODO:
var textbox_url = document.getElementById("url_textbox");
var textbox_value = textbox_url.value; //eg. value = "www.google.com"
//Need to have a POST method written here to send the url of the current
//webpage for example www.youtube.com to url listed in the textbox,
//for example www.google.com
//May I know how can I do it? Thanks.
}
</script>
</head>
<body>
<div id ="container">
<p>Enter URL:</p>
<input type="text" id="url_textbox" name="url_textbox" />
<input type="button" id="button_enter" name="button_enter"
value="enter" onclick="handleButtonEnter" />
</div>
</body>
</html>
What you need is a <form> element, which a) has action attribute to indicate where to send the data; b) on submit sends the data (I've added an extra <input type='hidden'> to store your current pages url for sending).
<script type="javascript/text">
function handleButtonEnterClick() {
var textbox_value = document.getElementById("url_textbox").value;
document.getElementById('myUrl').value = window.location;
var form = document.getElementById('myForm');
form.action = textbox_value;
form.submit();
}
</script>
<div id="container">
<form action="" method="post" id="myForm">
<p>Enter URL:</p>
<input type="hidden" id="myUrl" name="url" />
<input type="text" id="url_textbox" name="url_textbox" />
<input type="button" id="button_enter" name="button_enter"
value="enter" onclick="handleButtonEnter" />
</form>
</div>
This should work:
<html>
<head>
<title>YouTube</title>
<script type="javascript/text">
function handleButtonEnterClick(tab)
{
var textbox_url = document.getElementById("url_textbox");
var textbox_value = textbox_url.value; //eg. value = "www.google.com"
//Set the form action to the textbox value
var the_form = document.getElementById("the_form");
the_form.setAttribute("action", textbox_value);
//Set the value of the url field to the current url
document.getElementById("url").setAttribute("value", window.location);
the_form.submit();
}
</script>
</head>
<body>
<div id ="container">
<form action="" method="post" id="the_form">
<p>Enter URL:</p>
<input type="hidden" name="url" id="url" />
<input type="text" id="url_textbox" name="url_textbox" />
<input type="button" id="button_enter" name="button_enter"
value="enter" onclick="handleButtonEnter" />
</form>
</div>
</body>
</html>
The current page location is stored in the JavaScript variable "window.location.href" (thats in Chrome, might be different elsewhere).
You also need to set the action of your form to the URL in the textarea. Suggest you put an id tag on the html form element, and use that id tag to set the action property of the form to the contents of the textbox as part part of the buttons onclick handler.
There are two options:
Use a HTML form, as Ant has shown, set the action and method attributes. Add a submit button inside the form (along with your textbox). When you click on the Submit button, your data will get posted.
Use AJAX to post your form if you want to stay in the current page

Categories