Javascript not pulling value from form - javascript

userName = Global.getComponent('centerRegion').UserName.getValue();
That code pops up with the error
{"browserEvent":"'Global.getComponent(...).UserName' is null or not an object","button":-1,"ctrlKey":false,"xy":[0,0]}
When I run it on this form:
Using Form As New WebControls.Forms.Form
With Form
.ID = "Test"
.ItemName = "connector"
With .Toolbar
.UseDefaultButtons = False
.AddButton(Forms.FormToolbar.ButtonType.Save)
.AddButton(Forms.FormToolbar.ButtonType.Cancel)
.AddButton("Test Connection", "testConnection", "icon-button-testconnection", , "Test")
End With
With .CenterRegion
.Id = "centerRegion"
With .AddFieldSet("Activate Service")
.Id = "activate"
.LabelWidth = 0
Dim cb As New Forms.Control("IsActive", "", "", Model.IsActive, Forms.Control.ControlType.CheckBox)
cb.BoxLabel = "Activate Service"
.AddControl(cb)
End With
With .AddFieldSet("Connection Parameters")
.Id = "params"
.LabelWidth = 150
.AddControl(New Forms.Control("UserName", "", "User Name", Model.UserName, Forms.Control.ControlType.TextField))
.AddControl(New Forms.Control("Password", "", "Password", Model.Password, Forms.Control.ControlType.Password))
.AddControl(New Forms.Control("LoginUrl", "", "URL", Model.LoginUrl))
End With
End With
Response.Write(.ToString)
End With
End Using
Everything shows up and saves correctly from the form on the screen, so the value IS there, but I think my Javascript is wrong to pull it.
Edit:
Generated HTML:
xtype:'fieldset'
,title:'Connection Parameters'
,id:'params',autoHeight:true
,titleCollapse:true
,border:true
,collapsible:false
,labelWidth:139
,anchor:'100%'
,items:[
{xtype:'textfield',validationEvent:'blur',enableKeyEvents:true,anchor:'100%',value:'IDWSSample',fieldLabel:'User Name',itemId:'UserName',name:'UserName',allowDecimals:false,decimalPrecision:0,validator:function(value){var isCustomValid = true;if (this.ux_isInitialized == true) {isCustomValid = function(value){if (value.match(/<[a-zA-Z!\/]{1}/)) return 'If using the "<" character, it must not be followed by "!" or "/" or any letter.';if (value.match(/.*&#.*/)) return 'If using the "&" character, it must not be followed by "#".';return true;}(value);if (typeof(isCustomValid) == 'string') return isCustomValid;}if (isCustomValid == null) isCustomValid = true;return isCustomValid;}}
,
{xtype:'textfield',validationEvent:'blur',enableKeyEvents:true,anchor:'100%',value:'TcYg7m*a',fieldLabel:'Password',itemId:'Password',name:'Password',allowDecimals:false,decimalPrecision:0,inputType:'password'
}
,
{xtype:'textfield',validationEvent:'blur',enableKeyEvents:true,anchor:'100%',value:'http://sample.idws.syndication.kbb.com/VehicleInformationService2008R2.svc?wsdl',fieldLabel:'URL',itemId:'LoginUrl',name:'LoginUrl',allowDecimals:false,decimalPrecision:0,validator:function(value){var isCustomValid = true;if (this.ux_isInitialized == true) {isCustomValid = function(value){if (value.match(/<[a-zA-Z!\/]{1}/)) return 'If using the "<" character, it must not be followed by "!" or "/" or any letter.';if (value.match(/.*&#.*/)) return 'If using the "&" character, it must not be followed by "#".';return true;}(value);if (typeof(isCustomValid) == 'string') return isCustomValid;}if (isCustomValid == null) isCustomValid = true;return isCustomValid;}}
,
{xtype:'combo_transform',validationEvent:'blur',enableKeyEvents:true,anchor:'100%',fieldLabel:'Market Value',id:'ddlMarketValues',itemId:'ddlMarketValues',name:'ddlMarketValues',allowDecimals:false,decimalPrecision:0,id:'EXT_ddlMarketValues'
,el:null
,typeAhead:true
,triggerAction:'all'
,transform:'ddlMarketValues'
,forceSelection:true
,selectOnFocus:true
,lazyRender:true
,resizable:true
,editable:false

View the resulting source code and check the name being generated by ASP.NET for centerRegion. Depending on your version of ASP.NET, there may be automatically-generated suffixes added to the name.
If that is the case, update the name to match that being generated and see if this fixes it.

Not sure where the Global.getComponents method is from, but my guess is you have a typo there OR you are not properly accessing the field value. Try finding the field with regular javascript or even easier with jQuery.
try:
var userName = document.getElementById('UserName').value;
or with jQuery:
var userName = $("#UserName").val();
...assuming 'centerRegion' and 'UserName' are id values of elements on your page.
If you're not using jQuery, then you can try the asp.net way:
var userName = $find('UserName','centerRegion').value;

Related

String Concatenation on vTiger field before save handler on Javascript (code inside)

in vtiger 6.5 i'm trying to achieve this: in the Contact Module, when the user inputs firstname, lastname and birthday, the js code should concatenate the 3 of them and put the result in the text field cf_1142.
I put this code in layouts/vlayout/modules/Contacts/resources/Edit.js
createUniqueId: function (){
var firstname = $("input[name='firstname']");
var lastname = $("input[name='lastname']");
var birthday = $("input[name='birthday']");
$(document).on('keyup',"input[name='firstname'], input[name='lastname', input[name='birthday']", function(){
if (firstname.val() != '' && lastname.val() != ''&& birthday.val() != ''){
var uniqueid = string.concat(firstname, lastname, birthday);
$("input[name='cf_1142']").val(uniqueid);
}
})
},
Then i added in the Edit.js into registerBasicEvents:
registerBasicEvents : function(container){
this._super(container);
this.registerReferenceSelectionEvent(container);
this.registerEventForCopyingAddress(container);
this.registerRecordPreSaveEvent(container);
this.creaIdentificativo();
}
I'm a novice and i tried to adapt other code that did a math calculation to make it work with string concatenation, but it doesn't. Can someone help me in correct it and tell me what i did wrong?
Thanks!
Why the name of your function is not the same that in the registerBasicEvents function?
createUniqueId: function (){
and
this.creaIdentificativo()

href appending current URL before navigating to new link

function setRedirect()
{
var redirectDest = "This is additional description <a href="http://opensourceforgeeks.blogspot.in/">Click Me</a>.";
if(redirectDest != null && redirectDest != '')
{
document.getElementById("RedirectDestElem").innerHTML = redirectDest;
}
}
redirectDest is populated from Spring controller. So the function is actually
function setRedirect()
{
var redirectDest = "${redirectDest}";
if(redirectDest != null && redirectDest != '')
{
document.getElementById("RedirectDestElem").innerHTML = redirectDest;
}
}
This appends current url base address to http://opensourceforgeeks.blogspot.in and then redirects. I dont want this to happen. I have to convert " to " in Java code (escape it) so that my java script does not break. Otherwise it will be
var redirectDest = "This is additional description Click Me.";
which will break.
Why don't you enclose redirectDest in single quotes?
var redirectDest = '${redirectDest}';
you can use the escape sequence "\"
so your text will be like below:
var redirectDest = "This is additional description Click Me.";

Jquery: Copy text from a form to a DIV while checking the last letter

On my HTML form, users can enter their name.
Their name will then appear in a DIV as part of a book title.
The book title uses apostrophe 's (e.g. Amy's Holiday Album).
If the user enters a name which ends in a S, I don't want the apostrophe s to appear.
(e.g. it should be Chris' Holiday Album instead of Chris's Holiday Album).
I also only want this to occur if the form has a class of apostrophe. If this class does not exist, then the name should be copied as is without any apostrophe or 's'.
I know you can use slice() to get the last character of an element, so I thought I could combine this with an if statement. But it doesn't seem to work.
Here is JSFiddle
Here is my HTML:
<div><b class="title"></b> Holiday Album</div>
Here is my Jquery (1.8.3):
$(document).ready(function() {
$('.name').keyup(function() {
var finalname = text($(this).val());
var scheck = finalname.slice(-1);
var finaltitle;
if ($(".apostrophe")[0]) {
if (scheck == 's') {
finaltitle = finalname + "'";
}
else {
finaltitle = finalname + "'s";
}
$('.title').text(finaltitle);
}
else {
$('.title').text(finalname);
}
});
});
text method is not needed on
var finalname = $(this).val();
check fiddle
Use
var finalname = $(this).val();
instead of
var finalname = text($(this).val());
Simplified version
$(document).ready(function() {
//Code fires when user starts typing:
$('.name.apostrophe').keyup(function() {
if (this.value.indexOf("'s") != -1 ) {
$('.title').text(this.value.replace(/'s/g, "'"));
} else {
$('.title').text(this.value)
}
}); /* Capture Personalised Message */
});
This will also replace all occurrences of the 's with ' only.
Hope it helps!.

Django - Reverse Engineering the Admin site's "Add Foreign Key" button

TL;DR (Short synopsis):
I have recreated the admin "Add" button in my own project. However, when I hit "save" on the parent form, it is not recognizing the new select element.
Whole Story:
I have that functionality working in my own project... almost. I need help figuring out the last step. As it is now, I have a "+" button, I click it, a popup shows up, I add a new object, hit save, popup closes and that new item is now in my select box and selected - just like the admin page. However, when I hit save on this parent form, I get the error that I've selected an item not in the list. Of course, since the page has reloaded, my new item is part of the list and I just hit save again and it works. Of course, I need it to save on the first time!
The basic setup is my Parent model is called System and the foreign key model is called Zone. The Zone model lists how many zones a system has (1 zone,2 zones,10 zones, etc...)
OK, some code:
The "Add" link in the template of the parent form:
Add
In my New_Zone view, after saving the new zone, I check if the popup GET variable is 1, if so, return a javascript function. Here's the view:
...
if form.is_valid():
f = form.save(commit=False)
pk_value = f.numOfZones
form.save()
obj = Zone_Info.objects.get(numOfZones=pk_value)
if isPopup == "1":
return HttpResponse('<script>opener.closeAddPopup(window, "%s", "%s");</script>' % (escape(pk_value), escape(obj)))
...
And here is my Javascript (largely copied from the admin javascript:
function html_unescape(text) {
// Unescape a string that was escaped using django.utils.html.escape.
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/"/g, '"');
text = text.replace(/'/g, "'");
text = text.replace(/&/g, '&');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAddPopup(triggeringLink, pWin) {
var name = triggeringLink.id.replace(/^add_/, '');
href = triggeringLink.href;
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function closeAddPopup(win, newID, newRepr) {
newID = html_unescape(newID);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
if (elem.nodeName == 'SELECT') {
var o = new Option(newRepr, newID);
elem.options[elem.options.length] = o;
o.selected = true;
} else if (elem.nodeName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newID;
} else {
elem.value = newID;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newID);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
I took a look at this question and it seems that I am doing precisely the same thing.
Any ideas on how to get that last step of getting the form to recognize the new select element?
Thanks!
I Figured it Out
The problem was what I was passing to my closeAddPopup javascript function. Essentially, I was passing garbage values.
Here's what I originally had in my New_Zone view (which didn't work):
...
if form.is_valid():
f = form.save(commit=False)
pk_value = f.numOfZones
form.save()
obj = Zone_Info.objects.get(numOfZones=pk_value)
if isPopup == "1":
return HttpResponse('<script>opener.closeAddPopup(window, "%s", "%s");</script>' % (escape(pk_value), escape(obj)))
...
It's a pretty stupid mistake on my part (clearly it's late). I was assigning f to the field numOfZones which I thought was the pk and sending that to the script.
Now, the working view looks like this:
if form.is_valid():
obj = form.save()
pk_value = obj.pk
if "_popup" in request.REQUEST:
return HttpResponse('<script>opener.closeAddPopup(window, "%s", "%s");</script>' % (escape(pk_value), escape(obj)))
Anyway... thanks to... well, Stackoverflow. I don't think I would have solved the problem without posting the question and rereading my code on stackoverflow.

How to add a parameter to the URL?

My current URL is: http://something.com/mobiles.php?brand=samsung
Now when a user clicks on a minimum price filter (say 300), I want my URL to become
http://something.com/mobiles.php?brand=samsung&priceMin=300
In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.
Note: If no parameters are set then the function should add ? instead of &
i.e. if the current URL is http://something.com/mobiles.php then page should be re-directed to http://something.com/mobiles.php?priceMin=300
instead of http://something.com/mobiles.php&priceMin=300
try something like this, it should consider also cases when you already have that param in url:
function addOrUpdateUrlParam(name, value)
{
var href = window.location.href;
var regex = new RegExp("[&\\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\\?])" + name + "=\\d+");
window.location.href = href.replace(regex, "$1" + name + "=" + value);
}
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
}
then you invoke it like in your case:
addOrUpdateUrlParam('priceMin', 300);
Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:
<script>
function addParam(v) {
window.location.search += '&' + v;
}
</script>
add priceMin=300
There is no need to check for ? as this is already the search part and you only need to add the param.
If you don't want to even make use of a function you can write as so:
add priceMin=300
Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.
Edit:
In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:
if the parameter already exists, it should be changed.
if the parameter already exists multiple times, only the changed copy should survive.
if the parameter already exists, but have no value, the value should be set.
As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:
<script>
function setParam(name, value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for(var r = x.exec(s); r; r = x.exec(s))
{
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/* set param */
params[name] = encodeURIComponent(value);
/* build search */
var search = [];
for(var i in params)
{
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */
l.search = search;
}
</script>
add priceMin=300
This at least is a bit more robust as it can deal with URLs like these:
test.html?a?b&c&test=foo&priceMin=300
Or even:
test.html?a?b&c&test=foo&pri%63eMin=300
Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.
if(location.search === "") {
location.href = location.href + "?priceMin=300";
} else {
location.href = location.href + "&priceMin=300";
}
In case location.search === "", then there is no ? part.
So add ?newpart so that it becomes .php?newpart.
Otherwise there is a ? part already.
So add &newpart so that it becomes .php?existingpart&newpart.
Thanks to hakre, you can also simply set it like:
location.search += "&newpart";
It will automatically add ? if necessary (if not apparent, it will make it ?&newpart this way, but that should not matter).
I rewrite the correct answer in PHP:
function addOrUpdateUrlParam($name, $value){
$href = $_SERVER['REQUEST_URI'];
$regex = '/[&\\?]' . $name . "=/";
if(preg_match($regex, $href)){
$regex = '([&\\?])'.$name.'=\\d+';
$link = preg_replace($regex, "$1" . $name . "=" . $value, $href);
}else{
if(strpos($href, '?')!=false){
$link = $href . "&" . $name . "=" . $value;
}else{
$link = $href . "?" . $name . "=" . $value;
}
}
return $link;
}
I hope that help's someone...
There is an more elegant solution available, no need to write your own function.
This will add/update and take care of any ? or & you might need.
var params = new URLSearchParams(window.location.search);
params.set("name", "value");
window.location.search = params.toString();
var applyMinPrice = function(minPrice) {
var existingParams = (location.href.indexOf('?') !== -1),
separator = existingParams ? '&' : '?',
newParams = separator + 'priceMin=' + minPrice;
location.href += newParams;
}
If you're having the user fill out a textfield with a minimum price, why not let the form submit as a GET-request with a blank action? IIRC, that should do just what you want, without any javascript.
<FORM action="" method="get">
<P>
<LABEL for="brand">Brand: </LABEL>
<INPUT type="text" id="brand"><BR>
<LABEL for="priceMin">Minimum Price: </LABEL>
<INPUT type="text" id="priceMin"><BR>
</P>
use var urlString = window.location to get the url
check if the url already contains a '?' with urlString.indexOf('?'), -1 means it doesnt exist.
set window.location to redirect
this is like 101 of javascript. try some search engines!
<html>
<body>
..
..
..
<?php
$priceMinValue= addslashes ( $_GET['priceMin']);
if (!empty($priceMin)) {
$link = "currentpage.php?priceMin=". $priceMinValue;
die("<script>location.href = '".$link. "'</script>");
}
?>
</body>
</html>

Categories