Change HTML Document Title from Form input - javascript

I am trying to change a HTML page's title based on form input. This is needed because the page will be printed as a PDF and we want it to be saved as the customer's name + caller.)
I know the following code will change the document's title.
onClick="document.title = "My new title";
But I'm trying to do something like:
onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;"
Here is an example form:
<form action="">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName" ><br>
<input type="submit" value="Submit" onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;">
</form>

document.title = document.getElementById('customerName').value +' ' + 'Caller' ;

You have quote issues. Also use the submit event instead of click
document.getElementById("form1").addEventListener("submit", function(e) {
e.preventDefault(); // remove if you DO want the form to submit
document.title = document.getElementById("customerName").value + " " + "Caller";
})
<form action="" id="form1">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName"><br>
<input type="submit" value="Submit">
</form>

To give you the answer just try this code and see what i did different :)
let handleSubmit = (event) => {
event.preventDefault()
document.title = document.getElementById("customerName").value + " " + "Caller";
}
<form action="#" onsubmit="handleSubmit(event)">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName"><br>
<input type="submit" value="Submit">
</form>

Related

Form submits but no data present in console

I am trying to make my first form using HTML and JS(vanilla). When I submit the form the console shows the form coming in but as I check through it, there appears to be none of the data i entered into the fields.
I have read through a number of the forum posts on here and other forum sites but most of the are using Jquery, React, or some other framework, I am super new to this and forms are already hard enough.
window.onload = () => {
formID.addEventListener("submit" , (e) =>
{
console.log("form event listener activated");
e.preventDefault();
console.log("default prevented");
console.log("formID: " , e);
myModule.addToTable(e);
});
}
function addToTable(e) {
console.log("e " , e);
console.log("e target " , e.target);
console.log("e target.value " , e.target.value);
console.log("this is a test, line 80 client.js");
}
<form id="FormID" class="FormClass" method='POST' action="#">
<input class="inputClass" type="text" name='Name' placeholder="Name" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Model-Num' placeholder="Model Number" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Current-Stock' placeholder="Current Stock Amount" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Target-Stock' placeholder="Target Stock" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Reorder-Amount' placeholder="Reorder Amount" value=""/> <br/> <br/>
<input type="submit" value="Submit"/>
</form>
Result
under the target area i see
textContent: "↵ ↵ ↵ ↵
or
"↵↵↵↵↵↵↵↵↵↵"
I am of course wanting to get the actual values for my fields that were entered in the text box. Any help is absolutely appreciated.
Remember, I am super new, I do not understand a lot fo the backend DOM but I am trying to learn it.
The reason why it is not working is because you are using formID without even initializing the element to it. Try this instead
document.getElementById("FormID").addEventListener("submit" , (e) => {
//your code here
});
I also noticed that you use myModule in calling addToTable(e) which will cause error(based on that snippet) because myModule is undefined. Just call addToTable(e) directly. Check the working version of your code below
window.onload = () => {
document.getElementById("FormID").addEventListener("submit" , (e) =>
{
console.log("form event listener activated");
e.preventDefault();
console.log("default prevented");
console.log("formID: " , e);
addToTable(e);
});
}
function addToTable(e) {
console.log("e " , e);
console.log("e target " , e.target);
console.log("e target.value " , e.target.value);
console.log("this is a test, line 80 client.js");
}
<form id="FormID" class="FormClass" method='POST' action="#">
<input class="inputClass" type="text" name='Name' placeholder="Name" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Model-Num' placeholder="Model Number" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Current-Stock' placeholder="Current Stock Amount" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Target-Stock' placeholder="Target Stock" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Reorder-Amount' placeholder="Reorder Amount" value=""/> <br/> <br/>
<input type="submit" value="Submit"/>
</form>

Creating multiple elements (input) on button press, within a loop

