I am trying to use the typeWatch plugin for jQuery. I have this javascript:
<script type="text/javascript">
$(document).ready(function() {
var options = {
callback: function() { alert("a-ok! " + $(this).text); },
wait: 333,
highlight: true,
captureLength: 1
}
$("#customer").typeWatch(options);
});
</script>
And my view's HTML has this:
Method B: <%= Html.TextBox("customer") %>
With this test, if I type "ABC" in the textbox, I am expecting an alert to popup with "a-ok! ABC". Instead the following shows up...
a-ok! function (F) {
if (typeof F !== "object" && F != null) {
return this.empty().append((this[0] && this[0].ownerDocument ||
document).createTextNode(F));
}
var E = "";
o.each(F || this, function () {o.each(this.childNodes, function () {
if (this.nodeType != 8) {
E += this.nodeType != 1 ? this.nodeValue : o.fn.text([this]);}});});
return E;
}
I've tried changing the $(this).text to .val, and I've also tried referencing the input field more directly as $("#customer") but they yield similar results. How can I access just the entered text?
You should use the val() function on the textbox:
$(this).val();
Looking the code of typeWatch version 2.0 I found this:
function checkElement(timer, override) {
var elTxt = jQuery(timer.el).val(); <----------- !!! this...
// Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength
if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text)
|| (override && elTxt.length > options.captureLength)) {
timer.text = elTxt.toUpperCase();
timer.cb(elTxt); <-------------- !!! ...goes here.
}
};
timer.cb is the callback that you set up in the options. So you just add a parameter in that callback function that you use and that parameter will be the text from the input.
Related
input value to reflect the value in javascript input value to reflect the value in javascript input value to reflect the value in javascript input value to reflect the value in javascript
<div id="goodContent{{ entity.id}}" onclick="copyToClipboard();" style="display:none;">
{{ pdf_yolu }}
</div>
<div class="btn btn-default" id="clickCopy">Kopyala</div>
document.getElementById("clickCopy").onclick = function() {
copyToClipboard(document.getElementById("goodContent{{ entity.id}}"));
};
function copyToClipboard(e) {
var tempItem = document.createElement('input');
tempItem.setAttribute('type','text');
tempItem.setAttribute('display','none');
let content = e;
if (e instanceof HTMLElement) {
content = e.innerHTML;
}
tempItem.setAttribute('value',content);
document.body.appendChild(tempItem);
tempItem.select();
document.execCommand('Copy');
tempItem.parentElement.removeChild(tempItem);
}
This is not a Symfony issue as Symfony does not execute its own code on web browsers, which is where you need "copy to clipboard" functionality to run. (You should remove the Symfony tag from your question.) This is entirely JavaScript.
Consider a library such as ClipboardJS to do this. I can confirm it is usable on the front end templates of a Symfony based project.
In my case I had a table with many rows needing the 2nd column of each row to be copyable with a button. I wanted the button to appear in the first column. Here's the script I wrote:
Bare in mind I use other front end libraries too such as sprintf, jQuery, jQuery UI, Bootstrap 4, and FontAwesome. You should be able to adapt this though.
jQuery(document).ready(function($){
$('table').find('tr.js-copyable').each(function(k, v){
var $tr = $(v).first();
if ($tr.length != 1) {
return;
}
var $th = $tr.find('th').first();
if ($th.length != 1) {
return;
}
var $td = $tr.find('td').first();
if ($td.length != 1) {
return;
}
var value = $td.text();
if (typeof value != "string" || (value = value.trim()).length < 1) {
return;
}
var tdTooltip = function(text, icon){
if (typeof text != "string" || (text = text.trim()).length < 1) {
return;
}
if (typeof icon != "string" || (icon = icon.trim()).length < 1) {
icon = "";
}
$td.tooltip('dispose');
$td.tooltip({
html: true,
title: sprintf("<i class=\"fa %s\"></i><span>%s</span>", icon, text),
trigger: "manual",
placement: "left",
});
$td.tooltip('show');
setTimeout(function(){
$td.tooltip('hide');
}, 2000);
};
var $copyButton = $('<button class="btn btn-info js-copy js-tooltip" title="Copy to clipboard"><i class="fa fa-copy"></i></button>');
var clipboard = new ClipboardJS($copyButton[0], {
text: function(trigger){
$copyButton.tooltip('hide');
return value;
},
});
clipboard.on('success', function(e){
tdTooltip("Copied!", "fa-check-circle");
});
clipboard.on('error', function(e){
tdTooltip("Failed to copy.", "fa-times-circle");
});
$copyButton.appendTo($th);
});
});
Not one bit of the above has any wiff of Symfony about it. It's all JavaScript and associated front end libraries.
I have this code for autocomplete in an HTML input :
$("#myinput")
.bind("keydown", function(event) {
// don't navigate away from the field on tab when selecting an item
if (event.keyCode === $.ui.keyCode.TAB
&& $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
var results = [],
selectionStart = this.element[0].selectionStart
term = extractLast(request.term.substring(0, selectionStart));
if (term.length > 0) {
console.log(term);
if(/*input has string "where"*/)
results = $.ui.autocomplete.filter(table1, term);
else
results = $.ui.autocomplete.filter(table2, term);
}
response(results);
},
focus: function() {
return false; // prevent value inserted on focus
},
select: function(event, ui) {
var terms = split(this.value.substring(0, this.selectionStart));
terms.pop(); // remove the current input
terms.push(ui.item.value); // add the selected item
this.value =
$.trim(terms.join(" ") + this.value.substring(this.selectionStart)) + " ";
return false;
}
});
What I'm trying to do is if the input has string "where" in somewhere, then it will load autocomplete from table1, otherwise it will load from table2. How can I check if the input has that string? Thanks in advance.
You should use includes method.
var inputValue=$("#myinput").val();
if(inputValue.toLowerCase().includes("where")){
//rest of code
}
Another method is using indexOf method.
if(inputValue.indexOf("where")!==-1){
//rest of code
}
If you want to do this achievment using regex, you can use search method.
if(inputValue.search(/where/i)!==-1){
//rest of code
}
inputValue="awherea";
console.log(inputValue.search(/where/))
If you want the strongest browser support, use String#indexOf
if(this.value.indexOf('where') > -1) {
//doSomething
}
you can get your text value and use indexof to find it .
my_inp = $("#myinput").val();
if (my_inp.indexOf('where') > -1) {
console.log('yes');
}
Try with string#match method use the ternary operator for return true or false
And also Some of the More method
string.indexOf()
string.includes()
console.log('hello everyone'.match("hello") ? true : false)
For jquery you could use the contains() method
console.log($('p').is(':contains("hi")'))
console.log($('p').is(':contains("22")')) // not contains
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>hello hi</p>
I have a JS function that checks and restricts certain characters typed in input forms.
The code look like this:
var alphaOnly = /[sA-Za-z\söÖäÄüÜ]/g;
var alphaextraOnly = /[A-Za-z\-&/'"\öÖäÄüÜ]/g;
var alphadigitsOnly = /[sA-Za-z\söÖäÄüÜ\s1234567890]/g;
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var mailOnly = /[a-z\.#]/g;
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
It works when I add onkeypress to input like this:
<input type="text" class="span4 register_input" id="firma" name="firma" onkeypress="return restrictCharacters(this, event, alphaOnly);" />
But I want to do that with getElementById in the script. I tried to add this:
window.onload = function() {
document.getElementById("firma").onkeypress = restrictCharacters(this, event, alphaOnly);
}
But it didn't work... Help please.
You can't pass the arguments like that to onkeypress you would need to use a wrapper function
document.getElementById("firma").onkeypress = function (e)
{
return restrictCharacters(this,e,alphaOnly);
};
jsFiddle http://jsfiddle.net/BjU2e/5/
You are assigning to onkeypress the result of restrictCharacters(this,event,alphaOnly) instead of a function delegate. A correct version is in the following jsFiddle : http://jsfiddle.net/xL47r/1/
For future reference :
document.getElementById("firma2").onkeypress = function(e) {
return restrictCharacters(this,e,alphaOnly);
};
You can get this from e.target
document.getElementById("firma").onkeypress = function(e) {
restrictCharacters(e.target,e,alphaOnly);
}
document.getElementById("firma").onkeypress = function(){
return restrictCharacters.call(this/*becauseof 'this.blur()' */, this,event,alphaOnly);
};
You have wrong syntex to bind event with dom .here it is : window.onload = function () {
var ab = document.getElementById("firma");
ab.setAttribute("onkeypress", "restrictCharacters(this,event, true)");
}
I'm using JTube found over here: JTube at github
I'm trying to make a request on keyup instead of on submit. This is the script:
var qsParm = new Array();
function qs() {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0) {
var key = parms[i].substring(0,pos);
var val = parms[i].substring(pos+1);
qsParm[key] = val;
}
}
}
$(function() {
qs();
if(qsParm['search'] == '' || qsParm['search'] == null || qsParm['search'] == undefined)
qsParm['search'] = 'splinter cell';
else
qsParm['search'] = unescape(qsParm['search']);
$('input[name=search]').val(qsParm['search']);
$.jTube({
request: 'search',
requestValue: qsParm['search'],
limit: 10,
page: 1,
success: function(videos) {
$(videos).each(function() {
$('#example').append('<li><img src="'+this.thumbnail+'"><br>'+this.title+' - '+this.length+'</li>');
});
},
error: function(error) {
$('#example').html(error);
}
});
});
As far as I understand the function is ''qs'' So therefore I tried:
$("input").onkeyup(function(){
qs();
return false;
});
Did not work. I tried many other things with no success. Help is appreciated.
Change it to:
$("input").keyup(function(){
qs();
return false;
});
jQuery version of onKeyup is called keyup. In general onXXX are the DOM events and jQuery handlers simply do not have on in them.
You need to call the "sendQS" function (which is anonymous in your example) to actually send the data. Also, the jquery function is keyup not onkeyup.
function sendQS() {
qs();
if(qsParm['search'] == '' || qsParm['search'] == null || qsParm['search'] == undefined)
qsParm['search'] = 'splinter cell';
else
...
}
$("input").keyup(function(e){
sendQS();
return false;
});
Try something like this:
$('#target').keyup(function() {
alert('Handler for .keyup() called.');
});
I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
Your code currently gets the .val() for the first .required, from the .val() documentation:
Get the current value of the first element in the set of matched elements.
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
Or a bit more compact version:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
Try this jQuery selector:
$('.required[value=""], .required[value=0]')
You could also do it by defining your own custom jQuery selector:
$(document).ready(function(){
$.extend($.expr[':'],{
textboxEmpty: function(el){
return ($(el).val() === "");
}
});
});
And then access them like this:
alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection
So you could put a .each on them:
$('input.required:textboxEmpty').each(function(){
//do stuff
});