Insert keypress in input value - javascript

Hi i have a problem with insert value in input
You might ask why I did put keypress input field with JS?
I have the compiled program emscripten and it has driver input that intercepts all keypress, keydown, keyup and returns false for other element on page.
That blocks all input fields on page.
I have no way to fix this in the emscripten program, and I decided to fix it by jQuery on html side
jQuery(function() {
var $input = jQuery("#search-area228");
$input
.attr("tabindex", "0")
.mousedown(function(e){ jQuery(this).focus(); return false; })
.keypress(function(e){
var data = jQuery(this).val
var text = String.fromCharCode(e.keyCode || e.charCode)
for(var i = 0; i < text.length; i++)
jQuery(this).val(text[i])
return false; });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search-area228">
This will unlock the input field, but the problem is that allows you to write only one character and when you click on the following replaces it!
Please, help !

Just add the new text to the pre-existing text in that field which you already defined (in a wrong way) as data and didn't use it
when you call the method val of an input you should use it with braces jQuery(this).val() NOT jQuery(this).val because this is a function method of jQuery not a variable.
jQuery(function() {
var $input = jQuery("#search-area228");
$input
.attr("tabindex", "0")
.mousedown(function(e){ jQuery(this).focus(); return false; })
.keypress(function(e){
var data = jQuery(this).val();
var text = String.fromCharCode(e.keyCode || e.charCode)
for(var i = 0; i < text.length; i++)
jQuery(this).val(data + text[i])//<<< here
return false; });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search-area228">

Your code had little mistake.You were setting the value of the input to the current key instead of appending it to the current value of the input.
jQuery(this).val(jQuery(this).val() + text[i]);
This is the fixed version:
jQuery(function () {
var $input = jQuery("#search-area228");
$input.attr("tabindex", "0")
.mousedown(function (e) {
jQuery(this).focus();
return false;
})
.keypress(function (e) {
var data = jQuery(this).val
var text = String.fromCharCode(e.keyCode || e.charCode)
for (var i = 0; i < text.length; i++)
jQuery(this).val(jQuery(this).val() + text[i]);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-area228">

Related

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

jquery - Catch only new value in text input

I'm trying to create a JQuery method to tell me what the user writes in a text input. For example, if there's an input with the text foo and the user types in b I want to catch that. If the user types a afterwards, I want to catch only that a and not the ba.
How can I do that?
EDIT: I did it using this code:
$(".writetags").each(function(){
var elem = $(this);
elem.bind("keyup", function() {
elem.data("oldVal", $(this).data("newVal") || "");
elem.data("newVal", $(this).val());
var oldVal = elem.data("oldVal");
var newVal = $(this).val();
console.log("Was "+oldVal+" is "+newVal);
var newChar = newVal.charAt(newVal.length-1);
var oldChar = oldVal.charAt(oldVal.length-1);
console.log("The user just typed in "+newChar+" instead of "+oldChar);
});
});
this is a generic code that listen for all text input Changes in your web page:
$(document).ready(function() {
$("input[type=text]").change(function() {
$(this).data("oldVal", $(this).data("newVal") || "");
$(this).data("newVal", $(this).val());
console.log($(this).data("oldVal"));
console.log($(this).data("newVal"));
});
});
Thanks everyone, but I managed to do it using this code:
$(".writetags").each(function(){
var elem = $(this);
elem.bind("keyup", function() {
elem.data("oldVal", $(this).data("newVal") || "");
elem.data("newVal", $(this).val());
var oldVal = elem.data("oldVal");
var newVal = $(this).val();
console.log("Was "+oldVal+" is "+newVal);
var newChar = newVal.charAt(newVal.length-1);
var oldChar = oldVal.charAt(oldVal.length-1);
console.log("The user just typed in "+newChar+" instead of "+oldChar);
});
});
use the keyCode from the keypress event and use String.fromCharCode to get the character:-
$('input').keypress(function(event){
var character = String.fromCharCode(event.which || event.charCode || event.keyCode);
console.log(character);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

Javascript validation on select input

I am trying to make a javascript validating form, and am a bit stuck on validating drop down inputs (select)
I have been using this so far but am unsure on how to implement the validation to the select options, if anyone could give me some tips that would be great.
Edit: Also, how would I implement email validation, e.g containing #, thanks
Thanks
<input id="firstname" onblur="validate('firstname')"></input>
Please enter your first name
Thanks
http://jsfiddle.net/ww2grozz/13/
you need to handle select as follow
var validated = {};
function validate(field) {
// Get the value of the input field being submitted
value = document.getElementById(field).value;
// Set the error field tag in the html
errorField = field + 'Error';
// Set the success field
successField = field + 'Success';
if (value != '') {
document.getElementById(successField).style.display = 'block';
document.getElementById(errorField).style.display = 'none';
validated[field] = true;
} else {
document.getElementById(successField).style.display = 'none';
document.getElementById(errorField).style.display = 'block';
validated[field] = false;
}
}
function SimulateSubmit() {
// Query your elements
var inputs = document.getElementsByTagName('input');
// Loop your elements
for (i = 0, len = inputs.length; i < len; i++) {
var name = inputs[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
var all_select = document.getElementsByTagName("select"); // get al select box from the dom to validate
for (i = 0, len = all_select.length; i < len; i++) {
var name = all_select[i].id;
if (!validated[name]) {
// Call validate
validate(name);
// Prevent default
}
}
}
here the Working fiddle
using jQuery function
$('input').on('keyup', function() {
var isValid = $.trim($(this).val()) ? true : false;
// show result field is Valid
});
You must use <form> tag and set your action to it I have done that check this link and I have added select tag and set it to -1 by default for checking purpose while validating

change textbox value in client side and read it in server side

I have some textbox and I change the value of this textboxes in clientside (javascript) ,value was changed but when I read in server side after postback actually value not changed. my textbox isn't read only or disable.
notice that I use updatepanel and my postbacks is async.any idea to solve this issue?
update
I use this jquery to support placeholder in ie,but it cause value of my textboxes equal to placeholder value, and this conflict when my postback is async. for solving this problem I use below jquery code:
function EndRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
//alert('end');
$('input, textarea').placeholder();
var $inputs = $('.placeholder');
$inputs.each(function () {
var $replacement;
var input = this;
var $input = $(input);
var id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch (e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': $input,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
});
}}
function safeActiveElement() {
// Avoid IE9 `document.activeElement` of death
// https://github.com/mathiasbynens/jquery-placeholder/pull/99
try {
return document.activeElement;
} catch (err) { }}
function BeginRequestPostBackForUpdateControls() {
//*****************************For place holder support in ie******************************
if (runPlaceHolder != 0) {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder').each(function () {
var input = this;
var $input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
alert($(this)[0].value);
$(this)[0].value = '';
alert($(this)[0].value);
$input.removeClass('placeholder');
input == safeActiveElement() && input.select();
}
}
});
}}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestPostBackForUpdateControls);
prm.add_endRequest(EndRequestPostBackForUpdateControls);
});
I use this code to clear my textbox value before sending to server in add_beginRequest,and set value in add_endRequest (for placeholder in ie).
can anyone help solve this problem? thank you.
You changed the value of TextBox with javascript and the respective ViewState is not updated. You can use hidden field to store the value in javascript and get it in code behind.
Html
<input type="hidden" id="hdn" runat="server" />
JavaScript
document.getElementById("hdn").value = "your value";
Code behind
string hdnValue = hdn.Value;
Use hidden field to store the value, and retrieve it on the server side.

How do I input text via an HTML form and retrieve data from a JSON file as a response using Javascript?

I'm trying to make a little flashcard quiz game and I'm trying to implement a feature where someone can enter text into an input area and after they press enter the word "Correct" or "Incorrect" is flashed on the screen for 1 second before the input area is blank and the next question get loaded.
Here is a visual of what I am doing:
In particular, this is the HTML code that generates the input text area below:
<form id="answers">
<input type="text" name="inputtext" id="answer" style="width: 100%; height: 30px;" placeholder="Enter your answer..." onkeyup="checkAnswer(this,event);" autofocus><br>
</form>
This is the JSON file which is saved as: questionsAndAnswersItalian.json
[{"q":"What is the word for 'where' in Italian?","a":"Dove"},
{"q":"What is the word for 'when' in Italian?","a":"Quando"},
{"q":"What is the word for 'why' in Italian?","a":"Perché"}]
This is the javascript code that I've written which isn't working:
var jsonUrl = "questionsAndAnswersItalian.json";
var qs;
var numCards;
var maxIndex;
function checkAnswer(input, event){
if(event.keyCode == 13){
var answer = document.getElementById("answer").value.toLowerCase();
var questionNumber = 0;
for(var i = 0; i<jsonUrl.length; i++){
if(answer == jsonUrl[questionNumber]["a"].toLowerCase()){
setTimeout(correct_input, 1000);
input.value = "";
}else{
setTimeout(incorrect_input, 1000);
input.value = "";
}
questionNumber++;
}
}
}
function correct_input(){
input.value = "Correct!";
}
function incorrect_input(){
input.value = "Incorrect!";
}
function init() {
$.getJSON(jsonUrl, function(jsonObject) {
qs = jsonObject;
numCards = qs.length;
maxIndex = numCards-1;
displayCard();
});
}
The functions aren't working as I expected them to and I was wondering if someone could tell me where I am going wrong.
If you need more information to understand what I'm doing here please do not hesitate to ask!
Any help or advice would be much appreciated!
Thank you.
In this part :
for(var i = 0; i<jsonUrl.length; i++){
if(answer == jsonUrl[questionNumber]["a"].toLowerCase()){
setTimeout(correct_input, 1000);
input.value = "";
}else{
setTimeout(incorrect_input, 1000);
input.value = "";
}
questionNumber++;
}
You are looping through a String (jsonUrl), not your jsonObject. Use qs instead.
EDIT:
Here's a jquery code that works :
$('#answer').keyup(function(event) {
var code = event.keyCode || event.which;
if (code == 13) {
var answer = $(this).val().toLowerCase();
var goodAnswer = qs[currentCard].a.toLowerCase();
if (answer == goodAnswer) {
setTimeout(correct_input, 1000);
}
else {
setTimeout(incorrect_input, 1000);
}
$(this).val('');
}
});
Declare var currentCard = null; as global and set its value in displayCard() where I suppose you do a random or something like that.
With this code you have to remove onkeyup="checkAnswer(this,event);".
jsfiddle: http://jsfiddle.net/u7bkH/
the setTimeout function requires an asynchronous callback.
EDIT a more complete example, but note that it's only showing the way to correctly use setTimeout per your requirements. You'll need to complete with the appropiate check of correctness of the answer.
So, change your code to this
$('#answer').keyup(function(event) {
var code = event.keyCode || event.which;
if (code == 13) {
var input = $(this);
var answer = input.val().toLowerCase();
if (answer == "correct") {
input.val("Correct!");
}
else {
input.val("Incorrect!");
}
setTimeout(
function(){
input.val("");
},1000);
}
});

Categories