jquery - Catch only new value in text input - javascript

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" />

Related

How to assgin two diffrent url with java script code

Below is a JS code , and i want to redirect user to two different URL - If he enter value in input box 1 so he should redirect to this Default url[https://manage.bagful.com.au/cart.php?a=add&pid=30] else he put more than 1 so this URL [https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]]
Here is the Code:
$(document).ready(function(){
document.getElementById("input").addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 1) {
var inputvalue = $("#input").val();
window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
}
});
$('#button').click(function(e) {
var inputvalue = $("#input").val();
window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
});
});
Please check and suggest the best idea.
Here you go with jsfiddle https://jsfiddle.net/Lfremy6z/1/
$(document).ready(function()
{
$('#submit').click(function(){
var inputVal = $('input[type="text"]').val();
if( inputVal == 1){
window.location.replace("https://manage.bagful.com.au/cart.php?a=add&pid=30");
}else{
window.location.replace("https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]=" + inputVal);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<button id="submit" type="submit">Submit</button>
In jsfiddle window.location is not present so I added the code here.
If you want to redirect the user after insert value then
Try this
$('#input').on('change',function(e) {
var inputvalue = $("this").val();
if (inputvalue == 1) {
window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
}else {
window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
}
});
I thing it will work for you.
try if else condition to dynamic the url :
document.getElementById("input").addEventListener("keyup", function(event) {
event.preventDefault();
var inputvalue = $("#input").val(),
url = (inputvalue == 1) ? 'https://manage.bagful.com.au/cart.php?a=add&pid=30' : 'https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]';
window.location.replace(url);
});

how to compare equals '=' in javascript

I am doing a calculator program in javascript and HTML. I have a button with a value '=' in it. In that one when a user click on "=" button in calculator. it should start evaluate the input he/she had given so far. But when a user click '=' button i tried to compare like this
$(".calcinput").click(function () {
var res = $(this).val();
if (res == '=') {
//code to handle when '=' is pressed;
}
}
but it didn't work please help me.
Your code is good enough to handle the event .. Just add an extra = in comapre
$(".calcinput").click(function () {
var res = $(this).val();
//if (res == '=') {
if (res === '=') {
//code to handle when '=' is pressed;
}
});
Next check where you used div or button or something else element to represent the button =
If it is button then use val() to extract the value
var res = $(this).val();
If the element is div then it could be innerHTML or innerTEXT
var res = $(this).innerHTML;
//Or
var res = $(this).innerText;
You can add an extra line to check whether you getting proper value of element
var res = $(this).val();
alert(res);
You can also use $(this).val() provided you have non empty value attribute in the button
HTML
<button class ="calcinput" type ="button">1</button>
<button class ="calcinput" type ="button">2</button>
<button class ="calcinput" type ="button" value="=">=</button>
JS
$(".calcinput").on('click',function(){
if($(this).val() === "="){
alert("equal");
}
})
WORKING FIDDLE
use
$(this).text()
to retrieve button text instead of
$(this).val()
in your code
= is text of button element and not value. Due to which .val() returns empty string. hence you need to use .text() instead of .val here:
$(".calcinput").click(function () {
var res = $(this).text();
if (res == '=') {
//code to handle when '=' is pressed;
}
});
check out this Demo . I have done a operation for ADD Simillarly you can do it for all operations ..keep it simple
A<input type="text" class="a" /><br/>
B<input type="text" class="b" />
<input type="button" class="calcinput" />
$(".calcinput").click(function () {
var res1 = $(".a").val();
var res2 = $(".b").val();
alert(parseFloat(res1) + parseFloat(res2));
});

Reselect checkboxes after Post in included file

I have page Search.asp (code below). And Filtered.asp which include Search.asp.
<%
Dim CheckForCheckboxes
CheckForCheckboxes = Request.form("chkBoxes")
response.write "CheckForCheckboxes" & CheckForCheckboxes
%>
<div id="ExSearch" name="ExSearch" >
<script>
// on page load check if this page called from POST and have passed checkboxes to select
var str = '<%=CheckForCheckboxes%>'; // {"Make[]":["AIXAM","CADILLAC","JEEP"],"selCountry[]":["5","4","8"]}
if (!str || str.length === 0) {} else {
var Checked = JSON.parse(str);
// alert works here
// This one not work
$("#ExSearch").find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () {
// alert do not work here
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);}
});
};
// from here function which select checkboxes and hold them in hidden input field before submit, on submit pass this object with form
$(function() {
$('div.list input[type=checkbox], input[type=radio]').on('change',onValueChange);
$('div.selector select').on('change', onValueChange);
function onValueChange() {
var Checked = {};
var Selected = {};
// Hold all checkboxes
$('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (typeof (Checked[name]) === 'undefined') {Checked[name] = [];}
Checked[name].push($el.val());
});
// Hold all dropdowns
$('div.list select').each(function () {
var $el = $(this);
var name = $el.attr('name');
if (!!$el.val()) {Selected[name] = $el.val();}
});
// Put all together to POST
$.ajax({
url: '/Search.asp',
type: 'POST',
data: $.param(Selected) + "&" + $.param(Checked),
dataType: 'text',
success: function (data) {
// Put response data to page and reselect checkboxes, this works good
$("#ExSearch").html(data).find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () {
var $el = $(this);
var name = $el.attr('name');
var value = $el.attr('value');
if (Checked[name] && Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);}
if (Selected[name]) {$el.val(Selected[name]);}
});
// Hold converted object to string values
$("<input type='hidden' value='' />").attr("id", "chkBoxes").attr("name", "chkBoxes").attr("value", JSON.stringify(Checked)).prependTo("#ajaxform");
}
});
};
});
</script>
<form name="ajaxform" id="ajaxform" action="Filtered.asp" method="POST">
</form>
</div>
So If page Search.asp starting I check if object passed via form post method, and if passed I need to select checkboxes which is in this object.
So I create object, then I convert it to string with Json.stringify and then catch form post string and convert back to object with JSON.parse
So everything look ok but checkboxes is not selecting and no errors appears.
What now is wrong?
Note what your code loading first and then loading your all divs so $("#ExSearch").find( cant find any checkboxes.
Try to put your <script></script> code after </form>

Insert keypress in input value

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">

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.

Categories