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

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.

Related

Jquery Error validation insert div using after() but cannot remove

I want to show error validation messages next to the textbox. For that, I have used after() function and inserted a div. But the div gets appended again and again whenever the field is invalid. I just want it once. Can anybody help me with it?
Here's my code:
$(document).ready(function()
{
$("#name").blur(function()
{
var name = $("#name").val();
var txt= /^[A-Za-z\s]+$/i ;
if((txt.test(name) != true))
{
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
$("#one").empty();
}
else
{
$("#one").remove();
}
});
});
You could use HTML 5 field's validity which is the standard.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Your error message here')"
onchange="setCustomValidity('')" />
You should use additional variable to store your state. Try this logic.
$(document).ready(function() {
var flag = false;
$("#name").blur(function() {
var name = $("#name").val();
var txt = /^[A-Za-z\s]+$/i;
if (!txt.test(name) && !flag) {
$("#name").after('<div id="one" style="color:#00aaff;">Invalid Name</div>');
flag = true;
}
else if (flag && txt.test(name)) {
flag = false
$("#one").remove();
}
});
});

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

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

How to disable the button if the input has no arrays?

I have the following in my HTML thing, The input value will be populated by the user selection and store the values in the format of array( 45[45, 6, 33], 67[67,2,5] and so on.. ). Basically the value would be like the following:
<input id="question_string" type="hidden" value="{}">
<input class="submit_updates" name="commit" type="submit" value="Process">
Now i need to disable the submit button or alert some messages like 'Select all values' if the input has no arrays in the {}.
Updated:
var question_hash_element = document.getElementById('question_string');
var question_hash = JSON.parse(question_hash_element.value);
var myArray = new Array();
myArray[0] = window.batch_question_id;
myArray[1] = window.answer_id || window.answer_text || window.batch_answer_checkbox
myArray[2] = window.build_id
This bit of above code store the values into the {}. I just want to disable and let the user to select all the fields to process the form. If the values are {}, the button should disabled. and any of the values inside and it should be enabled.
I have tried like the following:
$('.submit_updates').click(function () {
if ($('#question_string') == {}) {
return false;
alert("Select all the Values");
} else {
return true;
}
});
It's not working..
Any help would be appreciated! Thanks
$('.submit_updates').on('click', function (e) {
e.preventDefault();
if ( $.trim($('#question_string').val())=='{}' ) {
alert('no question !');
}else{
this.form.submit();
}
});
You are returning false before alerting the message.
Try this:
$('.submit_updates').on("click", function () {
if ($('#question_string').val() == "{}") { //Adjusted condition
//Alert message
alert("Select all the Values");
//Disable the submit button
$(".submit_updates").prop("disabled", true);
return false;
} else {
return true; //Not really needed
}
});
It is nicer to use on and prop instead of click and attr, as #adeneo suggests.
Try this
$(function(){
$('.submit_updates').on('click', function () {
if ($('#question_string').val() == "{}") {
$(this).prop('disabled', 'disabled');
alert("Select all the Values");
} else {
}
});
});
DEMO

Categories