Using onChange event and sending two objects as parameter gets me undefined - javascript

I made a simple function that depending on the text of the item selected from a dropdownlist, a textbox will change its maxlength property.
function cambiarLength(drop, textbox) {
var option = document.getElementById(drop);
var texto = option.options[option.selectedIndex].text;
var field = document.getElementById(textbox);
if (texto == 'RUC') {
field.maxLength = 3;
}
else {
field.maxLength = 6;
}
};
Codebehind:
TipoDoc.Attributes.Add("onChange", "javascript: cambiarLength(this, txtDoc);");
Error:
0x800a1391 - JavaScript runtime error: 'txtDoc' is undefined
Image

If txtDoc is the literal id of the field, then it needs to be treated as a string. You should also remove the javascript: prefix as that will disallow this to be recognized in your routine.
TipoDoc.Attributes.Add("onChange", "cambiarLength(this, 'txtDoc');");
See here regarding the use of the javascript: prefix:
When is the 'javascript:' prefix valid syntax?
UPDATE
If you're using WebForms then you will want to use the ClientID, for example, if txtDoc is literally your code-behind control, you should do:
TipoDoc.Attributes.Add("onChange", "cambiarLength(this, '" + txtDoc.ClientID +"');");

Related

AngularJS bind and replace text [duplicate]

I'm new to AngularJS and trying to create a simple app that will allow me to upload files to my Laravel driven website. I want the form to show me the preview of what the uploaded item will look like. So I am using ng-model to achieve this and I have stumbled upon the following:
I have an input with some basic bootstrap stylings and I am using custom brackets for AngularJS templating (because as I mentioned, I am using Laravel with its blading system). And I need to remove spaces from the input (as I type it) and replace them with dashes:
<div class="form-group"><input type="text" plaeholder="Title" name="title" class="form-control" ng-model="gnTitle" /></div>
And then I have this:
<a ng-href="/art/[[gnTitle | spaceless]]" target="_blank">[[gnTitle | lowercase]]</a>
And my app.js looks like this:
var app = angular.module('neoperdition',[]);
app.config(function($interpolateProvider){
$interpolateProvider.startSymbol('[[').endSymbol(']]');
});
app.filter('spaceless',function(){
return function(input){
input.replace(' ','-');
}
});
I get the following error:
TypeError: Cannot read property 'replace' of undefined
I understand that I need to define the value before I filter it, but I'm not sure where to define it exactly. And also, if I define it, I don't want it to change my placeholder.
There are few things missing in your filter. First of all you need to return new string. Secondary, regular expression is not correct, you should use global modifier in order to replace all space characters. Finally you also need to check if the string is defined, because initially model value can be undefined, so .replace on undefined will throw error.
All together:
app.filter('spaceless',function() {
return function(input) {
if (input) {
return input.replace(/\s+/g, '-');
}
}
});
Demo: http://plnkr.co/edit/5Rd1SLjvNI18MDpSEP0a?p=preview
Bravi just try this filter
for eaxample {{X | replaceSpaceToDash}}
app.filter('replaceSpaceToDash', function(){
var replaceSpaceToDash= function( input ){
var words = input.split( ' ' );
for ( var i = 0, len = words.length; i < len; i++ )
words[i] = words[i].charAt( 0 ) + words[i].slice( 1 );
return words.join( '-' );
};
return replaceSpaceToDash;
});
First, you have to inject your filter in you module by adding it's name to the array :
var app = angular.module('neoperdition',['spaceless']);
Secondly, the function of the filter have to return something. The String.prototype.replace() return a new String. so you have to return it :
app.filter('spaceless',function(){
return function(input){
return input.replace(' ','-');
}
});
Edit: dfsq's answer being a lot more accurate than mine.

Getting javascript to pull array value from hidden input?

