Postprocessing an Knockout.JS input value - javascript

I have a basic input field with a knockout value:
<input type="text" data-bind="value: mytext"/>
However I want to perform som logic to my viewmodel after receiving a value for "mytext".
Initially I thought of some kind of post processing event ala "valueUpdate", but basically I just want to run a function after "enter" og "space" is hit. Do I need to write a new bindingHandler or is there a more straight forward knockout-apropriate way of doing this?
Basically what I´m trying to do is a combination of the jquery/autocomplete/multible and Ryan Niemeyers knockout-sortable example http://jsfiddle.net/rniemeyer/vgXNX .
My is in the div.container after the div.item, replacing the "Add task", like:
<div class="container">
<div class="item" data-bind="sortable:{template:'tagsTmpl',data:myTags, allowDrop:true"></div>
<input data-bind="value: mytext, event: {keypress: handleKey}"/>
<!-- Line above replacing this: Add Tag -->
</div>

basically I just want to run a function after "enter" og "space" is hit.
You could use the event binding.
ko.applyBindings({
mytext: ko.observable("initial value"),
handleKey: function(data, event) {
if (event.keyCode == 0x20) {
console.log("Space has been pressed!");
}
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="value: mytext, event: {keypress: handleKey}" />

Related

( HTML5, JQuery) Attributes of Input elements are ignored by JQuery

In HTML5, when I make a text box like below, and press the submit button.
<input type='number' name ='search_size' id ='search_size' class="" value="" min="0" max="100" >
When the value doesn't meet the min, max value, it will not proceed. However,
My button that handles the text box is made of JQuery. When I type nothing, and click, it processes it. When I type the value over 100, it also processes it. (There are other values from other tags and etc.)
Is there something I can add to JQuery so that it will check the condition or requirement in the text box?
I want to show the JQuery code here, but it is pretty long. Some of it looks like the below.
$("#search_submit").off("click").on("click", function(event_receiver){
$("#loading").css('z-index',-1);
$("#loading_search").css('top',$("#dialog_data_search").position().top + ($("#dialog_data_search").height()*0.7) );
$("#loading_search").show();
var search_data;
var request_obj = {
"baseDN" : $("#search_base_dn").val()
,"filter":$("#search_filter").val()
,"attribute":$("#search_attribute").val()
,"sortAsc":true
,"scope":$(":radio[name='search_scope']:checked").val()
,"size":$("#search_size").val()}; //<-- this guy!!
$.ajax({
url:"/browser/ajaxGetSearchData"
,dataType:"json"
,data:request_obj
,async:true
,type:"post"
,success:function(return_data){
if(return_data.success){
search_data = return_data.result;
}else{
alert(return_data.message);
}
}
you can add a validate function inside the jquery click function of yours. in that validate function the value of the input field must be validated. if it exceeds 100 it should return false
Instead of the <button>'s click event, you want to hook on the <form>'s submit one.
The click event will fire even though the form is invalid, while the submit one will first perform the validation:
document.getElementById('btn').onclick = e => console.log('btn has been clicked');
document.getElementById('form').onsubmit = e => console.log('form has been submitted');
<!-- an always invalid form... -->
<form id="form">
<input name="foo" maxlength="0" required>
<button id='btn'>bar</button>
</form>
Use validation bootstrap like this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form>
<div class="form-group">
<label for="number">Number</label>
<input type="number" class="form-control" name ='search_size' id ='search_size' value="0" min="0" max="100" required>
</div>
<button class="btn" type="submit">submit</button>
</form>

Permit of submitting an input value only when it fulfils a pattern

I want to make a list of items, double-clicking on one item makes it editable. Currently, while editing an item, clicking outside (ie, blur) or enter by keyboard submits the new value.
I want to be able to submit the new change only when it is not empty or fulfil a pattern (eg, a file name with .).
I tried ng-required="true", it did not work.
Does anyone know how to set this restriction?
JSBin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<style>
input {
font-size: 20px;
border:none;
background-color:transparent;
}
</style>
</head>
<body ng-app="app" ng-controller="Ctrl">
<table>
<tr ng-repeat="item in items">
<td>
<input type="text" value="{{item.name}}" ng-blur='eEditable = -1' ng-readonly='$index !== eEditable' ng-dblclick="eEditable = $index" ng-keypress="keypress($event)" ng-required="true"/>
</td>
</tr>
</table>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope', function ($scope) {
$scope.items = [{ name: "item #1" }, { name: "item #2" }, { name: "item #3" }];
$scope.eEditable = -1;
$scope.keypress = function ($event) {
if ($event.keyCode === 13)
$event.target.blur()
}
}])
</script>
</body>
</html>
Edit 1: the existing answers suggest to use form, but I don't want to use form or submit button.
One solution would be verifying the new value in a myBlur function: if the pattern is not satisfied, we could set the focus back to the input field and let users modify the value again. Here is another JSBin.
Does anyone know how to set the focus back to the input field?
Does anyone know how to set the focus back to the input field?
If you are validating the inputs in the ngKeypress event you can use the $event.
If the validation fails, set focus back to the input with
angular.element($event.currentTarget).focus();
use ng-pattern with a regular expression
<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" />
I found this site helpful making regex http://regexr.com/
You could prevent submission by using a <form> with ng-submit, ng-required, and, ng-pattern directives:
<form name="myForm" ng-submit="submitClicked($event, myForm)">
<input type="text" ng-required="true" ng-pattern="/.)/">
<input type="submit">
</form>
$scope.submitClicked = function($event, form) {
if (!form.$valid) {
$event.preventDefault();
}
}

How to run JavaScript on each letter entered in a search/text box field?

I have the following HTML
<form id="project-filter" class="aui ajs-dirty-warning-exempt">
<div class="project-filter-item">
<input type="text" id="project-filter-text" placeholder="Contains text..." class="version-filter- text text" value="">
</div>
</form>
This is a search box (text) field on the page.
I have a JS function that runs every time the page is loaded. The content of a page is like a table (headings and table data). However, the JS function doesn't run properly when something is entered in the Search box.
(Only the heading are executed, and the script doesn't run in the table body)
So I want the JS function to run every time a letter is entered.
For that I have tried to do the following, but its not working.
AJS.$('#project-filter-text').on('input', function() {
// Call my JS function.
setTimeout(removeProjectTypes, 0005);
return true;
});
And this:
AJS.$('#text').keyup(function(event) {
if(AJS.$('#text').val() == true) {
// Call my JS function here
}
});
Any suggestions on what should I do?
You can use the keyup event.
<form id="project-filter" class="aui ajs-dirty-warning-exempt">
<div class="project-filter-item">
<input type="text" id="project-filter-text" placeholder="Contains text..." class="version-filter- text text" value="">
</div>
</form>
$('#project-filter').on('keyup', function() {
console.log('This will run each time :)');
});
Try that :)
you could try
<input type="text" id="project-filter-text" placeholder="Contains text..." class="version-filter- text text" value="" onkeyup="myFunc()">
function myFunc()
{
alert('ok')
}
Use the onkeyup:
<form id="project-filter" class="aui ajs-dirty-warning-exempt">
<div class="project-filter-item">
<input type="text" id="project-filter-text" placeholder="Contains text..." class="version-filter- text text" value="" onkeyup=search()>
</div>
</form>
And add your function into the js file:
function search() {
console.log('run');
}
i don't know what ajs is, but with jquery you can use on method to wait for events
$('#project-filter-tex').on('keyup',function(){
// do something
});
sometimes i had the problem too, that jQuery.keyup() did not work. don't ask me why not.
$('#project-filter-text').keypress(function(e) {
if (e.which !== 0) {
console.log(String.fromCharCode(e.which));
//Logic here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="project-filter" class="aui ajs-dirty-warning-exempt">
<div class="project-filter-item">
<input type="text" id="project-filter-text" placeholder="Contains text..." class="version-filter- text text" value="">
</div>
</form>
If, like me, you need something which triggeres every time a letter is entered, try oninput:
<textarea oninput="console.log(this.value)"></textarea>
keyup doesn't quite work. For example, try this MCVE:
<textarea onkeyup="console.log(this.value)"></textarea>
It works fine, if you just tap each key. But press and hold and you'll hit the issue: This triggers once per time the key is released, not per letter entered.

jquery: Don't get why element selector work or don't work

I have an html document with the following element
<input type="text" style="width: 40px;" name="rate" id="rate" value="1" />
Now I want to use jQuery to run a function once this textfield is changed. But I seem not to understand how the selectors work. Because this example works:
<script>
// works
$(document).on('input', function() {
alert();
});
</script>
But of course it fires on all inputs that are interacted. So I only want a certain id to response:
<script>
// doesn't work
$(document).on('#rate', function() {
alert();
});
</script>
But it doesn't work. Neither does it with class or attributes ("input[name='rate']") nor with 'input#rate' instead of document.
$('input#rate').on(function() {
Why is that?
jQuery included in head is:
<script src="/assets/jquery-1.12.3.min.js"></script>
on() accepts the event name as the first argument.
As there is no event called #rate, the following will not work.
$(document).on('#rate', function() {
Use
$(document).on('keyup', '#rate', function() {
^^^^^^^ : Event name here
on should take event then selector like .on('keydown', '#rate'
Format like:
.on( events [, selector ] [, data ], handler )
so it would be
$(document).on('click', '#rate', function() {
^^^^^
alert();
});
More on Here
input in $(document).on('input', function() { is not a selector.
document is the selector, 'input' is the event type.
If you want to listen for the input event on a specific element, you can pass a selector as the second parameter to .on():
$(document).on('input', '#rate', function() {
// ^^^^^^^
...
});
or you can just select the specific element before binding the callback:
$('#rate').on('input', function () {
...
});
What you have now:
$(document).on('input', function() { } );
means
on every "input" event for any element do something
And if you want to do something only on particular element - pass this element as a selector:
$(document).on('input', "#rate", function() { } );
Here input is an event and #rate is an element selector.
Correct way to make this work is :
//on click
$(document).ready(function(){
$("#rate").click( function () {
alert('Awesome');
})});
for input box
<input type="text" style="width: 40px;" name="rate" id="rate" value="1" />
if you want to target class:
<input type="text" style="width: 40px;" name="rate" value="1" class="rate">
script will be
//on click
$(".rate").click( function () {
alert('Awesome');
})
for further info read :-
jQuery Selectors
I find that when I am confused why a jQuery function isn't properly working the way I expect to consult the API Documentation for jQuery for usage and examples. Specifically for .on() I would reference the documentation page for that function:
http://api.jquery.com/on/
Each event is going to give a different desired outcome. You are wanting to fire off some code when the input is changed. The events used are based on vanilla JavaScript events so in this case your options would include on change, keyup, or keydown.
To decide which event to use for this, to me, it usually comes down to one thing: Does my code need to check the input before it shows in the text field?
You can see in this code how to use each event that I mentioned.
// Using on-change
// You'll notice that this only 'fires off' when your cursor LEAVES the input field
$("#rate1").on("change",function() { $(this).next().html("<= Changed"); });
// Using on-keyup
// You'll notice that this only 'fires off' when the key you pressed is released, not when it is pressed
$("#rate2").on("keyup",function() { $(this).next().html("<= Changed"); });
// Using on-keydown
// You'll notice that this only 'fires off' when a key is pressed
$("#rate3").on("keydown",function() { $(this).next().html("<= Changed"); });
.label { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<input type="text" style="width: 40px;" class="change" name="rate" id="rate1" value="1" />
<span class="label"></span><br />
<input type="text" style="width: 40px;" class="keyup" name="rate" id="rate2" value="1" />
<span class="label"></span><br />
<input type="text" style="width: 40px;" class="keydown" name="rate" id="rate3" value="1" />
<span class="label"></span><br />
Something like keydown is best used when you're trying to see what key they entered before it goes into the input. I usually use this to see if the enter key was pressed.
Hope this helps!

Comparing 2 inputs with jquery

hello im trying to just compare what is inside of 2 different inputs.
$(document).ready(function() {
$('#pc').keydown(function() {
if ($('#ps').val() == $('#pc').val()) {
alert("it worked ");
}
});
});
<form id="identicalForm" class="form-horizontal" action="userSignup.php" method="post">
<fieldset>
<div id="legend">
<legend class="">Register</legend>
</div>
<div class="control-group">
<label class="control-label" for="email">E-mail</label>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input id="ps" name="password" placeholder="" class="form-control input-lg" type="password">
<p class="help-block">Password should be at least 6 characters</p>
</div>
</div>
<div class="control-group ">
<label class="control-label" for="password_confirm">Password (Confirm)</label>
<div class="controls">
<input id="pc" name="password_confirm" placeholder="" class="form-control input-lg" type="password">
<p class="help-block">Please confirm password</p>
</div>
</div>
</fieldset>
</form>
This is a semi condensed version of the web page. the inclusion is at the top of the page. if i put the alert outside of the if, it will do a pop up every time i type in that input box. but if i try to compare the two input fields nothing pops up when they both have the same password entered. from what ive seen from other SO post like this, it should work! I am still a novice with js, so i may just be over thinking this entirely.
The reason it wasn't working with the keydown event is because the event is only fired when the key is down. In other words, the event was being fired before the value was updated. You would be comparing 12345 with 1234 and even though the values would be the same, it wasn't recording the last character that was pressed.
Rather than using the keydown event, use the input or keyup event:
$('#pc').on('input', function() {
if ($('#ps').val() === $('#pc').val()) {
console.log("it worked ");
}
});
The keyup event is fired when the key is up, which means that the value of the element is actually updated. Similarly, the input event will behave the same way since it will be fired when the value changes. In addition, the input event will also catch paste events (which may be useful).
Instead of keydown, which actually executes before you press the key, use either blur or keyup:
$('#pc').on('blur', function() {
if ($('#ps').val() == $('#pc').val()) {
console.log("it worked ");
}
});
Use the keyup event. Also try to use === for comparing the values as we know the values are going to be both text type and do not need an explicit conversion before comparing.
$(document).ready(function () {
$('#pc').keyup(function () {
if ($('#ps').val() === $('#pc').val()) {
alert("it worked ");
}
});
});
The keyup event is sent to an element when the user releases a key on the keyboard.
Here is a working sample

Categories

Resources