How to display span value that is newly added via input text - javascript

Am trying to pass span value to a function, but couldn't get value from the span that is being received via input text field.
Below is my code:
HTML
<div id="tags" style="border:none">
<span class="tag" id="4"></span>
<input type="text" id="inptags" value="" placeholder="Add 5 main categories (enter ,)" />
</div>
Javascript
<script type="text/javascript">
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, '');
if (txt) {
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
}
this.value = "";
}).on('keyup', function (e) {
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 5) {
alert('Reached Maximum!');
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
$(this).remove();
document.getElementById('inptags').style.display = 'block';
});
});
</script>
Using above jquery functions, I can enter value in input text and it gets stored as span element. I want to pass the value of the which is being entered on 'enter key' or ',' . How can I do it?
I tried using $(this).innerHTML in keyup event, it doesn't work.
EDIT
In key up event I tried to call a method with the span value as suggested in the answer(trincot) like below:
.on('keyup', function (e) {
if (/(188|13)/.test(e.which)) $(this).focusout();
if (/(188|13)/.test(addnewrow(this.value))) $(this).focusout();
});
function addnewrow(inputtext)
{
alert('New row is : '+inputtext);
}
The problem with this is, as soon as I keyin the input text, alert gets.. how can I get the alert with the span value only after pressing either 'Enter' or ',' ?

You can use keydown event instead of keyup like following.
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, '');
if (txt) {
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
}
this.value = "";
}).on('keydown', function (e) {
if(e.which==13 || e.which==188){
addnewrow($(this).val());
$(this).val('');
return;
}
});
Hope this will help you.

Use this.value like you already do for the focusout handler:
if (/(188|13)/.test(this.value)) $(this).focusout();
You maybe want to improve on that regular expression. If you want to add tags as soon as the user enters a comma, semi-colon, hyphen or space then:
if (/([,;- ])/.test(this.value)) $(this).focusout();
You can extend the list of characters according to your preference.
To respond to the enter key (which does not change the value), you could extend with a test on the keyCode:
if (e.keyCode == 13 || /([,;\- ])/.test(this.value)) $(this).focusout();

Related

not receive negative numbers

I have the following code: http://jsfiddle.net/ntywf/1987/
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
}));
});
});
what I want is to remove the "-" sign off when it is inserted. what happens is that the cursor is always the last decimal home. I just want this code not to let the user enter negative numbers. How can I do this? (the problem is to move the cursor within the input, since it is always sent to the last character)
You can use a KeyCode (Link) to verify what key you pressed, and use replace to remove it:
$('input').keyup(function(e) {
var code = e.keyCode || e.which;
if(code == 109 || code == 189) { //Enter keycode
//Do something
var valor = $(this).val();
$(this).val(valor.replace(/[-]/g, ''))
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
Here what I have tried.
JS
$('input').keyup(function() {
var $th = $(this).val();
$th = $th.replace(/[-]/g, "");
$(this).val($th)
console.log( $(this).val());
});
It will remove - sign from data.
This should solve your problem
What I have done is:
I have used the inbuilt HTML input field method setSelectionRange(), which sets the start and end positions of the current text selection in an element. (From MDN)
MDN Reference : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
JS Code:
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
} ) );
$('input')[0].setSelectionRange(0, 0); //this method sets the range to zero text starting from 0 index to 0 index
});
});
JSFiddle: http://jsfiddle.net/dreamweiver/ntywf/1998/
Use type = "numeric" and min="0" This way you can prevent your text-field from accepting alphabets as well. min=0 will always make sure that it will never accept -ve value.
<input type="number" min="0"/>
JSFIDDLE DEMO will be helpful to you.

Adding a br tag on Enter

How do I add a <br /> tag each time enter is pressed inside a keyup function? I have no clue as to how this should be done.
.on("keyup", ".club", function() {
//detect enter key to add br tags
});
Try this:
.on("keyup", ".club", function(e) {
if (e.keyCode === 13) {
var $this = $(this); // Caching
$this.val($this.val() + '<br />');
// OR
$this.val($this.val() + '\n\r');
}
});

How can I detect if text is paste using right-click