How can I get the array value from a hidden input field and be able to grab the elements I need?
<input type="hidden" name="digital_object[prdcls][0][prdcl_links][0][_resolved]" id="digital_object[prdcls][0][prdcl_links][0][_resolved]" value="{"id":"/prdcl_titles/1","title":"test (test)","primary_type":"prdcl_title","types":["prdcl_title"],"json":"{\"lock_version\":0,\"title\":\"test (test)\",\"publication\":\"test\",\"publisher\":\"test\",\"created_by\":\"admin\",\"last_modified_by\":\"admin\",\"create_time\":\"2016-06-07T13:20:46Z\",\"system_mtime\":\"2016-06-07T13:20:46Z\",\"user_mtime\":\"2016-06-07T13:20:46Z\",\"jsonmodel_type\":\"prdcl_title\",\"uri\":\"/prdcl_titles/1\"}","suppressed":false,"publish":false,"system_generated":false,"repository":"global","created_by":"admin","last_modified_by":"admin","user_mtime":"2016-06-07T13:20:46Z","system_mtime":"2016-06-07T13:20:46Z","create_time":"2016-06-07T13:20:46Z","uri":"/prdcl_titles/1","jsonmodel_type":"prdcl_title"}">
When I run this I get 'undefined' for valp.
I also have the issue where the function prdcl_link is not executing on the hidden field being created or changed.
$( document ).ready(function() {
$("#digital_object[prdcls][0][prdcl_links][0][_resolved]").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__volume_num_").on('keyup change', prdcl_link);
$("#digital_object_prdcls__0__issue_num_").on('keyup change', prdcl_link);
function prdcl_link(){
var valp = {};
valp = $("#digital_object[prdcls][0][prdcl_links][0][_resolved]").val();
console.log(valp);
var valv = $("#digital_object_prdcls__0__volume_num_").val();
var vali = $("#digital_object_prdcls__0__issue_num_").val();
var res;
var pub;
var vol;
var iss;
if (valp!=""){
pub = valp['json']['publication'];
res = pub;
if (valv!=""){
vol = " - Volume " + valv;
res = res.concat(vol);
}
if (vali!=""){
if (valv!=""){
iss = ", Issue " + vali;
}
else {
iss = " - Issue " + vali;
}
res = res.concat(iss);
}
}
$("#digital_object_title_").val(res);
};
});
The value of the input seems to be JSON format, but HTML encoded. First you need to decode the string. Underscore have en unescape function, or you can search to find other ways to do it.
Then you can use JSON.parse to convert it to a javaScript object. But you have an error, so it can't be parsed. There are some extra quotes around an object named 'json'
...,"json":"{...}",...
If you didn't have the quotes around the brackets, it would be valid. What I think happened here is the 'json' object got converted to JSON format (a string) first. Then this string was part of another object, which also got converted to JSON. Now it's impossible to distinguish which quotes is part of what.

Adding a character on a string from a HTMLInput using javascript

I have this htmlInput in an ASP:Repeater that I want to be formatted in time format (e.g: 13:39) on its keypress. So far I have this code in repeater databound:
Protected Sub rpt_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rpt.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim txt As HtmlInputText = DirectCast(e.Item.FindControl("txtKmRun"), HtmlInputText)
If txt IsNot Nothing Then
txt.Attributes.Add("onkeypress", "return kmRun('" & txt.Value & "');")
End If
End If
End Sub
..and this is in the JavaScript:
<script>
function kmRun(myValue) {
String x = myValue;
x = x.substring(0, 2) + ":" + x.substring(2, x.length());
alert(x); //alert to test display but is not working
//HOW TO PASS x VALUE TO BACK TO THE TEXTBOX?
}
</script>
Tested the onkeypress attribute with a simple javascriptalert message and it worked but when modified with value passing, there's no return value. So I guess, the error starts there.
Additional question is when the javascriptpart works, how to return the "converted" string value back to the htmlInput? Is there any other solution for this problem that will not use a PostBack?
Thanks.
===================
This is the working code:
Protected Sub rpt_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rpt.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim txt As HtmlInputText = DirectCast(e.Item.FindControl("txtKmRun"), HtmlInputText)
If txt IsNot Nothing Then
txt.Attributes.Add("onkeypress", "return kmRun(this);")
End If
End If
End Sub
<script>
function kmRun(x) {
if (x.value.length > 2) {
x.value = x.value.substring(0, 2) + ":" + x.value.substring(2, x.value.length);
}
}
</script>
You don't need to declare another variable, you can use the myValue parameter.
I'd recommend to use onchange="kmRun(this)" instead onkeypress="kmRun(this)", because you got to change the content, to finally be formatted by the code.
By using this, you can get all attributes of the textBox control.
You might try something like this, in your javascript code:
function kmRun(control) {
control.value = control.value.substring(0, 2) + ":" + control.value.substring(2, control.value.length);
}
<input id="txt" type="text" onchange="kmRun(this)" value="" />
There are some problems with your logic.
You're sending txt.Value inside your ItemDataBound, but it will be a fixed value when rendered in your HTML, since it will not get updated when the user types. You must change that:
txt.Attributes.Add("onkeypress", "return kmRun(this.value);")
The keyword this above refers to your input, and whenever the user types, it will get updated.
Javascript is not a typed language, there is no String x = declaration. You must use:
var x = myValue;
You shouldn't use .substring(0, 2) directly without validating if the field has more than two characters, because if it doesn't, the browser will throw an error.
You're using .length as it was a method, but it's a property. Don't use the parenthesis ().
Finally, to pass the value back to your TextBox, you can do:
this.value = x;

