Adding a br tag on Enter - javascript

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');
}
});

Related

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

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();

how do i trigger search with the enter key

i need to trigger search with the enter key but its not working, this is the code i used. any help will be appreciated.
$('#header input[name=\'search\']').bind('click', function(e) {
if (e.keyCode == 13) {
url = $('base').attr('href') + 'index.php?route=product/search';
var search = $('input[name=\'search\']').attr('value');
if (search) {
url += '&search=' + encodeURIComponent(search);
}
location = url;
}
});
you most likely want to catch the keyup event and not click
$('#header input[name=\'search\']').bind('keyup', function(e) {
if (e.keyCode == 13) {
console.log("FOOOOOO");
url = $('base').attr('href') + 'index.php?route=product/search';
var search = $('input[name=\'search\']').attr('value');
if (search) {
url += '&search=' + encodeURIComponent(search);
}
console.log("url: "+url);
window.location.href = url;
}
});
i dont know what youre try to achive but i would code this selector :
$('#header input[name="search"]')...
updated
//
$('input[name="search"]').bind("enterKey",function(e){
console.log("yeah i just triggered");
});
$('input[name="search"]').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
If it's possible, you'd better use
<input type="submit" value="">
wrap inputs into a <form>
and stylize button
input[type='submit'] {height: 0; width: 0; overflow: hidden;}
If you need to change action url in javascript, use something like
$('form').submit ( function() {
$(this).attr('action','/route-to-submit');
})

JAVASCRIPT - intercepting keycode 13 (enter) in dynamically-created editbox and passing element to different function

Ok..I've been working all day on a demo CRUD app learning some Bootstrap and JS basics...
I've almost got what I want but the last thing is I need it to do is while in the editbox to grab the keycode 13 event (enter) and so send the right class to a function that already works..
it all goes something like this...
$(function() {
...
...
$(document).on("blur", "input#editbox", function(){ saveEditable(this) });
});
function saveEditable(element) {
$('#indicator').show();
var User = new Object();
User.id = $('.current').attr('user_id');
User.field = $('.current').attr('field');
User.newvalue = $(element).val();
var userJson = JSON.stringify(User);
$.post('Controller.php',
{
action: 'update_field_data',
user: userJson
},
function(data, textStatus) {
$('td.current').html($(element).val());
$('.current').removeClass('current');
$('#indicator').hide();
},
"json"
);
}
function makeEditable(element) {
$(element).html('<input id="editbox" size="'+ $(element).text().length +'" type="text" value="'+ $(element).text() +'" onkeypress="return checkForEnter(event)">');
$('#editbox').focus();
$(element).addClass('current');
}
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e);
return false;
}
}
It works pretty good on the blur event firing but just isn't quite there for ENTER
here is the link...just Load the table and see http://markenriquez.tekcities.com/credapp
advTHNAKSance
You are passing event as argument to saveEditable() method from checkForEnter(). Wherein you should pass input field reference instead.
Try this,
function checkForEnter(e){
if (e.keyCode == 13) {
saveEditable(e.target);
return false;
}
}
Hope this helps.
$(window).on("keypress", "input#editbox",function(e){
if(e.keyCode == 13){
do_something();
}
});
PS. Your textarea top-left and bottom-left corners are rounded.

Why is the val I'm adding to an unordered list vanishing right after I add it?