If I paste text using ctrl c and ctrl v on table1(For example on "Apple"), duplicate text on input on table2 still change, but If i paste using right click and paste,duplicate input on table 2 does NOT change. :( Ive created two different event(keyup and change) but nothing seems to work when text is paste using right click. Please see below :
Keypress fiddle demo
$(document).off('keydown').on('keydown', $('#table1 tbody tr td input:eq(0)'), function (e) {
var oldValue =$(e.target).val();//get the input value before keypress or edit
$(document).on('keyup', $('#table1 tbody tr td input'),function(e){
$('#table2').find('td input').each(function(){
if($(this).val() === oldValue){
$(this).val($(e.target).val());
}
$(document).off('keyup');
});
});
});
on change fiddle demo
var oldValue;
$(document).on('keydown', '.main', function (e) {
oldValue = $(this).val();
foo(oldValue);
});
var newValue;
$(document).on('keyup', '.main', function (e) {
newValue = $(this).val();
foo(oldValue);
});
function foo(oldValue) {
$('#table1').find('tbody tr').find('td input').change(function (i) {
var orig = $(this).val();
$('#table2 tbody tr').find('td input').each(function (i) {
if (oldValue == $(this).val()) {
$(this).val(orig);
}
});
});
}
You can count the characters onChange (since you can only enter one character at a time.
Edit:
Why it wasn't working:
on your jsfiddle remember to set onDomReady in the frameworks & extension for the equivalent of $(document).ready(handlerFn)
When you use on('change', handlerFn) or .change(handlerFn) on an input it will fire only after the textbox loses focus ( blur ). The response is not instantaneous like when you use select on your forms. Use bind("input", handlerFn) instead of on(change) for inputs.
The code below will update the matching word on #table2 from the one being edited on #table1. Updating will work for copy-paste CTRL C/V or on mouse copy/paste events. It will also alert if the user copy/paste by comparing the length of the old and new value.
$("#table1 >* input").each(function() {
var elem = $(this),
oldValue;
elem.on('focus', function () {
elem.data('oldVal', elem.val());
elem.data('oldLen', elem.data('oldVal').length);
});
// Look for changes in the value,
// bind 'input' event to the textbox to fire the function
// every time the input changes (paste, delete, type etc.)
elem.bind("input", function(event){
oldValue = elem.data('oldVal');
// update oldVal
elem.data('oldVal', elem.val());
// check if pasted
if (elem.val().length - elem.data('oldLen') > 1 ) {
alert('Most certainly pasted');
}
// update input value length
elem.data('oldLen', elem.data('oldVal').length);
// update #table2
foo(oldValue, elem.val()) ;
});
});
And the function to update #table2
function foo(oldValue, newValue) {
$('#table2')
.find('input')
.each(function (i) {
if (oldValue === $(this).val()) {
$(this).val(newValue);
}
});
}
here's a jsfiddle for you to play with
Check this code, Hope this will help you:
jQuery('#some_text_box').on('input propertychange paste', function() {
var text1 = $('#some_text_box').val();
//alert(text1);
$('#tab2').val(text1);
});
This is your first text box #some_text_box.
<input type='text' value = "Apple" id='some_text_box' />
And this is table 2 text box #tab2
<input type='text' value="Apple" id='tab2'/>
JSFiddle
Ok well this will detect for you if the user uses Ctrl + V etc but thats it. If they right click and paste then you will need another expression to capture that. I left this open by using keydownand keyupso you can capture more variations if needed.
This is jQuery so you will need the library to cover this.
$(document).ready(function()
{
var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67;
$(document).keydown(function(e)
{
if (e.keyCode == ctrlKey) ctrlDown = true;
}).keyup(function(e)
{
if (e.keyCode == ctrlKey) ctrlDown = false;
});
$("#no-copy-paste").keydown(function(e)
{
if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;
});
});
Here is an article on handlers that may be some help to you as well.
http://unixpapa.com/js/key.html
-Epik

Jquery click event works on 2nd click

I'm trying to format the users input in the textarea, where extra spaces and enters are replaced with single spaces fortunately this part works, however only on the 2nd click of the button. I want to know what's wrong and how to fix this:
Here's my code and a fiddle: http://jsfiddle.net/EnXp7/
Html
<textarea type="text" id="address" onfocus="if(this.value===this.defaultValue)this.value=''" onblur="if(this.value==='')this.value=this.defaultValue">
Input Address Here
</textarea>
<input type="button" id="Validate" value="Validate" onClick="valbtn()">
Jquery/Javascript
function valbtn() {
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
});
var x = document.getElementById("address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
}
}
Your current function valbtn() gets called on the first click and binds your validation to click again. So you'll have to click again before actually running that validation.
If you keep calling valbtn() onclick, modify the function like that:
function valbtn() {
// Run it instead of binding it to the click event
$('#address').val($('#address').val().replace(/\s+/g,' '));
var x = document.getElementById("address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
}
}
Because you are assigning a second click handler inside the click function.
Delete the onClick attribute from you HTML and in Javascript replace your current code with just this:
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
});
Change your code to:
<script type="text/javascript">
$(document).ready(function() {
$("#Validate").click(function() {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
var x = document.getElementById("address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
}
});
});
</script>
and totally remove the onclick event in your input:
<input type="button" id="Validate" value="Validate">
With JQuery you dont need that.
You have an action listener in an action listener or in other words you mixed jQuery and JavaScript I suggest you drop the JavaScript call as desribed above and do a pure JQUery action listener which is more clear and easy to use.
It will also take care about browser compatiblity for you.
You should move
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
});
outside of the valbtn function:
$("#Validate").click(function () {
if (valbtn()) {
$('#address').val($('#address').val().replace(/\s+/g, ' '));
}
});
I also made valbtn return boolean indicating if processing is needed or not:
function valbtn() {
var x = $("#address").value;
if (x === "" || x === "Input Address Here") {
alert("No Input");
return false;
}
return true;
}
Updated code: http://jsfiddle.net/EnXp7/1/
Put your jquery script out side valbtn() function. no need create function use only
below code
$("#Validate").click(function () {
$('#address').val($('#address').val().replace(/\s+/g,' '));
});

How do I implement a keyup function with a dynamically create input element with JQuery?

I can not figure out why the following code does not work.
JSFIDDLE LINK
$(document).ready(function () {
addInput();
});
var limit = 30;
function addInput() {
var numberOfRows = $("#shipping tr").size();
var id = numberOfRows;
if (numberOfRows == limit) {
alert("You have reached the limit of adding " + limit + " inputs");
} else {
$('#shipping').append('<tr id="rate' + id + '"></tr>');
$('tr#rate' + id).append('<td></td>');
$('tr#rate' + id).append('<td><input type="text" name="rate" /></td>');
}
$('input[name=rate]').on('keyup', 'input', function () {
alert('YAY');
return false;
});
}
I am trying to assign a keyup function to the inputs that I add dynamically.
Expected output: YAY! inside a popup box
Please help!
Attach an keyup event handler to shipping table, and the event will bubble up from the input[name="rate"] to shipping table:
$('#shipping').on('keyup', 'input[name="rate"]', function () {
alert('YAY');
return false;
});
DEMO
You need to add delegation to document because its added to the document.
Example
$(document).on('keyup', 'input[name="rate"]', function () {
alert('YAY ');
});
Working Demo

Categories