Specify first character of input - javascript

I have an input where I want the first character to be #.
That means if the user writes something, it automatically adds the #, or better, the # is already present in the input.
How do I do that? I thought i could do that with jQuery mask but I couldn't make it work.

Here is the code,
$("#your-input-id").keypress(function(e) {
if (e.keyCode != 8) {
var text = this.value;
if (text.length == 0) {
this.value = text + '#';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="#">
<input id="your-input-id" type="text" placeholder="Type a text here..." data-prefix="#" />
</form>
Hope this will work.
This will append # when you will start typing, and it will append everything later to #.
EDIT
$("#your-input-value").keydown(function(e) {
var cur_val=$(this).val();
var field=this;
setTimeout(function () {
if(field.value.indexOf('#') !== 0) {
$(field).val(cur_val);
}
}, 1);
});

See this solution http://codepen.io/bachors/pen/yeJOrg
Running example to meet your needs:
/***********************************************
* #### jQuery Prefix Input ####
* Coded by Ican Bachors 2015.
* http://ibacor.com/labs/jquery-prefix-input/
* Updates will be posted to this site.
***********************************************/
$(".yourClass").focus(function(){var a=$(this).data("prefix"),ibacor_currentId=$(this).attr('id'),ibacor_val=$(this).val();if(ibacor_val==''){$(this).val(a)}ibacor_fi(a.replace('ibacorat',''),ibacor_currentId);return false});function ibacor_fi(d,e){$('#'+e).keydown(function(c){setTimeout(function(){var a=bcr_riplis($('#'+e).val()),qq=bcr_riplis(d),ibacor_jumlah=qq.length,ibacor_cek=a.substring(0,ibacor_jumlah);if(a.match(new RegExp(qq))&&ibacor_cek==qq){$('#'+e).val(bcr_unriplis(a))}else{if(c.key=='Control'||c.key=='Backspace'||c.key=='Del'){$('#'+e).val(bcr_unriplis(qq))}else{var b=bcr_unriplis(qq)+c.key;$('#'+e).val(b.replace("undefined",""))}}},50)})}function bcr_riplis(a){var f=['+','$','^','*','?'];var r=['ibacorat','ibacordolar','ibacorhalis','ibacorkali','ibacortanya'];$.each(f,function(i,v){a=a.replace(f[i],r[i])});return a}function bcr_unriplis(a){var f=['+','$','^','*','?'];var r=['ibacorat','ibacordolar','ibacorhalis','ibacorkali','ibacortanya'];$.each(f,function(i,v){a=a.replace(r[i],f[i])});return a}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="#">
<input id="yourInput" class="yourClass" type="text" placeholder="Type a text here..." data-prefix="#" />
</form>

You can try this,
HTML
<input type="text" class="txtUrl" />
Javascript
$('.txtContent').keydown(function(e) {
var cur_val = $(this).val();
if(cur_val.length == 0) {
$(this).val('#' + cur_val);
}
});
Here is the working fiddle: http://jsfiddle.net/jMH9b/43/
Hope this helps!

As you stated, if there is already a SLASH it should not do anything. Here is the solution
$('#description').bind('input', function(event){
var currentVal = $(this).val();
$(this).val(currentVal.indexOf('#') !== 0 ? ('#' + currentVal) : currentVal)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label name="description">Enter some text</label>
<input type="text" id="description" name="description">

<input id='e' onKeyup='test(this)' value='#'/>
var input = document.getElementById('e');
function test(e){
input.value = e.value.charAt(0) !== '#' ? input.value = '#' + e.value : e.value
}
hope this helps...

Related

jQuery keyup - multiple inputs and pass id name?

I've got a number of input id's in a form as follows (example, not complete form) This is for a Chrome Extension so I cannot modify the form.
<form>
<input id="data-draft-brand-name" />
<input id="data-draft-name-en-us" />
<input id="data-draft-bullet-points-bullet1-en-us" />
<input id="data-draft-bullet-points-bullet2-en-us" />
<input id="data-draft-description-en-us" />
</form>
What I am doing is using keyup on each on the inputs, and then doing the same thing for each id like so:
$( "#data-draft-description-en-us" ).keyup(function() {
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();
var currentLength = currentVal.length;
currentLength = 2000 - currentLength;
$('#description-count').text(`${currentLength} characters left`);
if(currentVal.indexOf('word') !== -1) {
$('#data-draft-description-en-us').css('border','1px solid red');
$('#data-draft-description-en-us').css('background','red');
} else {
$('#data-draft-description-en-us').css('border','1px solid #a6a6a6');
$('#data-draft-description-en-us').css('background','none');
}
});
As you can see, there will be a lot of repetition. Is there anyway I can pass an array of id's to keyup, and then access the id in the function. Some pseudo code as an example..
$(["#data-draft-brand-name","#data-draft-name-en-us"]).keyup(function(inputID) {
$(inputID).css('border','1px solid red');
}
Here you go with a solution
$("#data-draft-brand-name, #data-draft-name-en-us").keyup(function() {
var id = $(this).attr('id');
$('#' + id).css('border','1px solid red');
});
No need to provide square brackets [], id should be separated by comma.
Here you go with jsfiddle https://jsfiddle.net/tjkah0ck/2/
$( "#data-draft-brand-name, #data-draft-name-en-us" ).keyup(function() {
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();
console.log(currentVal);
var currentLength = currentVal.length;
currentLength = 2000 - currentLength;
$('#description-count').text(`${currentLength} characters left`);
if(currentVal.indexOf('word') !== -1) {
$('#data-draft-description-en-us').css('border','1px solid red');
$('#data-draft-description-en-us').css('background','red');
} else {
$('#data-draft-description-en-us').css('border','1px solid #a6a6a6');
$('#data-draft-description-en-us').css('background','none');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="data-draft-brand-name"/>
<input id="data-draft-name-en-us"/>
<input id="data-draft-bullet-points-bullet1-en-us" />
<input id="data-draft-bullet-points-bullet2-en-us" />
<input id="data-draft-description-en-us" />
</form>
Hope this will help you.
You can use start with selector for attribute, [name^=”value”] [https://api.jquery.com/attribute-starts-with-selector/][1]
If we need to edit your code then it should be below
$( "div[id^='data-draft-'" ).keyup(function() {
var currentInput = $(this);
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();
console.log(currentVal);
var currentLength = currentVal.length;
currentLength = 2000 - currentLength;
$('#description-count').text(`${currentLength} characters left`);
if(currentVal.indexOf('word') !== -1) {
currentInput.css('border','1px solid red');
currentInput.css('background','red');
} else {
currentInput.css('border','1px solid #a6a6a6');
currentInput.css('background','none');
}
});
Enjoy
To realize what you want, you should use a class to define which input will have a keyup event handler.
Also, you can retreive the id of the current input by calling attr("id").
So you'll have a code like this:
$(document).ready(function(){
$(".keupinput").keyup(function(event) {
var inputid = $(this).attr("id");
console.log("I'm the " + inputid + " input.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="keupinput" id="data-draft-brand-name" />
<input class="keupinput" id="data-draft-name-en-us" />
<input class="keupinput" id="data-draft-bullet-points-bullet1-en-us" />
<input class="keupinput" id="data-draft-bullet-points-bullet2-en-us" />
<input class="keupinput" id="data-draft-description-en-us" />
</form>

Update placeholder by id using jQuery

I have an input field in html which is created 'dynamically' in a function say :
'<input id="id1'+var1+'" name="id1" type="text" placeholder="Provide IP"/>'
In the same function in javascript, I'm trying to change the placeholder text by :
$("#id1"+var1).attr("placeholder",arr[i]);
It doesn't work!!The array arr also gets updated in the function
Also further options like :
$("#id1"+var1).attr("placeholder",arr[i]).blur();
$("#id1"+var1).attr("placeholder",arr[i]).placeholder();
$("#id1"+var1).attr("placeholder",arr[i]).val("").focus().blur();
doesn't work. It is retaining previous placeholder text only!! How to resolve this? I'm using Google Chrome
Your are missing to do the change after the dom is loaded. Try this:
$(document).ready(function(){
$("#id1").attr("placeholder","IP changed");
})
$(document).ready(function() {
var i = 0;
var j = i - 1
var myArray = ["firts text", "second text", "and so on"]
$("#button").click(function() {
if (i > 2) {
i = 0;
}
$('input').each(function() {
if ($(this).attr('placeholder') == "Provide IP" || $(this).attr('placeholder') == myArray[j]) {
$(this).attr("placeholder", myArray[i]);
return false;
}
})
i++;
j++;
if (j > 2) {
j = i - 1;
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" name="id1" type="text" placeholder="Provide IP" />
<input type="button" id="button" value="Click me" />
<input id="id1"+var1 name="id1" type="text" placeholder="Provide IP"/>
you have the " in the wrong place on id.

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

Dynamic Form Input Based on Anchor Value

I have the following snippets that open a single Modal Form:
<a class="modalbox" id="foo" href="#inline">Request a Quote</a>
<a class="modalbox" id="bar" href="#inline">Request a Quote</a>
...and so on...
Somehow, I need to render the value of ID in the input "sub" in the following HTML form
as well as concatenate the ID with some predetermined text, which is "I am interested in..."
<form id="contact" name="contact" action="#" method="post">
<input type="hidden" id="product" name="product" value="">
<label for="sub">Subject:</label>
<input type="sub" id="sub" name="sub" class="txt" value="I am interested in '$id'">
<button id="send">Submit</button>
I'm already using Javascript for verification and AJAX for processing to PHP script.
Edit:
This is the Javascript already being used to populate the hidden input above, which is working perfectly:
$('a').click(function(e) {
$('#product').val($(this).attr('id'));
I'd suggest, with plain JavaScript, something like:
function addTextToInput(from, to, prefix, e) {
e = e || window.event;
if (!from || !to) {
return false;
}
else {
from = from.nodeType == 1 ? from : document.getElementById(from);
to = to.nodeType == 1 ? to : document.getElementById(to);
var text = from.id;
to.value = prefix ? prefix + ' ' + text : text;
}
}
var as = document.querySelectorAll('a.modalbox');
for (var i = 0, len = as.length; i<len; i++) {
as[i].onclick = function(e) {
addTextToInput(this, 'sub', 'I am interested in', e);
};
}​
JS Fiddle demo.
But given that you already seem to be using jQuery:
$('a.modalbox').click(function(e){
e.preventDefault();
$('#sub').val('I am interested in ' + this.id);
});
JS Fiddle demo.

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources