I have a TextBoxcontrol in my web form, where in I display Height & Width of certain product.
Now I display this as follows :
As you can see, I append a " to show inches, in the string in the following way :
txtH.Text = arrHW[i].ToString() + "\"";
Now, this causes problem while editing! As the user can never always be sure of correctly editing the field by editing the number only and not the " symbol.
I need someway either through JavaScript or C#, that removes the symbol " while the user clicks on the textbox and removes as the focus is changed.
I tried this method, but it doesn't seem to work!
protected void txtH_TextChanged(object sender, EventArgs e)
{
string height = txtH.Text;
char[] splitArr = { '"' };
string[] editH = height.Split(splitArr);
for (int i = 0; i < editH.Length; i++)
{
if (editH[i].ToString().Equals("\""))
{
editH[i].Remove(i);
}
}
}
This is the designer code for the textboxes :
<asp:PlaceHolder ID="plcHW" runat="server">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-arrows-v"></i> Height</span>
<asp:TextBox ID="txtH" runat="server" Width="60px" CssClass="form-control" OnTextChanged="txtH_TextChanged" />
<span class="input-group-addon"><i class="fa fa-arrows-h"></i> Width</span>
<asp:TextBox ID="txtW" runat="server" Width="60px" CssClass="form-control" />
</div>
</asp:PlaceHolder>
You can clear the text box as soon as the focus is on it then add" after the user adds the value to it! This is one way of doing it!
var prev="";
$('#HEIGHT').focus(function() {
prev=$(this).val();
$(this).val(prev.replace("\"", ""));
}).blur(function() {
if($(this).val()==""){
$(this).val(prev)
}
else{
$(this).val($(this).val()+"\"");
}
});
Without any jquery:
(function($el) {
"use strict";
$el.addEventListener("focus", adjust, true);
$el.addEventListener("blur", adjust, true);
function adjust($e) {
var e = $e.type;
if (e === "focus") $el.value = $el.value.replace(/\"/g, "");
if (e === "blur") $el.value = $el.value + '"';
}
})(document.getElementById("height"));
http://jsfiddle.net/dlizik/5cb7g8te/
You can do it as
$(document).ready(function(){
$("TextBoxId").focus(function(){
var tval = $(this).val();
$(this).val(tval.replace(/\"/g, ""));
});
$("TextBoxId").focusout(function(){
var tval = $(this).val();
$(this).val(tval.replace(/\"/g, "")+ '\"');
});
});
I have tried solving your issue with this Fiddle: http://jsfiddle.net/akd7r31a/1/
$(document).ready(function(){
$('#username').focus(function(){
var txtValue = $(this).val();
var charTest = txtValue.substr(txtValue.length - 1);
if(charTest == '"'){
var showString = txtValue.slice(0, -1);
$(this).val(showString);
}
});
$('#username').focusout(function(){
var txtValue = $(this).val();
var charTest = txtValue.substr(txtValue.length - 1);
if(charTest != '"'){
var newVal = $(this).val() + '"';
$(this).val(newVal);
}
});
});
Related
Sometimes the event can be fired but sometimes nothing happen.
I have no idea why.
Below is my code for .aspx and javascript.
It does hit alert('register') everytime the page loads.
.aspx
<span class="searchInputContainer" data-moreresults="<%= SeeMoreText %>" data-noresult="<%= NoResultText %>">
<asp:TextBox ID="txtSearchNew" runat="server" CssClass="SearchTextBox" UseSubmitBehaviour="false" AutoPostBack="false" MaxLength="255" EnableViewState="False" aria-label="Search"></asp:TextBox>
<a class="dnnSearchBoxClearText" title="<%= ClearQueryText %>"></a>
</span>
JavaScript
document.addEventListener("DOMContentLoaded", fn);
function fn() {
alert('fn');
document.getElementById("<%= txtSearchNew.ClientID %>")
.addEventListener("keyup", function (event) {
event.preventDefault();
if (event.keyCode === 13) {
alert('enter');
redirectNew();
}
});
};
function redirectNew() {
alert('redirect');
var input = document.getElementById("<%= txtSearchNew.ClientID %>").value
var inputSplit = input.split(" ");
var param = "";
for (let i = 0; i < inputSplit.length; i++) {
if (i < (inputSplit.length - 1)) {
param += inputSplit[i] + "+";
}
else {
param += inputSplit[i];
}
}
alert('https://abc.local/index.php?search=' + param);
window.open('https://abc.local/index.php?search=' + param, 'searchTab');
}
Anyone has idea about it?
The process is simple:
Type text into a textbox
if the text matches a value in the dropdown list update the value.
If the text does not match a value in the dropdown list do postback using ASP.NET onTextChanged event. (Here lies the problem. The code below currently prevents postback in all instances)
HTML
<asp:DropDownList ID="d" runat="Server" AppendDataBoundItems="true"/>
<asp:TextBox ID="t" runat="Server" AutoPostBack="true" onchange="if(!test(this)) return false;"/>
JQUERY
$(function test() {
var d = ('#<%= d.ClientID%>'),
t = ('#<%= t.ClientID%>');
$(d + ',' + t).on('change', function () {
var val = this.value;
$(d + ' option').each(function () {
if (this.value == val) {
$(d + ',' + t).val(val);
return false;
}
return true;
});
});
});
This code works perfectly for updating the dropdown value.
The problem is this code prevents postback in all cases.
I think the problem is that onchange is fired from textbox and then the subsequent code inside the javascript onchange will not work.
Try javascript:return test() instead of if(!test(this)) return false;, like this
<asp:TextBox ID="t" runat="Server" AutoPostBack="true"
onchange="javascript:return test()"/>
and in JavaScript
function test() {
var d = document.getElementById('d'), t = document.getElementById('t');
var ddl = ('#d');
var txt = ('#t');
var val = t.value;
var len = $(ddl+ ' option[value=' + val + ']').length;
if (len > 0) {
d.value = t.value = val;
return false;
}
return true;
}
Update
Aspx
<asp:DropDownList ID="d" runat="Server" AppendDataBoundItems="true" onchange="javascript:return test('ddl')"/>
<asp:TextBox ID="t" runat="Server" AutoPostBack="true" onchange="javascript:return test('txt')" />
JavaScript
function test(temp) {
var d = document.getElementById('<%= d.ClientID%>'), t = document.getElementById('<%= t.ClientID%>');
var ddl = ('#<%= d.ClientID%>');
var txt = ('#<%= t.ClientID%>');
var val = t.value;
if (temp == "txt") {
var len = $(ddl + ' option[value=' + val + ']').length;
if (len > 0) {
d.value = t.value = val;
return false;
}
}
else {
t.value = d.value;
return false;
}
return true;
}
You can use __doPostBack instead.
post back when drop down list changed:
$(function() {
var d= $('#<%= d.ClientID%>');
d.removeAttr('onchange');
d.change(function(e) {
//You can decide when to post back
setTimeout('__doPostBack("<%= d.ClientID%>","")', 0);
});
});
or post back when textbox changed
$(function() {
var t= $('#<%= t.ClientID%>');
t.removeAttr('onchange');
t.change(function(e) {
setTimeout('__doPostBack("<%= t.ClientID%>","")', 0);
});
});
In the below code i have coded in page load.In this i have store regular expressions in hidRegExp.Value. Now i have to store this value in the hidden field.Now in javascript i have to validate the user input in textbox.But when i enter a value it shows blank alert.But i want to display the regular expression in alert.Pls help me to do this.
code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (FieldTypeInfo == FieldType.TextBox)
{
TblSearch.Visible = false;
TblDate.Visible = false;
tblDropd.Visible = false;
TblChk.Visible = false;
lblText.Text = FieldLabel;
//txtreq.Enabled = this.IsMandatory;
string strRegularExp = string.Empty;
if (ListOfRegularExpression != null)
{
for (int iRow = 0; iRow < ListOfRegularExpression.Count; iRow++)
{
strRegularExp += ListOfRegularExpression[iRow].ToString() + "~~";
hidRegExp.Value = strRegularExp;
if (iRow == ListOfRegularExpression.Count - 1)
{
strRegularExp = strRegularExp.TrimEnd("~~".ToCharArray());
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp('" + txtField.ToString() + "');");
}
}
}
hidRegExp.Value = strRegularExp;
lbl.Text = "The value of the HiddenField control is " + hidRegExp.Value + ".";
}}
code:
<script type="text/javascript">
function ValidateRegExp(txtInput) {
var hiddenValue = document.getElementById("<%=hidRegExp.ClientID%>").value;
alert("hiddenValue" + hiddenValue+".");
var mySplitResult = new Array();
mySplitResult = hiddenValue.split("~~");
for (i = 0; i < mySplitResult.length; i++) {
//document.write("<br /> Array[" + i + " ]= " + mySplitResult[i]);
var re = new RegExp(mySplitResult[i]);
if (txtInput.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
}
</script>
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState= "true" >
</asp:HiddenField >
<asp:Label ID="lbl" runat="server"></asp:Label>
Initially ListOfRegularExpression will be null so control will not enter into if (ListOfRegularExpression != null) and HiddenField.Value wont be set.
I have had the problem before. Honestly, I don't remember how I resolved it, but I tried a few things. Here they are:
For displaying the hidden field, add ClientIdMode as static on your hidden field like
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState="true" ClientIDMode="Static"></asp:HiddenField>
and in the JavaScript, use:
document.getElementById("hidRegExp");
If this does not work, try your approach with these below:
1) Try moving your hidden field before the script.
2) Try making it a label and use that in the JavaScript.
Hope this helps.
Per this code below, when users check a box, date is automatically inserted into a textbox control called cDate. This works great:
function ClickBox(cb) {
var tr = cb;
while (tr.tagName != "TR") {
tr = tr.parentNode;
if (tr == null) return; // something went wrong
}
var inps = tr.getElementsByTagName("input");
for (var i = 0; i < inps.length; ++i) {
var inp = inps[i];
if (inp.name.indexOf("cDate") >= 0) {
inp.value = rightDate();
break;
}
}
}
These are the affected controls:
<ItemTemplate>
<asp:CheckBox ID="myrecord" runat="server" onclick="ClickBox(this)" />
</ItemTemplate>
<ItemTemplate>
<asp:TextBox runat="server" style="border: none;" ID="cDate"></asp:TextBox>
</ItemTemplate>
The issue users are currently having is that once a checkbox is checked and date is inserted, only way to remove the inserted dates is the click the Reset button.
They would prefer to have the inserted dates disappear once a checked box is unchecked.
This modified code below isn't working. I am not getting any errors, however, whenever I am checking a box or unchecking it, nothing is happening - no date is getting inserted anymore.
function ClickBox(cb) {
var tr = cb;
var inps = tr.getElementsByTagName("input");
if(cb.checked == 1){ // CheckBox checked condition
while (tr.tagName != "TR") {
tr = tr.parentNode;
if (tr == null) return; // something went wrong
}
for (var i = 0; i < inps.length; ++i) {
var inp = inps[i];
if (inp.name.indexOf("cDate") >= 0) {
inp.value = rightDate();
break;
}
}
}
else{
for (var i = 0; i < inps.length; ++i) {
var inp = inps[i];
inp.value = '';
}
}
}
I am not sure what I am doing wrong.
Thanks for your assistance.
Here's a very simple solution that works for me:
ASP.NET Markup:
<div>
<asp:CheckBox ID="cbDate" runat="server" onclick="ClickBox(this)" />
<br />
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</div>
JavaScript:
function ClickBox(checkbox) {
var dateCheckbox = checkbox;
var dateTextBox = document.getElementById("txtDate");
if (dateCheckbox.checked === true) {
dateTextBox.value = "TODAY";
} else {
dateTextBox.value = "";
}
}
Hope this helps.
I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>