appent text to input field - javascript

Is there any way to append a text to input field?
So lets say instead of:
<input type="text" id="val" name="val" value="http://" style="width: 140px;" />
with "http://" already written, have a "http://" added automatically when someone types an address, and if someone types full url "http://www.****.com" the http should not be added so it's not doubled.
Any one has any ideas? I can't use php.

Why not just add the http:// if it is missing?
var input = document.getElementById('val').value;
if (input.search('http://') === -1) {
input = 'http://' + input;
}
edit: if you need to allow https also, change the search to a regex:
if (input.search(/https?:\/\//) === -1) {
http://jsfiddle.net/jbabey/Bt67X/

I strongly suggest using a scripting framework, e.g. jQuery (http://jquery.com) to access the input field.
See here:
http://jsfiddle.net/5BLrU/
Here is the JS code for reference
$(function() {
$("#some-form").submit(function(){
var $val = $("#val");
var url = $val.val();
if (!/^http:\/\/.+/.test(url)) {
$val.val("http://" + url);
}
// remove this to submit the form!
return false;
});
});

The following example assumes the ID of the target element is val.
// Store current element
var elem = document.getElementById('val'),
// Store current value
currentValue = elem.value;
// Prepend something if not present
if (currentValue.match(/^http:\/\//) == false) {
currentValue = 'http://' + currentValue;
}
// Re-assign
elem.value = currentValue;

Append:
document.getElementById('val').value += "http://www.google.co.uk";
Remove Duplicate:`
document.getElementById('val').value.replace("http://http://","http://");
This way, if they did type http:// twice, it would just remove it.

Related

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

Initials field in HTML form,

For a project i need a initial textfield which use the every first letter of a forname and bornnames. So basically the field needs to autoformat the input by user. If i fill in my initials MGJ it needs to be M.G.J. (after every letter he must put in the point).
Be aware;
The webform made with Webform module Drupal, so i only could use css or Javascript.
Are there some easy option for that?
Regards,
Martijn
http://nosir.github.io/cleave.js/ you can use this library to format your input the easy way.
Or you can do it like this in JS
var input = document.querySelector('#initials');
input.addEventListener('focusout', function() {
this.value = this.value.split('').join('.');
})
<input type="text" id="initials" />
all you need to do is to split your string and then join with a dot.
string.split('').join('.');
Oke I allready found the solution my own; i used:
`$( document ).ready(function() {
if ($(".input")[0]){
$(".input").focusout(function() {
var initials = this.value.replace(/\./g,'');
this.value = initials.split('').join('.');
});
}
});
})( jQuery );`
Late answer; I needed the same thing but wasn't happy with the current answers.
document.getElementById('initialsOnly').addEventListener('keyup', function(e) {
if (e.code === 'Backspace') {
this.value = this.value.slice(0, -1);
} else {
const newString = this.value.replace(/[\W\d]/g, '').split('').join('.').toUpperCase();
this.value = newString + (newString.length > 0 ? '.' : '');
}
});
<input id="initialsOnly" type="text" />

shorten querystring for searching and many filters

i am building a search function which use many filters. i decide to use the get method instead of post (different reasons). Problem is, when using many filters the querystring gets very long, especially when i use filter with same name so i get
myurl.com?filter1[]=val1&filter1[]=val2&filter2=val
To get better control and to prevent 0 values i tried serializeArray:
var array = {};
jQuery.each(jQuery('form').serializeArray(), function(index,val) {
if (val.value != 0 )
array[value.name] = val.value;
});
But this way it overrides the first filter1 with the last value of filter1, so multiple values doesn´t work. And then i have the "problem" to create the querystring. I am not a javascript prof. so i need a little help here.
What can i do, so i get a querystring which looks like:
myurl.com?filter1=val1|val2&filter2=val and so on
The HTML are "normal" input fields
<input type="checkbox" name="filter1[]" />
<input type="text" name="filter2" />
Thank you in advance
ruven
How about this (working demo):
<form action="search.html">
<input type="text" value="val1" name="filter1" />
<input type="text" value="val2" name="filter1" />
<input type="text" value="val" name="filter2" />
<input type="submit" value="search" name="cmdSearch" />
</form>
​
<script>
// don't do anything until document is ready
$(function() {
// register to form submit event
$('form').submit(function(e){
// stop the form from doing its default action (submit-GET)
e.preventDefault();
// initialise url
var url = '';
// keep track of previously enumerated field
var prev = '';
// iterate all fields in the form except the submit button(s)
$('input:not([type="submit"])', $(this)).each(function(){
// get the name of this field, with null coalesce
var name = $(this).attr('name') || '';
// get the value of this field
var val = $(this).attr('value');
// does this field have the same name as the previous?
if (name.toLowerCase() == prev.toLowerCase()) {
// same name therefore we have already appended the name
// append value separator
url += '|';
}
else {
// different name, track new name
prev = name;
// append parameter separator, parameter name, equals char
url += '&' + name + '=';
}
// append value of this field
url += val;
});
// removing leading ampersand
if (url.length && [0] == '&') {
url = url.substring(1);
}
// insert leading question mark
url = '?' + url;
// insert url from "action" attribute of the form
url = $(this).attr('action') + url;
// display url (delete this line)
alert(url);
// redirect to the new url (simulates the GET)
window.location.href = url;
});
});
</script>

always want to keep first digit of my textfield as 0

hi guys i have a html form where i have a textfield which is having capabilities to enter two digits the first digit is autopopulated to be 0 and i donot want users to change that hows that possible using javascript or jQuery or anything else.
Here is another way.
the onKeyUp might not be how you want it to work but at least you have some ideas
<script>
window.onload=function() {
document.getElementById('part2').focus();
}
</script>
<form onSubmit="this.realvalue.value='0'+document.getElementById('part2').value">
<input type="text" name="realvalue" value="">This can be hidden<br />
<input type="text" style="border-right:0; width:12px" value="0" readonly="readonly" size="1"><input type="text" id="part2" style="border-left:0; width:13px" size="1" maxsize="1"
onKeyUp="this.value=(this.value.length>1)?this.value.substring(-1):this.value">
<input type="submit">
You can use the event "keyup" triggered when the user enters text in the field:
$('#my-input').keyup(function() {
var theInputValue = $(this).val();
// Do whatever you want with the value (like check its length,
// append 0 at the beginning, tell the user not to change first
// character
//
// Set the real value
$(this).val(newValue);
});
You may be better off with a '0' as text in front of a textbox that can only accept a single digit and then prepend the '0' programmatically?
I wrote and tested this code, and works exactly as you expect:
$(function (){
$('#input_id').bind('input',function (){
var val = $(this).val();
var r = val.match(/^[0][0-9]$/g);
if (r !== null){
val = r[0];
if (val.length === 1){
val = '0' + val;
}
}else{
val = '0';
}
$(this).val(val);
});
});
And works for copy/paste too =]

jQuery: How can I add line break to form input?

I'm collecting information in a standard HTML form. I have, for example, <input type="text" name="UserName" id="name"/>. When the form is submitted, I want to add a line break to the value entered. So if the user entered "foo," the form would submit the value "foo\n."
Here's the jQuery function I'm using:
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var newValue = value + " \n";
$(this).val(newValue);
});
});
When the form is submitted, however, the value assigned to the form field does not have the line break.
My goal is for the line break to survive the output of the back-end form processing, which generates an email. Since I don't have control over the script that generates the mail, I'm trying to impose some formatting with what I can control.
Any assistance is appreciated.
I posted my previous answer before I saw your comment that the output is plain text. Now try this:
$(document).ready(function() {
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var myname = $(this).attr('name');
var newValue = value + " \n";
var hid = '<input type="hidden" name="' + myname + '" value="' + newValue + '"/>';
$(this).removeAttr('name');
$("#formID").append(hid);
});
});
});
Previous Answer
As Mark says, the line break character is not rendered as a line break when viewed in the browser (or email client for that matter), so instead of adding a line break character "\n", you should add a <br/>
$("#formID").submit(function () {
$(":text").each(function () {
var value = $(this).val();
var newValue = value + '<br/>';
$(this).val(newValue);
});
})
Textbox doesn't holds "\n" only textarea does. What you can do is post the data yourself to the controller or store the values in hidden fields and submit the form and read the hidden fields in the server, if you don't have much control there match the names to the hidden fields.

Categories

Resources