My goal with this is to have forms that contain a beginning input, and if the '+' button next to it is pressed, it will create another input below it. All of these inputs will eventually be inserted in AJAX.
Right now my form is inside a PHP foreach loop, so I have multiple forms, each with their own set of inputs and buttons.
If I click the '+' button in each form, it will create a new input below, but the way I'm trying to limit each form to 10 inputs, it's going across all forms like this:
So in that image, I clicked the '+' button of the first form 3 times (up to item 4) and then I pressed it in the next form which gave Item 5.
The functionality is basically working here, but I need each form to have it's own inputs, limited to 10. This way if they save items on any form, I can pass only those inputs to AJAX.
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="xyz">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<!-- ticker modal JS -->
<script type="text/javascript">
var maxItems = 1;
function moreItems(button) {
if (maxItems < 10) {
var label = document.createElement("label");
label.id="ItemLabel"+maxItems;
label.innerHTML = "Item "+(maxItems+1)+": ";
var input = document.createElement("input");
input.type='text';
input.name = 'item'+maxItems;
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
//Insert a line break so that the next label and input are on new line
$('<br/>').insertBefore($(button));
maxItems++;
}
}
</script>
You're using a global variable as your counter so it will increment with every use for every form. Why not have the button check what's in the form and do the counting itself? And while you're at it, may as well go full jQuery.
$("button.moreItems_add").on("click", function(e) {
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Items" method="post">
<label class="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="xyz">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
Also you were naming your text inputs sequentially, which I assume was a mistake?
Here's a solution after a couple modifications to your code.
function moreItems(button) {
var maxItems = Number(button.attributes.cnt.value);
maxItems += 1;
button.setAttribute("cnt", maxItems);
if (maxItems < 10) {
var label = document.createElement("label");
label.id = "ItemLabel" + maxItems;
label.innerHTML = "Item " + (maxItems + 1) + ": ";
var input = document.createElement("input");
input.type = 'text';
input.name = 'item' + maxItems;
$($(label)).insertBefore($(button));
$($(input)).insertBefore($(button));
$('<br/>').insertBefore($(button));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Items" method="post">
<label id="ItemLabel">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" cnt="0" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<br><br>
<form id="Items" method="post">
<label id="ItemLabel2">Item 1:</label>
<input type="text" name="Items[]"><br/>
<button type="button" cnt="0" class="moreItems_add" onclick="moreItems(this);">+</button>
<input type="hidden" name="tickerID" id="tickerID2">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
Changes made:
add a custom attribute to each + button, in here cnt="0".
in moreItems() function, increment value of cnt of respective form's + button.

Add multiple fields to form

I would like to add a function that generates multiple fields to my form.
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
How can I do this?
https://jsfiddle.net/374cxt5s/
Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.
I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.
CodePen Example
http://codepen.io/anon/pen/yeVRgw
The Basic HTML Setup
So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1
<form action="form_sent.php" method="POST">
<input type="hidden" name="contacts" id="contacts" value="1">
<div class="form-contacts-container">
<div class="form-contact" id="form-contact-1">
<input type="text" name="name-1" id="name-1" placeholder="Name">
<input type="text" name="email-1" id="email-1" placeholder="E-mail">
<input type="text" name="phone-1" id="phone-1" placeholder="Phone">
</div>
<!-- We'll be adding additional inputs here -->
</div>
<div class="form-contacts-add">
<input type="button" value="Add More Fields" id="add-fields">
</div>
<div class="form-contacts-submit">
<input type="submit" name="submit" id="submit" value="Submit">
</div>
</form>
The JavaScript
This assumes you are using jQuery, so ensure that this is in your <head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.
<script type="text/javascript">
var total = 1; // Our default for how many contacts we have
$( document ).on( 'click', '#add-fields', function() {
var addBlockId = total = total + 1;
var addBlock = document.createElement('div');
$(addBlock).addClass('form-contact');
$(addBlock).attr('id','form-contact-' + addBlockId);
var inputName = document.createElement('input');
$(inputName).attr('type','text');
$(inputName).attr('name','name-' + addBlockId);
$(inputName).attr('id','name-' + addBlockId);
$(inputName).attr('placeholder','Name');
$(inputName).appendTo($(addBlock));
var inputEmail = document.createElement('input');
$(inputEmail).attr('type','text');
$(inputEmail).attr('name','email-' + addBlockId);
$(inputEmail).attr('id','email-' + addBlockId);
$(inputEmail).attr('placeholder','E-mail');
$(inputEmail).appendTo($(addBlock));
var inputPhone = document.createElement('input');
$(inputPhone).attr('type','text');
$(inputPhone).attr('name','phone-' + addBlockId);
$(inputPhone).attr('id','phone-' + addBlockId);
$(inputPhone).attr('placeholder','Phone');
$(inputPhone).appendTo($(addBlock));
$(addBlock).appendTo($('.form-contacts-container'));
$('#contacts').val(total);
});
</script>
Processing your Form
The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:
$total = $_POST['contacts'];
$contacts = array();
for( $i = 1; $i < $total; $i++ ) {
$this_contact = $array(
'Name' => $_POST['name-' . $i],
'Email' => $_POST['email-' . $i],
'Phone' => $_POST['phone-' . $i]
);
array_push($contacts, $this_contact);
}
var_dump( $contacts );
try something like this :
(function() {
var button=document.getElementById("add-user");
button.addEventListener('click', function(event) {
event.preventDefault();
var cln = document.getElementsByClassName("user")[0].cloneNode(true);
document.getElementById("users").insertBefore(cln,this);
return false;
});
})();
<form id="users" action="form_sent.php" method="post">
<div class="user">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id='add-user'>Add more fields</button><br><br>
<input type="submit">
</form>
https://jsfiddle.net/9955n4fo/
It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html
<form action="form_sent.php" method="post">
<div id="fields">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
and then your javascript can be completed as so
$(function() {
$('button').click(function() { addFields(); });
});
function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
<input name='phone' type='text' placeholder='Phone'><br>
<input name='email' type='text' placeholder='E-Mail'><br><br>";
$('#fields').append(html);
}
You need to implement jQuery to change the HTMLs DOM.
So, you add this in your <head></head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
You need to modify your HTML like this:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>
Then you need to use this jQuery code:
<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>
This is the end!! :)
Try This :
Jquery append() function seems to sort out your answer
HTML Code should be as follow :
<form action="form_sent.php" method="post">
<div class = 'xyz'>
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
you JS should be as follow :
$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});
This is how I would solve it.
HTML:
<form action="form_sent.php" method="post">
<div id="inputHolder">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id="addMoreFields">Add more fields</button><br><br>
<input type="submit">
</form>
JS:
$( document ).ready(function() {
$("#addMoreFields").click(function(event) {
event.preventDefault();
$("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
$("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
$("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
});
});
https://jsfiddle.net/r71odb7t/
First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.
$(function() {
var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
$('form > button').on('click', function(e) {
e.preventDefault();
$(this).before(inputs.clone());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>

How to submit form using JavaScript and redirect to a URL?

How to submit form using JavaScript and redirect to a URL ?
<form name="f1" method="get" action="aaa.php">
name : <input type="text" name="value_1" value=""/><br>
age: <input type="text" name="value_2" value=""/>
<input type="submit" name="submit" value="send"/>
</form>
please see image in this link:
http://image.ohozaa.com/i/4d0/zCzQIH.jpg
after press submit button , i want to redirect page to www.example.com/aaa/robert/21
How can i do that ?
Try this with html code
<form name="f1" method="get" action="aaa.php">
name : <input type="text" id="value_1" name="value_1" value=""/><br>
age: <input type="text" id="value_2" name="value_2" value=""/>
<input type="button" name="submit" onclick="checkredirect()" value="send"/>
And javascript
<script type="text/javascript">
function checkredirect(){
var value_1 = $('#value_1').val();
var value_2 = $('#value_2').val();
window.location = 'http://www.example.com/'+value_1+'/'+value_2;
return false;
}
</script>
Don't forget to add jQuery library
Maybe something like this:
HTML:
<form id="f1" class="js-redirect" method="get" action="aaa.php">
name : <input type="text" name="value_1" id="value_1" value=""/><br>
age: <input type="text" name="value_2" id="value_2" value=""/>
<input type="submit" name="submit" value="send"/>
</form>
N.B.: name attribute in form tags is deprecated, use id attribute. Input, select and textarea tags should have ids as well.
JS:
$('.js-redirect').on('submit', function() {
var newUrl = this.action.replace('.php', '/' + $('#value_1').val() + '/' + $('#value_2').val());
this.action = newUrl;
})
set header in php file
$dynamic = $_GET['value_1'];
$id =$_GET['value_2'];
header('location:www.example.com/aaa/'.$dynamic.'/'.$id);
Try this function on click button
function myFunction() {
document.getElementById("myForm").submit();
}

name of uploaded file in title field

I have seen on youtube when we upload any videos automatically, the title field of form gets filled with the name of the video file. How can i achieve this?
my form is
<form enctype="multipart/form-data" method="post" action="http://youshare.ca/music/writestorypost"><p>
<span class="form_label">Title</span><input type="text" value="" name="title" style="width:400px" class="inputText required"></p>
<p><label>Upload</label><input type="file" name="song">
<p><input type="submit" value="Submit" class="button"></p><input type="hidden" value="935" name="page_id">
</form>
Here's some jquery code to make it work:
$('#myfile').change( function(){
var fileValue = $(this).val();
$('#mytitle').val(fileValue);
});
And here's the modified HTML:
<form enctype="multipart/form-data" method="post" action="http://youshare.ca/music/writestorypost"><p>
<span class="form_label">Title</span><input id="mytitle" type="text" value="" name="title" style="width:400px" class="inputText required"></p>
<p><label>Upload</label><input id="myfile" type="file" name="song">
<p><input type="submit" value="Submit" class="button"></p><input type="hidden" value="935" name="page_id">
</form>
Click here for the working JSFiddle. If you've never used jQuery before, then tell me, as this may be confusing!
Edit: Here's the replacing code:
$('#myfile').change( function(){
var fileValue = $(this).val();
fileValue = fileValue.replace('_', ' ');
fileValue = fileValue.replace('-', ' ');
$('#mytitle').val(fileValue);
});
Here's the updated jsfiddle
Use this code:
//use this in your form tag
<input id="song" type="file" />
//use this in your destination(action)
document.title = document.getElementById("song").value ;

Categories

Resources