I've got a "text box" whose contents I want to send to an unordered list when the user mashes the "Enter" key:
HTML
<input type="text" name="InputUPC" id="InputUPC" />
<ul id="CandidateUPCs" name="CandidateUPCs" class="ulUPCs"></ul>
CSS
.ulUPCs {
min-height:160px;
height:auto !important;
height:160px;
max-width:344px;
width:auto !important;
width:344px;
border-style:solid;
border-width:2px;
}
jQuery
$('#InputUPC').keypress(function (event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var upcPrefix = jQuery.trim($("#InputUPC").val());
if (upcPrefix != "") {
$("#CandidateUPCs").append('<li>' + upcPrefix + '</li>');
}
$("#InputUPC").val("");
}
});
When I enter something into "InputUPC" and mash the key, the value appears in the unordered list, but only for a "brief second" then it disappears. The value in "InputUPC" also disappears, but that is as expected. Why is it also vacating the UL premesis?
UPDATE
This is what I've ended up with (http://jsfiddle.net/AEy9x/), based primarily on adeneo's answer:
$('#InputUPC').keyup(function (event) {
event.preventDefault();
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var upcPrefix = jQuery.trim($("#InputUPC").val());
if (upcPrefix != "") {
$("#CandidateUPCs").append('<label for=' + upcPrefix + '>' + upcPrefix + ' </label>');
$("#CandidateUPCs").append('<input type=\"checkbox\" name=' + upcPrefix + ' id=' + upcPrefix + ' />');
$("#CandidateUPCs").append('<br>');
}
$("#InputUPC").val("");
}
});
UPDATE 2
In jsfiddle, this works as long as the jquery version is above 1.6.4.
That being the case, I updated my project to jquery 1.9.1 (it had been referencing version 1.4.4 in one place, and 1.6.2 in all other places). However, it still does not work...?!?
I see the val in the UL for a "flash," but then it's gone again.
Note: I also updated the jquery-ui:
#* <script src="#Url.Content("~/Scripts/jquery-ui-1.8.16.custom.min.js")" type="text/javascript"> </script>*#
<script src="#Url.Content("http://code.jquery.com/ui/1.10.3/jquery-ui.js")" type="text/javascript"> </script>
UPDATE 3
#sriniris:
The same thing happens with either block of code (mine is first; adeneo's is second), namely, the UL is populated for a nanosecond, but then the flighty bits skedaddle quicker than greased and polished lightning:
$('#InputUPC').keyup(function (event) {
event.preventDefault();
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var upcPrefix = jQuery.trim($("#InputUPC").val());
if (upcPrefix != "") {
$("#CandidateUPCs").append('<label for=' + upcPrefix + '>' + upcPrefix + ' </label>');
$("#CandidateUPCs").append('<input type=\"checkbox\" name=' + upcPrefix + ' id=' + upcPrefix + ' />');
$("#CandidateUPCs").append('<br>');
}
$("#InputUPC").val("");
}
});
$('#InputUPC').on('keyup', function(e) {
e.preventDefault();
if (e.which == 13) {
var upcPrefix = $.trim( this.value );
if (upcPrefix != "") {
var upcElem = $('<li />', {text : upcPrefix});
$("#CandidateUPCs").append(upcElem);
}
this.value = "";
}
UPDATE 4
The problem is that the form is being submitted, even though there is code to prevent that (preventDefault). I know this because when I select a slew of checkboxes, they all go deselected at the same time that the value briefly entered into the UL also goes bye-bye. So is there something analagous to this mixture of "metaphors":
e.preventDefault(); ! important
?
UPDATE 5
I still have the same problem with this:
$('#InputUPC').keyup(function (event) {
if (event.stopPropagation) { // W3C/addEventListener()
event.stopPropagation();
} else { // Older IE.
event.cancelBubble = true;
}
event.preventDefault();
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
//alert('get the values that start with what was entered and place it in ulUPCStartsWith');
var upcPrefix = jQuery.trim($("#InputUPC").val());
if (upcPrefix != "") {
$("#CandidateUPCs").append('<label for=' + upcPrefix + '>' + upcPrefix + ' </label>');
$("#CandidateUPCs").append('<input type=\"checkbox\" name=' + upcPrefix + ' id=' + upcPrefix + ' />');
$("#CandidateUPCs").append('<br>');
}
$("#InputUPC").val("");
}
});
$('#InputUPC').on('keyup', function(e) {
e.preventDefault();
if (e.which == 13) {
var upcPrefix = $.trim( this.value );
if (upcPrefix != "") {
var upcElem = $('<li />', {text : upcPrefix});
$("#CandidateUPCs").append(upcElem);
}
this.value = "";
}
});
The code as in the question works fine, however I imagine that in your actual code the input is inside a form.
Thus, hitting the enter key is very likely submitting the form (see ยง4.10.22.2 "Implicit submission" in the spec). What you are seeing is not a script/logic error that is clearing the ul; you are seeing the page reloading.
You can fix this by adding: [event object].preventDefault();
Examples:
Undesirable submission
Fixed
Adeneo's solution is the right one. But if you want to get it to work without upgrading to jQuery 1.9, you can always use the "bind" event instead of "on". On is supported from v1.7 onwards and replaces bind in the newer versions.
$('#InputUPC').bind('keyup', function(e) {
UPDATE 4 The problem is that the form is being submitted, even though
there is code to prevent that (preventDefault). I know this because
when I select a slew of checkboxes, they all go deselected at the same
time that the value briefly entered into the UL also goes bye-bye. So
is there something analagous to this mixture of "metaphors":
e.preventDefault(); ! important?
Your issue may be caused by event bubbling. Try adding this code before event.preventDefault();
if (event.stopPropagation) { // W3C/addEventListener()
event.stopPropagation();
} else { // Older IE.
event.cancelBubble = true;
}

How to edit and update <td> value when double click Jquery

I have written my code such that when user double clicks on a <td> element I am:
appending am <input> of type="text"
adding a value to it and update it if the user clicks on enter
Here is the my problem:
If user double clicks on <td> and clicks on another <td> without pressing enter, I need the initial <td>'s <input> to be reset to previous value.
// Selecting the table <th> odd elements
$("#div table td").dblclick(function(){
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
function updateVal(currentEle, value)
{
$(currentEle).html('<input class="thVal" type="text" value="'+value+'" />');
$(".thVal").focus();
$(".thVal").keyup(function(event){
if(event.keyCode == 13){
$(currentEle).html($(".thVal").val().trim());
}
});
$('body').not(".thVal").click(function(){
if(('.thVal').length != 0)
{
$(currentEle).html($(".thVal").val().trim());
}
});
}
Please help me.
I don't want to use jeditable datatable.
Here in your case you need .stopPropagation(): http://jsfiddle.net/jFycy/
$(function () {
$("#div table td").dblclick(function (e) {
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function () { // you can use $('html')
$(currentEle).html($(".thVal").val().trim());
});
}
Instead doing click on body do the event on document or html which is the parent elem of all others elems.
Fixed the last answer. by checking who triggered the event i can prevent the double click issue on the input.
Also, with the .off('click') you dont have the problem where every td you updated before changes with the last one.
$(function () {
$(".inner").dblclick(function (e) {
if($(event.target).attr('class')!="thVal")
{
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
}
});
});
function updateVal(currentEle, value) {
$(document).off('click');
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
}
});
$(document).click(function () {
if($(event.target).attr('class')!="thVal")
{
$(currentEle).html($(".thVal").val());
$(document).off('click');
}
});
}
I know its an old topic... but the answer that posted here didnt worked well because of the click event on the input, I took the answer and modified it
$(".daily-signals > tbody > tr > td").dblclick(function (e) {
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
console.log('fire!');
updateVal(currentEle, value);
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
var thVal = $(".thVal");
thVal.focus();
thVal.keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html(thVal.val());
save(thVal.val());
}
});
thVal.focusout(function () {
$(currentEle).html(thVal.val().trim());
return save(thVal.val()); // <---- Added missing semi-colon
});
}
function save(value) {
console.log(value);
}
the save function will make the ajax request

Categories