I tried to comment on the existing post, however I cannot until I have at least 50 'Reputation'.
The question I have is very much the same but my form submits to it's self. I wanted to use JavaScript to detect form data and display it if present, but inset a file if not.
The default action is to insert one of several 'Inserts'. Originally I had the form post to a separate ASP classic processor, but I want it all contained on the same ASP document.
In psudo, I want {If Form then Print Data Else Print 'Welcome' insert).
My psudo above is more VBScriptish, but it's a JavaScript function I want (If (Form.Data==True){Do Nothing}else{SetInset('Welcome.asp');)
I do hope that's a readable question. As I say, much the same question as above link. I'm just kinda trying to justify the question.
<body onload="goSec();AutoRun()">
function AutoRun(){
setAppDiv('AboutUs.asp', 'apDiv1');
}
function chkQryInsert() {
var z=document.location.search;
var zx=z.substr(1);
var params = {}, queries, temp, i, l;
// Split into key/value pairs
queries = zx.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
if (temp[0]=='Insert'){
setAppDiv(temp[1],'apDiv1');
}
else{
setAppDiv('AboutUs.asp', 'apDiv1');
}
}
}
Why not intercept the post using a button and process your answers before posting back to the server, makes more sense.
Just set the button's onClick event to the name of a JavaScript function. In the JavaScript function you can include a document.forms["myform"].submit();.
To take this a step further you could also include something like this to allow a level of Ajax like functionality, loading an ASP partial page into a particular div.
-- EDIT --
Also, consider best practice when you want to join different forms together - is it really worthwhile doing that? I always separate my mark-up and script from each other; it makes it immeasurably more readable.
Related
I'm writing a chrome extension that will add helper text instructions/reminders to specific location in the "new order" form we use at work. I'm really new to coding (basically using this project as a way to learn). I've created something that works - but I'm convinced there's a more elegant solution that I just haven't been able to figure out.
var helpText = "this is the message"
var customAlert = makeAlert(helpText) //create html container for msg
function makerAlert(helpText){...} //createElem, add class/style, append children
I'm okay with that bit (above). But should i be storing information on each message in objects instead? why would/wouldn't i? what information would go in it?
function alertPlacer(customAlert){
var par = document.getElementsByClassName("class-name")[i];
var sib = par.childNodes[j];
par.insertBefore(customAlert, sib);
};
really struggling with this bit (above). I have actually made alertPlacer() functions for each message because i can't figure out how to create a function that will take different class name & index parameters. should i be breaking this up more? if i stored these bits of info in an object, would that be useful?
relevant info:
because the target locations are within a form, almost nothing has an "id" attribute. so i have to use getElementsByClassName & an index.
for each message, I know the target parent className & index and the child node index to "insert before".
i would like to stick with javascript-only solution.
functions can take multiple arguments:
function alertPlacer(customAlert,className,parIndex,childIndex){
var par = document.getElementsByClassName(className)[parIndex]; var sib = par.childNodes[childIndex];
par.insertBefore(customAlert, sib);
};
And you call your function like
alertPlacer(yourAlert,"class-name",6,9);
I'm working on a long, long user form which will then lead to a customized display.
The final display has to be curated, paragraph by paragraph, to fit the user's input.
My first attempt was all if statements:
if($input_a && $input_b && $input_c !== $input_d) :
echo result;
if($input_a === 'example') :
return false;
endif;
if($input_b !== 'example') :
echo $input_c * $input_d;
endif;
endif;
This got very messy, especially when I had to pass the results of this logic between JS and PHP.
My next attempt involved building a custom string for each user, based on some of the inputs ('x' means no input):
$code = array('x', 'x', 'x', 'x', 'x', 'x');
if($input_a && $input_b && $input_c !== $input_d) :
$code[0] = 1;
$code[1] = 1;
if($input_a === 'example') :
$code[2] = 1;
else:
$code[2] = 0;
endif;
if($input_b !== 'example') :
$code[3] = 1;
else :
$code[3] = 0
endif;
else :
$code[0] = 0;
$code[1] = 0;
endif;
So, in the above, the string would read something like '01x0'. Now I can assign the user this code, based on their input. Further along in the logic, I can check against this code to decide whether to serve some blocks of content or hide others.
If I want to check for a match on the first and fourth inputs, but don't care about the second and third, I can do this:
// 'x' is a placeholder for code items I don't care about
$result_option = '1xx1';
$pattern = '/[' . $code[0] . 'x][' . $code[1] . 'x][' . $code[2] . 'x]/';
if(preg_match($pattern, $result_option) :
echo $result_option;
endif;
Ok, so this works.
But I feel like I'm reinventing the wheel here and eventually my code string is going to be a hundred characters long.
Are there better ways to serve customized content based on hundreds of user options that doesn't involve a hundred classes of nested if statements?
Edit:
So just to be clearer on what I'm trying to accomplish, let's say fills in the form. They say they own a house and a car and they have a lot of debt.
For that user, I want to show them content about dealing with debt, and that's it.
Another user fills in the form. They say they rent and they lease a car and they have moderate debt.
For that user, I want to show the same debt content, slightly modified because their debt is less extreme. In addition to that, I want to show content on buying a house and the benefits of buying a used car.
Each user has a unique combination of attributes, and for each attribute, custom content is served.
I agree with Kyle - insert into a database and then create a class to handle the data manipulation that queries the new DB record(s).
In a simple example:
User enters all data on a form on a page
User submits form
On the subsequent page, the first thing you do is create a new record (or records) in a MySQL table and get the newly-created ID
for the record(s)
Now you can have a class or set of classes to handle each data point or data set
I'm not super clear on your end objective, but I might use a template page that instantiates the above-referenced class and, for each data point I want to display, I call a function in that object to do the business logic. It's not necessarily a better solution than just using the $_POST data directly, but for me such an approach helps me break down the task logically and in a clean, simplified fashion.
(NOTE: this should solve the nested 'if's but may not shorten your code per-se.)
UPDATE:
I actually do something similar to what you're talking about but with much less custom content and I use a .txt template file and then basically parse it.
The template (which is static):
<p>
Hi {recipientFname},<br>
{senderFname} has nominated you for membership into blah blah. As per your conversation with him, visit the site by following the below URL for your next steps.<br><br>
{choiceLines}
</p>
Then I have a class that does all the muscle work, but the important part is here:
$arr_tpl_vars = array('{salutation}',
'{directMessage}',
'{referralMessage}',
'{senderFname}',
'{parentFname}',
'{parentLname}',
'{memberFname}',
'{memberLname}',
'{recipientFname}'
);
$arr_tpl_data = array($this->recipient_salutation,
$directMessage,
$referralMessage,
$this->sender_fname,
$this->parent_fname,
$this->parent_lname,
$this->memberFname,
$this->memberLname,
$recipFname);
$msg = str_replace($arr_tpl_vars, $arr_tpl_data, $msg_tmpl);
With the above code, I basically load in the template, feed it the array of strings to look for (all the replaceable content is denoted by {string} ) and the function replaces everything.
In your case, I'd define the text to use (ex: $this->recipient) in business logic functions...
I need to write a Javascript function that run from Master page, to find a ModalPopup in the contenct page and close it. Following code works, but not what I want. I need use something like mpeEditUser.ClientID, but I got an error. Also, it would be nice if I could find a ModalPopup without knowing its id, by its type (ModalPopupExtender) instead. Any suggestion?
function CloseModalPopup() {
var mpu = $find('ctl00_ContentPlaceHolder1_mpeEditUser');
mpu.hide();
}
Here is my solution: (If you see any problem, please let me know. Thanks)
I get the ModalPopup id in the codebehind, and pass it to my javascript function.
In the Page_Load of the default.master.cs:
ContentPlaceHolder cph = (ContentPlaceHolder)FindControl("ContentPlaceHolder1");
string sMpeID = (AjaxControlToolkit.ModalPopupExtender)cph.FindControl("mpeEditUser");
In my Javascript function:
var mpe = $find('<%=sMpeID%>');
if (mpe != null) {
mpe.hide();
}
Its likely the tag is getting mucked up by being called through another page, this happened to me. I don't know the best fix for you, however the way I addressed the issue was to first find the mpe through a javascript function that looked for a vague match out of all of the elements on the page.
var elemets = document.getElementsByTagName("*");
var mpe;
for (var i = 0; i < elemets.length; i++) {
var id = elemets[i].id
if (id.indexOf("mpe") >= 0) {
mpe = elemets[i];
}
}
If you have more then one mpe on the page you may want to match more if the string. For me the elements function only returned about 50 elements, so it was not too much overhead. That may not be the case for you, but even if you dont use this function in the final product it will assist you in discovering the actual ID of the elment.
I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!
You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later
You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?
I have a question i don't know how to start with...
We all know that DOM elements have their own events such as 'onChange'. Well a TextBox can fire onChange events and anyone can register to them.
I have a .NET usercontrol with 2 textboxes (country code + phone). The textboxes are validated using a .NET CustomValidator. I have server-side methods to handle the control such as 'Value' witch gives-me a unique string with cc+phone.
What about client side? ...
I would like to wrap around the 2 textboxes and the customvalidator in a "javascript control". I would love to create functions to work with my control as an unique entity.
What i would like to do was things like:
var x = document.getElementById('myControlId'); // where my control id was the wrap around
x.value("+351875647356); // witch will fill the two text boxes respectively.
Is this possible? What the way to follow?
Thank U All.
It's possible to do wnat you want by creating a javascript object ala a c#/vb.net 1class to represent your control. Your javascript instance would keep references to the individual elements and you would use custom methods to do the heavy lifting.
<script>
function MyUserControl (ccID, phoneID) {
// set references to elements
var _ccInput = document.getElementById(ccID);
var _phoneInput = document.getElementById(phoneID);
this.setValues = function (value) {
// TODO process your input here
// _ccInput.value = ... ;
// _phoneInput .value = ... ;
}
}
</script>
You could create a new instance of the object by generating the javascript from the server side.
string script = string.format("var myControl = new MyUserControl('{0}','{1}');",
ccTextbox.ClientID, phoneTextbox.ClientID);
ClientScript.RegisterStartupScript(this.GetType(), "uniqueKeyName", script, true);
after it's created on the client side, you can reference it from some javascript.
<script>
myControl.setValues("+351875647356");
</script>