how to make an input field add text after submission - javascript

I was wondering if it is possible to have an input field that has a bit of text added to it after the user enters the information they want. EX. a user types youtube.com into a search bar, and the input applies https://www.

You could use an event listener that will change the value of the input field.
Use RegEx to find out if the string (https://www.) has been set before (for instance by copying and pasting the URL).
Here is an example:
document.getElementById('url').addEventListener('keyup', (e) => {
if (!/^(https:\/\/www.)/.test(e.target.value) && e.target.value) {
e.target.value = `https://www.${e.target.value}`;
}
});
<input type="text" id="url">

use blur event
you can run a function after a user leaves the input field
see https://www.w3schools.com/jsref/event_onblur.asp

You need to manipulate the user input for that use javascript. If user presses submit button then don't submit input immediately use event.preventDefault() to stop default action and then change user input if needed after that manually submit it using AJAX.
function manuallySubmit(event){
event.preventDefault();
// manipulate input here
var input = document.getElementById("input").value;
input = "changed value " + input;
console.log(input);
/* AJAX POST request
let xhr = new XMLHttpRequest();
xhr.open('POST','location',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8');
data = 'input='+(input);
xhr.send(data);
*/
// window.location.href="newlocation" if you want to redirect
}
<form onsubmit="manuallySubmit(event)" action='#' method="POST">
<input type="text" name="input" id="input" /><br/>
<input type="submit">
</form>

Related

How to mirror an input field to another input field?

I have an input field and multiple input fields, the original input field is the primary field that gets submitted.
So, I need to mirror one field to the main field.
I tried watching the keyup and change events but when the user pastes with the mouse it does not work, because the event is triggered before the user presses paste and not after it.
I am not sure that this is the best way to mirror two fields, so I am asking you if you have better methods of doing it
Is there an event that can be triggered after the paste is pressed?
Instead of triggering on key/mousevents, you could try using an "input" event on the input element you would like to mirror.
const ogInput = document.getElementById("og")
const mirrorInput = document.getElementById("mirror")
ogInput.addEventListener("input", () => {
mirrorInput.value = ogInput.value
})
<input type="text" id="og" />
<input type="text" id="mirror" />

Populate hidden field with autocomplete value

I have an HTML form with a regular text input and a hidden field.
I also have the following code that will populate the hidden field with the value of the text field either when it is changed, or if the text field has a default value (supplied by the page itself):
$(document).ready(function() {
var emailinput = document.getElementById('emailval');
document.getElementById('usernameval').value = emailinput.value;
emailinput.onkeyup = function() {
document.getElementById('usernameval').value = emailinput.value;
}
emailinput.onblur = function() {
document.getElementById('usernameval').value = emailinput.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="email" id="emailval" />
<input type="hidden" name="username" id="usernameval" />
This works well, except in the case where the browser autofills the text field. If the user submits the form without changing the textfield.
So my question is, is there any way to have the javascript pull the value from the browser-autofilled text field?
Attach an event handler on the form's submit event, and copy the value of #emailval to #usernameval. For example, let's say your form has the ID, #form:
$('#form').submit(function (event) {
'use strict';
$('#usernameval').val($('#emailval').val());
});
Documentation: https://api.jquery.com/submit/
What is 'input7'? I'm assuming this is a key. You could add another event for when the mouse leaves the input box, to get that value, since the user has to use the mouse to select the value.
Another thing you might want to consider, is turn off autocomplete on that field.
https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
You could use the form's onsubmit event. Here's the pseudo code:-
form.onsubmit= function(e){
e.preventDefault();
document.getElementById('usernameval').value = document.getElementById('emailval').value;
this.submit();
}

How to take an input and when the submit button is pressed put it into a variable?

Lets say I got some HTML like this
<input type="text" placeholder="Enter Mineral">
<input type = "submit">
I have no idea how to put what is in the text into a javascript variable when the submit button is pressed. I'll use jQuery if that makes it easier.
Use .val() to fetch the value of the input field.
$("input[type=submit]").click(function(e){
e.preventDefault(); // <-------- To stop form submission
var txt = $("input[type=text]").val(); // <----- Fetch value of input field
console.log(txt) // <----------- Check console has the value of the input field.
});

Disabling "save" button until at least one input field has changed

There are around 20 input fields and a save and a register buttons in a page. How can I enable a "save" button only when something changed in at least one field?
You can use Angularjs form validation:
I suppose you created a form with text inputs.
You can conditionally disable your save button (If the form is prisitine, disable the button):
<input type="submit" ng-disabled="myForm.$pristine" />
Working plunker here.
If you don't need to compare values you can just attach an event handler on key event to all text boxes and enable the save button once the event in any of them is triggered.
If you need to more "sophisticated" feature to allow saving only when some data has really changed (you may for example change "aaa" to "aa" - but then realize you want it back to "aaa") then you need to maintain the original data and compare them against any new changes and then determine whether you enable save button or keep it disabled. In such case you can for example add some sort of "original-data" attribute to your input textboxes which will hold the original value when the page is generated/loaded and on every key change event run the comparer.
Assuming your HTML looks like this:
<input>
<input>
<input>
<button class=save disabled>Save</button>
You can do something like this:
var inputs = document.getElementsByTagName("input");
var enableSave = function() {
document.querySelector("button.save").disabled = false;
for (var i = 0; i < inputs.length; i++) {
inputs[i].removeEventListener("input", enableSave);
}
};
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("input", enableSave);
}
Disabling a button for a form can be done using ng-disabled
<form name="myForm">
Name :
<input type="text" name="Name" required><br>
Age:
<input type="number" name="Age" required><br>
<input type="submit" value="Save" ng-disabled="myForm.$error.required">
here the save button is enabled only when the required fields in the form is satisfied

Ajax form submit after validating input elements

I have a form which collects some information using text boxes. Some text boxes have a strick pattern, e.g. few input boxes take only numbers.
I was able to add validation using pattern attribute of input field. http://www.w3schools.com/tags/att_input_pattern.asp
However, when user submits the form I need to do a ajax post request to a different end point. So, I think I have to make a call to preventDefault() method to prevent default form submit.
But when I call preventDefault(), it also disables validating input fields.
How can I achieve validating fields and make a ajax request, only if the input fields pass the validation.
You can either way use this:
First change the input[type="submit"] to this:
<button onclick="submitThis()">Save</button>
function submitThis() {
var firstInput = $("#idoffirstinput).val(); // basic validation
if(firstInput == "correctinput") {
$.ajax({
// send the ajax form
})
}
}
You can seperately validate each input using the technique provided there, or the one I provided. The jQuery error will be same; I mean the validation.
Use this:
if(firstInput == "correctinput") {
// ajax form
} else {
// show the error popup!
}
The plus point for this one is that you can style the error dialouge popup too. Like
$("#errordiv").css("border", "1px solid #hexcode");
And everything else is same!
HTML and jQuery:
<form id="details">
Phone no: <input type="text" id="phone_no" pattern="[A-Za-z]{3}">
<input type="submit" id="submit">
</form>
var input = $('#phone_no').val();
if(input != '')
{
var YOUR_URL = 'www.example.com';
var formData = $('#details').serialize();// If you want to pass that data to that URL
$.post(YOUR_URL,formData,function(result){
});
}
else
{
return false;
}

Categories