Find and remove text from input value string

Our form has a hidden input that contains all the required values we send to the server for server-side validation. This is formed of a comma-separated string:
i.e. <input type="hidden" value="name,address,telephone,email">
We now have new inputs (i.e. website) that appear on a radio button check and I can successfully add these to the value="" string:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
$('input[name="required"]').val(nowReq + ',website');
}
But when a different radio is checked, I can't get it to remove ,website from the string.
I believe I need to grab the string, split it by comma, find and remove website and then re-join the string, but I'm not sure how to implement this (or if this is even the best way):
if ($('#fax').is(':checked')) {
var splitReq = nowReq.split(',');
// Something goes here?
$('input[name="required"]').val(nowReq2);
}
You can use string.indexOf(searchValue); and string.replace(oldValue, newValue); to search and remove non-selected elements or better pass Regular expression in the first parameter of string.replace(regex, newValue):
Non-regex Example:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
nowReq = nowReq + ',website';
}
else {
if(string.indexOf(',website') > -1) // If website is the last element
nowReq = nowReq.replace(',website', '');
else if(string.indexOf('website,') > -1) // If website is not the last element
nowReq = nowReq.replace('website,', '');
}
$('input[name="required"]').val(nowReq);
You simply need to remove the last element in your array and join it with the ',' character :
splitReq.pop();
$('input[name="required"]').val(splitReq.join(','));
Try:
var splitReq = nowReq.split(',website').join("");
the following would work in most cases:
var s = "name,address,telephone,email";
s = s.replace(",address", "").replace("address,", "").replace("address", "");
I'd suggest that you avoid parsing the value string, and simply recalculate the value on the change of the relevant input elements; the following is a demonstrative example because of the lack of information presented in the question (a more specific example could be provided if we can see your HTML, and current jQuery, rather than a description of it):
$('input[type="checkbox"]').on('change', function(){
var requiredString = $('input[type="checkbox"]').map(function(){
if (this.checked) {
return this.value;
}
}).get().join(',');
$('input[name="required"]').val(requiredString);
}).change();
JS Fiddle demo.
References:
change()
filter()
get()
map()
on()

Getting input text box value of display type "Number" in Client Side Java Script (CSJS)

I've been trying to get the value of input text box from Client Side like this:
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var CKQtyToDate = XSP.getElementById("#{id:CKQtyToDate}");
var SLQtyToDate = XSP.getElementById("#{id:SLQtyToDate}");
var FinishingQtyToDate = XSP.getElementById("#{id:FinishingQtyToDate}");
var PackingQtyToDate = XSP.getElementById("#{id:PackingQtyToDate}");
if ((parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value))>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value));
return false;
}
But I'm still having the result which is only string concatenation,how can i get through this thing???
First of all, in Javascript parseInt returns NaN when parsing an empty string. So make sure to test for empty strings before doing the calculation. You can test if the string can be parsed by using !isNaN(string).
I believe that your problem is that you concatenate strings in your alert box. I will suggest that you move the calculation to a seperate variable and then concatenate the message string with this variable in the alert box:
var result = parseInt(CKQtyToDate.value)+parseInt(SLQtyToDate.value)+parseInt(FinishingQtyToDate.value)+parseInt(PackingQtyToDate.value);
if (result>parseInt(hContractQty.value))
{
alert("Total qty more than contract qty! =" + result);
return false;
}

Categories

Resources