Disable New Line in Textarea when Pressed ENTER - textarea

I am calling a function whenever someone press enter in the textarea. Now I want to disable new line or break when enter is pressed.
So new line should work when shift+enter is pressed. In that case, the function should not be called.
Here is jsfiddle demo:
http://jsfiddle.net/bxAe2/14/

try this
$("textarea").keydown(function(e){
// Enter was pressed without shift key
if (e.keyCode == 13 && !e.shiftKey)
{
// prevent default behavior
e.preventDefault();
}
});
update your fiddle to
$(".Post_Description_Text").keydown(function(e){
if (e.keyCode == 13 && !e.shiftKey)
{
// prevent default behavior
e.preventDefault();
//alert("ok");
return false;
}
});

Below code is to prevent to getting resize the "textarea", avoid scroll bar inside textarea, and also prevent to get into next line when enter key is pressed.
style.css
textarea {height:200px; width:200px;overflow:hidden;resize: none;}
index.html
<textarea></textarea>
Script.js
$("textarea").keydown(function(e){
// Enter pressed
if (e.keyCode == 13)
{
//method to prevent from default behaviour
e.preventDefault();
}
});

React: textarea w/ value and onChange event
const PreventTextAreaEnter = () => {
const [comment, setComment] = useState();
const handleTextArea = (e) => {
console.log({e}) // Destructure to get a more accurate log
// Return if user presses the enter key
if(e.nativeEvent.inputType === "insertLineBreak") return;
setComment(e.target.value);
};
return (
<>
<textarea value={comment} onChange={ (e) => { handleTextArea(e) } />
</>
)
}

$(".Post_Description_Text").keypress(function(event) {
if (event.which == 13) {
alert("Function is Called on Enter");
event.preventDefault(); //Add this line to your code
}
});

For Angular Users
While there are existing working solutions, if anyone comes across this question using Angular, you can disable new lines with the following:
Add <textarea ng-trim="false" ng-model='your.model' ...
In your controller, add:
$scope.$watch('your.model', function(newvalue, oldvalue) {
if (newvalue && newvalue.indexOf('\n') > -1) {
$scope.your.model = oldvalue;
}
});

use the input tag instead of textArea tag in your HTML

Related

How to remove cancel button on alertify prompt?

<SCRIPT LANGUAGE='JavaScript'>
alertify.prompt('Please enter password for authorization', function(evt, value) {
value = md5(value);
if (value != null && value == '$pass') {
alertify
.alert('Success! Shifting to Happy Hour. ', function(){
alertify.message(window.location = `main_2.php`);
});
}else{
alertify
.alert('Invalid Password, Please Try Again.', function(){
alertify.message(window.history.back());
});
}});
</SCRIPT>");
I want to make to prompt to have the text input and ok button only. What will be the easiest way to do this?
The easiest way would be hiding the cancel button. I have added a CSS to hide the Cancel button.
alertify.prompt('Please enter password for authorization', function(evt, value) {
value = md5(value);
if (value != null && value == '$pass') {
alertify
.alert('Success! Shifting to Happy Hour. ', function(){
alertify.message(window.location = `main_2.php`);
});
}else{
alertify
.alert('Invalid Password, Please Try Again.', function(){
alertify.message(window.history.back());
});
}});
.ajs-cancel {
display: none;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.11.1/alertify.min.js'></script>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.11.1/css/alertify.min.css'>

How to put kendo validator message span element underneath the input being validated?

I'm trying to figure this out for a while.
All the examples I saw, use the html with input and span elements manually inserted
I have the following code that generate form and its datepicker elements dynamically:
#using (Html.BeginForm("Reload", "FileDate", FormMethod.Post, new { returnUrl = this.Request.RawUrl, id = "DateForm", onsubmit = "return ValidateDate();" } ))
{
#(Html.Kendo().DatePicker()
.Name("Date")
.Value(Session["FileDate"] == null ? DateTime.Now : Convert.ToDateTime(Session["FileDate"].ToString()))
.Events(e => e
.Change("datepicker_change")
)
)
#Html.Hidden("returnUrl", this.Request.RawUrl)
<script>
function datepicker_change() {
if(ValidateDate()){
$("#DateForm").submit();
}
}
</script>
}
When form is generated, I have the following code on the page:
This is a validation:
<script>
$(document).ready(function() {
$("#mainMenu").kendoMenu();
$("#Date").attr('required', 'required');
$("#Date").attr('data-WrongFormat-msg', 'Date Format is Wrong');
var validator = $("#container").kendoValidator({
rules: {
WrongFormat: function (input) {
if (input.is("[data-role=datepicker]")) {
var dateBox = input.data("kendoDatePicker");
return input.data("kendoDatePicker").value();
} else {
return true;
}
}
}
})
});
function ValidateDate()
{
var validator = $("#container").data("kendoValidator");
if (validator.validate()) {
return true;
}
else
{
return false;
}
}
</script>
When I provide the incorrect input or no input at all, I get the correct message in the span. However, this span section modifies the layout of the page:
How can I fix that, so my error span is placed underneath my form, the way it is shown in some examples like here: http://dojo.telerik.com/ikUfu:
I have the exact same issue. The problems seems to be that the validation message span element is in the wrong place for DatePickers. It is inside this element:
but, in all other widgets, it's inside the spam element one level higher:
So, it seems this is a bug in Telerik at the moment. It works for other widgets, but not for DatePicker. I'll see and find if this bug is already reported, and if not, report it. If you desperately need it fixed asap, I assume you could try some jquery magic to move the span element.
I've faced it too. Is there any proper solution for this issue?
My workaround in a nutshell:
Delete all possible old error messages
Move the new one into the proper HTML container
<div id="div_id">
<input id="input_id" type="text">
</div>
<script>
var validatable = $("[id='input_id'").kendoValidator({
rules: {
minimumLengthRule: function (input) {
var trimmedInputValue = $.trim(input.val());
return trimmedInputValue.length > 0 ;
}
},
messages: {
minimumLengthRule: "The input length is too short."
}
}).data("kendoValidator");
validatable.bind("validateInput", function (e) {
$("#div_id > span").not(':first').remove(); // 1.
if (!e.valid) {
$("[id='input_id_validationMessage'").appendTo('#div_id'); // 2.
}
});
</script>

Is there a way to handle clear event on text input in jquery mobile

I am using a text input with data clear option. Is there a way to handle the clear event so I can perform some cleanup task?
<input type="text" name="txbAppraisalAmount" id="txbAppraisalAmount" value="" data-clear-btn="true" data-mini="true"/>
Attach event to .ui-input-clear.
$(document).on("pagecreate", function () {
$(".ui-input-clear").on("click", function() {
/* do what you want */
});
});
Demo
This will handle a value change including a clear (although not in the midst of a user typing):
$('#textInput').on('change', function() {
/* ... */
});
If you want to handle just a clear, you can check for an empty value within the callback:
$('#textInput').on('change', function() {
if($(this).val() === '') {
/* ... */
}
});
And if you wanted to handle value changes and clears regardless of whether the user is typing:
$('#textInput').on('change input', function() {
if($(this).val() === '') {
/* ... */
}
});

SlickGrid styling after cell edit

I'm using SlickGrid (2.0) dataView with slick.editors. In the Grid, a user can edit any number of cells which then modifies the underlying grid data so that the edits are maintained when the grid scrolls. This works great. But I also want to provide visual feedback for all the edits since these are not saved to the database until user hit "Save Edits" button.
Problem is that the editor method resets the cell after it reads back the changed grid data. I need to maintain a background color change to indicate that it's been edited. Has anyone been able to do this?
Here is the relevent code (simple Integer editor):
function IntegerCellEditor(args) {
var $input;
var defaultValue;
var scope = this;
this.init = function() {
$input = $("<input type=text class='edited' type=text style='font:normal 12px arial; width:95px; text-align:right; border:none;' />");
$input.bind("keydown.nav", function(e) {
if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
e.stopImmediatePropagation();
}
});
$('#saveChanges').removeAttr("disabled"); // remove disabled attribute from "Save Changes" btn
$input.appendTo(args.container);
$input.focus().select();
};
this.destroy = function() {
$input.remove();
};
this.focus = function() {
$input.focus();
};
this.loadValue = function(item) {
defaultValue = item[args.column.field];
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function() {
return parseInt($input.val(),10) || 0;
};
this.applyValue = function(item,state) {
item[args.column.field] = state;
};
this.isValueChanged = function() {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
document.getElementsByClassName('ui-widget-content slick-row')[row].className += 'edited';
};
this.validate = function() {
if (isNaN($input.val()))
return {
valid: false,
msg: "Please enter a valid integer"
};
return {
valid: true,
msg: null
};
};
this.init();
}
This line does nothing and I can't figure out how to do this:
document.getElementsByClassName('ui-widget-content slick-row')[row].className += 'edited';
Thanks
I am not an expert in SlickGrid but take a look a Example 14, I think it has similar information that would help you.
My idea would be something like:
subscribe to grid.onCellChange event
store changes in object
use grid.setCellCssStyles('highlight',changes) to update CSS or grid.addCellCssStyles
Hope that helps a little at least.

How to validate select with JQuery.Validate while using JQueryMobile

I'm just exploring the Validate plug-in for JQuery. During implementing in my webapp made with JQueryMobile I stumbled over the fact that validating such an element is not so simple like usual input-elements.
So the Question is: How to enable validation for select?
The trick consists out of two parts:
Validate is by default ignoring :hidden. But that's what JQM does with an <select>: hide it and placing a div-span-wrapper on top. Solution is to redefine the ignore-selector:
{ignore: ":hidden:not(select)"}
To inform the user about the invalid field you have to show the error right on the wrapper:
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput")
And now in an working example:
$.validator.setDefaults({
debug: true,
ignore: ":hidden:not(select)",
submitHandler: function() { alert("submitted!"); },
showErrors: function(map, list) {
$(this.currentElements).each(function() {
if(this.nodeName == "SELECT") {
$(this).closest('.ui-select').removeAttr("title").removeClass("invalidInput");
return true;
}
$(this).removeAttr("title").removeClass("invalidInput");
});
$.each(list, function(index, error) {
if(error.element.nodeName == "SELECT") {
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput");
return true;
}
$(error.element).attr("title", error.message).addClass("invalidInput");
});
}
});
$('div[data-role="page"]').bind('pageinit', function(event) {
var rules = {};
$('input:not(:button)').each(function() {
rules[this.name] = {required:true};
});
$('#fzgherst').each(function() {
// revalidates the select when changed, other elements gets revalidatet onblur
$(this).on('change', function() {$(this).valid();});
rules[this.name] = {required:true};
});
$("form").validate({
rules: rules
});
});
That's all folks!

Resources